branch feature/optimize_application_swing_packages created (now 092be3f)
This is an automated email from the git hooks/post-receive script. New change to branch feature/optimize_application_swing_packages in repository observe. See https://gitlab.nuiton.org/codelutin/observe.git at 092be3f Move it all! This branch includes the following new commits: new 092be3f Move it all! The 1 revisions listed above as "new" are entirely new to this repository and will be described in separate emails. The revisions listed as "adds" were already present in the repository and have only been added to this reference. Detailed log of new commits: commit 092be3f55cddfa28d31867fb4c53c0e8c1fe9771 Author: Tony CHEMIT <chemit@codelutin.com> Date: Tue Aug 23 14:19:34 2016 +0200 Move it all! -- To stop receiving notification emails like this one, please contact codelutin.com SCM administrator <admin+scm@codelutin.com>.
This is an automated email from the git hooks/post-receive script. New commit to branch feature/optimize_application_swing_packages in repository observe. See https://gitlab.nuiton.org/codelutin/observe.git commit 092be3f55cddfa28d31867fb4c53c0e8c1fe9771 Author: Tony CHEMIT <chemit@codelutin.com> Date: Tue Aug 23 14:19:34 2016 +0200 Move it all! --- observe-application-swing/pom.xml | 6 +- .../java/fr/ird/observe/ObserveActionExecutor.java | 318 --- .../main/java/fr/ird/observe/ObserveAdminCLI.java | 58 - .../main/java/fr/ird/observe/ObserveCLAction.java | 399 ---- .../fr/ird/observe/ObserveOpenDataManager.java | 288 --- .../fr/ird/observe/ObserveResourceManager.java | 325 ---- .../main/java/fr/ird/observe/ObserveRunner.java | 650 ------- .../observe/ObserveSwingApplicationContext.java | 715 ------- .../ObserveSwingApplicationDataSourcesManager.java | 108 - .../fr/ird/observe/ObserveSwingBinderService.java | 50 - .../observe/ObserveSwingTechnicalException.java | 50 - .../java/fr/ird/observe/ObserveTextGenerator.java | 133 -- .../application/swing/ObserveActionExecutor.java | 318 +++ .../observe/application/swing/ObserveAdminCLI.java | 58 + .../observe/application/swing/ObserveCLAction.java | 399 ++++ .../application/swing/ObserveOpenDataManager.java | 288 +++ .../application/swing/ObserveResourceManager.java | 325 ++++ .../observe/application/swing/ObserveRunner.java | 648 ++++++ .../swing/ObserveSwingApplicationContext.java | 715 +++++++ .../ObserveSwingApplicationDataSourcesManager.java | 108 + .../swing/ObserveSwingBinderService.java | 50 + .../swing/ObserveSwingTechnicalException.java | 50 + .../application/swing/ObserveTextGenerator.java | 133 ++ .../ObserveSwingApplicationConfig.java | 1168 +++++++++++ .../ObserveSwingApplicationConfigOption.java | 943 +++++++++ .../ObserveSwingApplicationConfigProvider.java | 60 + .../observe/application/swing/db/DataContext.java | 778 ++++++++ .../swing/db/ObserveSwingDataSource.java | 723 +++++++ .../swing/db/constants/ConnexionStatus.java | 66 + .../swing/db/constants/CreationMode.java | 108 + .../swing/db/constants/DataContextType.java | 331 ++++ .../application/swing/db/constants/DbMode.java | 70 + .../db/event/ObserveSwingDataSourceEvent.java | 83 + .../db/event/ObserveSwingDataSourceListener.java | 75 + .../ObserveSwingDataSourceListenerAdapter.java | 56 + .../fr/ird/observe/application/swing/package.html | 27 + .../application/swing/ui/ObserveCommon.jcss | 94 + .../application/swing/ui/ObserveMainUI.jaxx | 341 ++++ .../application/swing/ui/ObserveMainUI.jcss | 474 +++++ .../application/swing/ui/ObserveMainUIHandler.java | 512 +++++ .../application/swing/ui/ObserveUICallback.java | 115 ++ .../application/swing/ui/ObserveUIMode.java | 43 + .../ird/observe/application/swing/ui/UIHelper.java | 595 ++++++ .../swing/ui/actions/AbstractObserveAction.java | 54 + .../actions/ChangeApplicationLanguageAction.java | 82 + .../swing/ui/actions/ChangeDbLanguageAction.java | 83 + .../swing/ui/actions/ChangeStorageAction.java | 97 + .../swing/ui/actions/CloseApplicationAction.java | 87 + .../swing/ui/actions/CloseHelpAction.java | 76 + .../swing/ui/actions/CloseStorageAction.java | 86 + .../swing/ui/actions/GotoSiteAction.java | 87 + .../ui/actions/ImportStorageFromFileAction.java | 105 + .../swing/ui/actions/LaunchAdminAction.java | 79 + .../swing/ui/actions/ReloadApplicationAction.java | 73 + .../actions/ReloadDefaultConfigurationAction.java | 95 + .../swing/ui/actions/ReloadResourcesAction.java | 109 ++ .../swing/ui/actions/ReloadStorageAction.java | 125 ++ .../swing/ui/actions/SaveStorageToFileAction.java | 92 + .../swing/ui/actions/ShowAboutAction.java | 126 ++ .../swing/ui/actions/ShowConfigAction.java | 500 +++++ .../swing/ui/actions/ShowStorageInfoAction.java | 81 + .../swing/ui/actions/StartH2WebServerAction.java | 100 + .../swing/ui/actions/StartServerModeAction.java | 127 ++ .../swing/ui/actions/StopH2WebServerAction.java | 82 + .../swing/ui/actions/StopServerModeAction.java | 105 + .../swing/ui/actions/shared/AbstractUIAction.java | 113 ++ .../ui/actions/shared/CancelCreateUIAction.java | 72 + .../ui/actions/shared/CloseAndCreateUIAction.java | 157 ++ .../swing/ui/actions/shared/CloseOpenUIAction.java | 173 ++ .../ui/actions/shared/DeleteDataUIAction.java | 80 + .../ui/actions/shared/DeleteReferenceUIAction.java | 74 + .../swing/ui/actions/shared/GoDownUIAction.java | 151 ++ .../swing/ui/actions/shared/GoUpUIAction.java | 129 ++ .../shared/MoveActivityLonglinesUIAction.java | 197 ++ .../actions/shared/MoveActivitySeinesUIAction.java | 192 ++ .../ui/actions/shared/MoveRoutesUIAction.java | 199 ++ .../actions/shared/MoveTripLonglinesUIAction.java | 85 + .../ui/actions/shared/MoveTripSeinesUIAction.java | 85 + .../swing/ui/actions/shared/MoveTripsUIAction.java | 197 ++ .../swing/ui/actions/shared/ReOpenUIAction.java | 103 + .../swing/ui/actions/shared/ResetEditUIAction.java | 69 + .../swing/ui/actions/shared/SaveEditUIAction.java | 69 + .../ui/actions/shared/SelectNodeUIAction.java | 62 + .../ui/actions/shared/SelectOpenNodeUIAction.java | 58 + .../swing/ui/admin/AdminActionModel.java | 38 + .../swing/ui/admin/AdminActionWorker.java | 57 + .../application/swing/ui/admin/AdminStep.java | 451 +++++ .../application/swing/ui/admin/AdminTabUI.jaxx | 208 ++ .../swing}/ui/admin/AdminTabUI.jcss | 0 .../swing/ui/admin/AdminTabUIHandler.java | 242 +++ .../application/swing/ui/admin/AdminUI.jaxx | 203 ++ .../{ => application/swing}/ui/admin/AdminUI.jcss | 0 .../application/swing/ui/admin/AdminUIHandler.java | 381 ++++ .../swing/ui/admin/AdminUILauncher.java | 275 +++ .../application/swing/ui/admin/AdminUIModel.java | 1493 ++++++++++++++ .../swing/ui/admin/config/ConfigUI.jaxx | 199 ++ .../swing}/ui/admin/config/ConfigUI.jcss | 0 .../swing/ui/admin/config/ConfigUIHandler.java | 186 ++ .../swing/ui/admin/config/SelectDataUI.jaxx | 87 + .../swing}/ui/admin/config/SelectDataUI.jcss | 0 .../ui/admin/consolidate/ConsolidateModel.java | 56 + .../swing/ui/admin/consolidate/ConsolidateUI.jaxx | 65 + .../swing}/ui/admin/consolidate/ConsolidateUI.jcss | 0 .../ui/admin/consolidate/ConsolidateUIHandler.java | 186 ++ .../swing/ui/admin/export/ExportModel.java | 179 ++ .../swing/ui/admin/export/ExportUI.jaxx | 89 + .../swing}/ui/admin/export/ExportUI.jcss | 0 .../swing/ui/admin/export/ExportUIHandler.java | 334 ++++ .../swing/ui/admin/export/TripEntry.java | 59 + .../ui/admin/export/TripToExportTableModel.java | 170 ++ .../swing/ui/admin/report/ReportConfigUI.jaxx | 70 + .../swing}/ui/admin/report/ReportConfigUI.jcss | 0 .../swing/ui/admin/report/ReportModel.java | 248 +++ .../swing/ui/admin/report/ReportUI.jaxx | 122 ++ .../swing}/ui/admin/report/ReportUI.jcss | 0 .../swing/ui/admin/report/ReportUIHandler.java | 504 +++++ .../swing/ui/admin/report/ResultTableModel.java | 199 ++ .../swing/ui/admin/resume/ShowResumeUI.jaxx | 94 + .../swing}/ui/admin/resume/ShowResumeUI.jcss | 0 .../swing/ui/admin/resume/ShowResumeUIHandler.java | 108 + .../swing/ui/admin/save/SaveLocalModel.java | 140 ++ .../swing/ui/admin/save/SaveLocalUI.jaxx | 122 ++ .../swing}/ui/admin/save/SaveLocalUI.jcss | 0 .../swing/ui/admin/save/SaveLocalUIHandler.java | 193 ++ .../admin/synchronize/data/DataSynchroModel.java | 119 ++ .../ui/admin/synchronize/data/DataSynchroUI.jaxx | 139 ++ .../ui/admin/synchronize/data/DataSynchroUI.jcss | 0 .../synchronize/data/DataSynchroUIHandler.java | 301 +++ .../data/DataSynchronizeTaskListCellRenderer.java | 29 + .../data/task/CopyToLeftDataSynchronizeTask.java | 33 + .../data/task/CopyToRightDataSynchronizeTask.java | 33 + .../data/task/DataSynchronizeTaskSupport.java | 56 + .../task/DeleteFromLeftDataSynchronizeTask.java | 25 + .../task/DeleteFromRightDataSynchronizeTask.java | 25 + .../legacy/ObsoleteReferentialReference.java | 74 + ...soleteReferentialReferenceListCellRenderer.java | 72 + .../referential/legacy/SynchronizeModel.java | 124 ++ .../referential/legacy/SynchronizeUI.jaxx | 120 ++ .../referential/legacy/SynchronizeUI.jcss | 0 .../referential/legacy/SynchronizeUIHandler.java | 356 ++++ .../referential/ng/ReferentialReplaceUI.jaxx | 0 .../referential/ng/ReferentialReplaceUI.jcss | 0 .../ng/ReferentialReplaceUIHandler.java | 40 + .../referential/ng/ReferentialSynchroConfigUI.jaxx | 80 + .../referential/ng/ReferentialSynchroConfigUI.jcss | 0 .../referential/ng/ReferentialSynchroModel.java | 299 +++ .../referential/ng/ReferentialSynchroUI.jaxx | 144 ++ .../referential/ng/ReferentialSynchroUI.jcss | 0 .../ng/ReferentialSynchroUIHandler.java | 191 ++ .../ng/ReferentialSynchronizeResources.java | 161 ++ ...ReferentialSynchronizeTaskListCellRenderer.java | 29 + .../ng/ReferentialSynchronizeTaskListModel.java | 52 + .../referential/ng/action/ApplyAction.java | 86 + .../ng/action/RegisterAddTaskAction.java | 42 + .../ng/action/RegisterCopyTaskAction.java | 41 + .../ng/action/RegisterDeleteTaskAction.java | 34 + .../ng/action/RegisterDesactivateTaskAction.java | 34 + .../ng/action/RegisterRevertTaskAction.java | 27 + .../ng/action/RegisterSkipTaskAction.java | 27 + .../ng/action/RegisterTasksActionSupport.java | 190 ++ .../ng/action/RegisterUpdateTaskAction.java | 43 + .../ng/task/AddReferentialSynchronizeTask.java | 19 + .../ng/task/DeleteReferentialSynchronizeTask.java | 19 + .../DesactivateReferentialSynchronizeTask.java | 40 + .../ng/task/ReferentialSynchronizeTaskSupport.java | 79 + ...ferentialSynchronizeTaskWithReplaceSupport.java | 39 + .../ng/task/RevertReferentialSynchronizeTask.java | 19 + .../ng/task/SkipReferentialSynchronizeTask.java | 24 + .../ng/task/UpdateReferentialSynchronizeTask.java | 19 + .../ReferentialSynchronizeTreeCellRenderer.java | 122 ++ .../ng/tree/ReferentialSynchronizeTreeModel.java | 393 ++++ .../ReferentialSynchronizeTreeModelsBuilder.java | 171 ++ .../node/AddedReferenceReferentialSynchroNode.java | 20 + .../ReferenceReferentialSynchroNodeSupport.java | 61 + .../tree/node/ReferentialSynchroNodeSupport.java | 38 + .../ng/tree/node/RootReferentialSynchroNode.java | 55 + .../ng/tree/node/TypeReferentialSynchroNode.java | 42 + .../UpdatedReferenceReferentialSynchroNode.java | 19 + .../swing/ui/admin/validate/ValidateConfigUI.jaxx | 184 ++ .../swing}/ui/admin/validate/ValidateConfigUI.jcss | 0 .../validate/ValidateEntityListCellRenderer.java | 158 ++ .../swing/ui/admin/validate/ValidateModel.java | 261 +++ .../swing/ui/admin/validate/ValidateUI.jaxx | 127 ++ .../swing}/ui/admin/validate/ValidateUI.jcss | 0 .../swing/ui/admin/validate/ValidateUIHandler.java | 603 ++++++ .../validate/ValidationMessageTableModel.java | 115 ++ .../{ => application/swing}/ui/content/Common.jcss | 0 .../application/swing/ui/content/ContentMode.java | 38 + .../application/swing/ui/content/ContentUI.jaxx | 160 ++ .../swing}/ui/content/ContentUI.jcss | 0 .../swing/ui/content/ContentUIHandler.java | 1122 +++++++++++ .../swing/ui/content/ContentUIInitializer.java | 853 ++++++++ .../swing/ui/content/ContentUIManager.java | 447 +++++ .../swing/ui/content/ContentUIModel.java | 335 ++++ .../swing/ui/content/ObserveContentUI.java | 81 + .../content/impl/longline/BasketsTableModel.java | 168 ++ .../ui/content/impl/longline/BranchlineUI.jaxx | 254 +++ .../ui/content/impl/longline/BranchlineUI.jcss | 245 +++ .../content/impl/longline/BranchlineUIHandler.java | 354 ++++ .../content/impl/longline/BranchlineUIModel.java | 110 ++ .../impl/longline/BranchlinesTableModel.java | 180 ++ .../LonglineCompositionTableModelSupport.java | 215 ++ .../impl/longline/LonglineDetailCompositionUI.jaxx | 205 ++ .../impl/longline/LonglineDetailCompositionUI.jcss | 0 .../LonglineDetailCompositionUIHandler.java | 1369 +++++++++++++ .../LonglineDetailCompositionUIInitializer.java | 398 ++++ .../longline/LonglineDetailCompositionUIModel.java | 132 ++ ...onglineDetailCompositionUIValidationHelper.java | 165 ++ ...LonglineDetailCompositionValidationContext.java | 116 ++ .../LonglineDetailCompositionValidatorService.java | 155 ++ .../impl/longline/LonglineGlobalCompositionUI.jaxx | 157 ++ .../impl/longline/LonglineGlobalCompositionUI.jcss | 0 .../LonglineGlobalCompositionUIHandler.java | 248 +++ .../longline/LonglineGlobalCompositionUIModel.java | 42 + .../impl/longline/SectionTemplatesTableModel.java | 158 ++ .../content/impl/longline/SectionsTableModel.java | 180 ++ .../ui/content/impl/longline/SetLonglineUI.jaxx | 428 ++++ .../ui/content/impl/longline/SetLonglineUI.jcss | 398 ++++ .../impl/longline/SetLonglineUIHandler.java | 470 +++++ .../content/impl/longline/SetLonglineUIModel.java | 132 ++ .../impl/seine/ActivitySeineObservedSystemUI.jaxx | 113 ++ .../impl/seine/ActivitySeineObservedSystemUI.jcss | 78 + .../ActivitySeineObservedSystemUIHandler.java | 123 ++ .../seine/ActivitySeineObservedSystemUIModel.java | 42 + .../FloatingObjectTransmittingBuoyOperationUI.jaxx | 257 +++ .../FloatingObjectTransmittingBuoyOperationUI.jcss | 0 ...ngObjectTransmittingBuoyOperationUIHandler.java | 376 ++++ ...tingObjectTransmittingBuoyOperationUIModel.java | 42 + .../ui/content/impl/seine/FloatingObjectUI.jaxx | 136 ++ .../ui/content/impl/seine/FloatingObjectUI.jcss | 126 ++ .../impl/seine/FloatingObjectUIHandler.java | 225 +++ .../content/impl/seine/FloatingObjectUIModel.java | 42 + .../swing/ui/content/impl/seine/SetSeineUI.jaxx | 255 +++ .../swing/ui/content/impl/seine/SetSeineUI.jcss | 226 +++ .../ui/content/impl/seine/SetSeineUIHandler.java | 345 ++++ .../ui/content/impl/seine/SetSeineUIModel.java | 94 + .../swing}/ui/content/impl/seine/package.html | 0 .../swing/ui/content/list/ContentListUI.jaxx | 119 ++ .../swing}/ui/content/list/ContentListUI.jcss | 0 .../ui/content/list/ContentListUIHandler.java | 283 +++ .../swing/ui/content/list/ContentListUIModel.java | 134 ++ .../list/impl/longline/ActivityLonglinesUI.jaxx | 69 + .../list/impl/longline/ActivityLonglinesUI.jcss | 0 .../impl/longline/ActivityLonglinesUIHandler.java | 126 ++ .../impl/longline/ActivityLonglinesUIModel.java | 43 + .../content/list/impl/longline/CommonListUI.jcss | 0 .../list/impl/longline/TripLonglinesUI.jaxx | 67 + .../list/impl/longline/TripLonglinesUI.jcss | 0 .../list/impl/longline/TripLonglinesUIHandler.java | 112 ++ .../list/impl/longline/TripLonglinesUIModel.java | 51 + .../content/list/impl/seine/ActivitySeinesUI.jaxx | 69 + .../content/list/impl/seine/ActivitySeinesUI.jcss | 0 .../list/impl/seine/ActivitySeinesUIHandler.java | 123 ++ .../list/impl/seine/ActivitySeinesUIModel.java | 43 + .../ui/content/list/impl/seine/CommonListUI.jcss | 0 .../swing/ui/content/list/impl/seine/RoutesUI.jaxx | 68 + .../ui/content/list/impl/seine/RoutesUI.jcss | 0 .../content/list/impl/seine/RoutesUIHandler.java | 121 ++ .../ui/content/list/impl/seine/RoutesUIModel.java | 43 + .../ui/content/list/impl/seine/TripSeinesUI.jaxx | 77 + .../ui/content/list/impl/seine/TripSeinesUI.jcss | 0 .../list/impl/seine/TripSeinesUIHandler.java | 109 ++ .../content/list/impl/seine/TripSeinesUIModel.java | 52 + .../swing}/ui/content/list/package.html | 0 .../swing/ui/content/open/ContentOpenableUI.jaxx | 114 ++ .../swing}/ui/content/open/ContentOpenableUI.jcss | 0 .../ui/content/open/ContentOpenableUIHandler.java | 314 +++ .../ui/content/open/ContentOpenableUIModel.java | 68 + .../open/impl/longline/ActivityLonglineUI.jaxx | 147 ++ .../open/impl/longline/ActivityLonglineUI.jcss | 100 + .../impl/longline/ActivityLonglineUIHandler.java | 363 ++++ .../impl/longline/ActivityLonglineUIModel.java | 89 + .../content/open/impl/longline/TripLonglineUI.jaxx | 242 +++ .../content/open/impl/longline/TripLonglineUI.jcss | 196 ++ .../open/impl/longline/TripLonglineUIHandler.java | 373 ++++ .../open/impl/longline/TripLonglineUIModel.java | 42 + .../content/open/impl/seine/ActivitySeineUI.jaxx | 290 +++ .../content/open/impl/seine/ActivitySeineUI.jcss | 226 +++ .../open/impl/seine/ActivitySeineUIHandler.java | 378 ++++ .../open/impl/seine/ActivitySeineUIModel.java | 121 ++ .../swing/ui/content/open/impl/seine/RouteUI.jaxx | 102 + .../swing/ui/content/open/impl/seine/RouteUI.jcss | 92 + .../ui/content/open/impl/seine/RouteUIHandler.java | 466 +++++ .../ui/content/open/impl/seine/RouteUIModel.java | 42 + .../ui/content/open/impl/seine/TripSeineUI.jaxx | 256 +++ .../ui/content/open/impl/seine/TripSeineUI.jcss | 225 +++ .../open/impl/seine/TripSeineUIHandler.java | 370 ++++ .../content/open/impl/seine/TripSeineUIModel.java | 42 + .../swing}/ui/content/package.html | 0 .../swing/ui/content/ref/ContentReferenceUI.jaxx | 201 ++ .../swing}/ui/content/ref/ContentReferenceUI.jcss | 0 .../ui/content/ref/ContentReferenceUIHandler.java | 828 ++++++++ .../ui/content/ref/ContentReferenceUIModel.java | 259 +++ .../swing/ui/content/ref/ReferenceHomeUI.jaxx | 46 + .../swing}/ui/content/ref/ReferenceHomeUI.jcss | 0 .../ui/content/ref/ReferenceHomeUIHandler.java | 53 + .../swing/ui/content/ref/ReferenceHomeUIModel.java | 42 + .../ref/ReferentialContentUIInitializer.java | 57 + .../swing/ui/content/ref/UniqueKeyTableModel.java | 87 + .../swing/ui/content/ref/impl/CountryUI.jaxx | 185 ++ .../swing}/ui/content/ref/impl/CountryUI.jcss | 0 .../swing/ui/content/ref/impl/CountryUIModel.java | 45 + .../swing/ui/content/ref/impl/FpaZoneUI.jaxx | 181 ++ .../swing}/ui/content/ref/impl/FpaZoneUI.jcss | 0 .../swing/ui/content/ref/impl/FpaZoneUIModel.java | 45 + .../content/ref/impl/GearCaracteristicTypeUI.jaxx | 162 ++ .../ref/impl/GearCaracteristicTypeUIModel.java | 42 + .../ui/content/ref/impl/GearCaracteristicUI.jaxx | 187 ++ .../ui/content/ref/impl/GearCaracteristicUI.jcss | 0 .../content/ref/impl/GearCaracteristicUIModel.java | 49 + .../swing/ui/content/ref/impl/GearUI.jaxx | 200 ++ .../swing}/ui/content/ref/impl/GearUI.jcss | 0 .../swing/ui/content/ref/impl/GearUIHandler.java | 102 + .../swing/ui/content/ref/impl/GearUIModel.java | 92 + .../swing/ui/content/ref/impl/HarbourUI.jaxx | 149 ++ .../swing}/ui/content/ref/impl/HarbourUI.jcss | 0 .../swing/ui/content/ref/impl/HarbourUIModel.java | 55 + .../ui/content/ref/impl/I18nReferenceEntity.jcss | 0 .../content/ref/impl/LengthWeightParameterUI.jaxx | 300 +++ .../content/ref/impl/LengthWeightParameterUI.jcss | 0 .../ref/impl/LengthWeightParameterUIHandler.java | 102 + .../ref/impl/LengthWeightParameterUIModel.java | 102 + .../ref/impl/NeedCommentReferenceEntity.jcss | 0 .../swing/ui/content/ref/impl/OceanUI.jaxx | 164 ++ .../swing/ui/content/ref/impl/OceanUIModel.java | 42 + .../swing/ui/content/ref/impl/OrganismUI.jaxx | 189 ++ .../swing}/ui/content/ref/impl/OrganismUI.jcss | 0 .../swing/ui/content/ref/impl/OrganismUIModel.java | 45 + .../swing/ui/content/ref/impl/PersonUI.jaxx | 169 ++ .../swing}/ui/content/ref/impl/PersonUI.jcss | 0 .../swing/ui/content/ref/impl/PersonUIModel.java | 61 + .../content/ref/impl/ProgramObservationEnum.java | 60 + .../swing/ui/content/ref/impl/ProgramUI.jaxx | 339 ++++ .../swing}/ui/content/ref/impl/ProgramUI.jcss | 0 .../ui/content/ref/impl/ProgramUIHandler.java | 102 + .../swing/ui/content/ref/impl/ProgramUIModel.java | 126 ++ .../ui/content/ref/impl/ReferenceEntity.jcss | 0 .../swing/ui/content/ref/impl/SexUI.jaxx | 164 ++ .../swing/ui/content/ref/impl/SexUIModel.java | 42 + .../swing/ui/content/ref/impl/SpeciesGroupUI.jaxx | 166 ++ .../swing}/ui/content/ref/impl/SpeciesGroupUI.jcss | 0 .../ui/content/ref/impl/SpeciesGroupUIModel.java | 42 + .../swing/ui/content/ref/impl/SpeciesListUI.jaxx | 206 ++ .../swing}/ui/content/ref/impl/SpeciesListUI.jcss | 0 .../ui/content/ref/impl/SpeciesListUIHandler.java | 102 + .../ui/content/ref/impl/SpeciesListUIModel.java | 94 + .../swing/ui/content/ref/impl/SpeciesUI.jaxx | 282 +++ .../swing}/ui/content/ref/impl/SpeciesUI.jcss | 0 .../ui/content/ref/impl/SpeciesUIHandler.java | 102 + .../swing/ui/content/ref/impl/SpeciesUIModel.java | 124 ++ .../ui/content/ref/impl/VesselSizeCategoryUI.jaxx | 121 ++ .../ui/content/ref/impl/VesselSizeCategoryUI.jcss | 0 .../ref/impl/VesselSizeCategoryUIModel.java | 50 + .../swing/ui/content/ref/impl/VesselTypeUI.jaxx | 164 ++ .../ui/content/ref/impl/VesselTypeUIModel.java | 42 + .../swing/ui/content/ref/impl/VesselUI.jaxx | 297 +++ .../swing}/ui/content/ref/impl/VesselUI.jcss | 0 .../swing/ui/content/ref/impl/VesselUIHandler.java | 102 + .../swing/ui/content/ref/impl/VesselUIModel.java | 126 ++ .../ref/impl/longline/BaitHaulingStatusUI.jaxx | 163 ++ .../impl/longline/BaitHaulingStatusUIModel.java | 42 + .../ref/impl/longline/BaitSettingStatusUI.jaxx | 163 ++ .../impl/longline/BaitSettingStatusUIModel.java | 42 + .../ui/content/ref/impl/longline/BaitTypeUI.jaxx | 163 ++ .../content/ref/impl/longline/BaitTypeUIModel.java | 42 + .../ref/impl/longline/CatchFateLonglineUI.jaxx | 163 ++ .../impl/longline/CatchFateLonglineUIModel.java | 42 + .../content/ref/impl/longline/EncounterTypeUI.jaxx | 163 ++ .../ref/impl/longline/EncounterTypeUIModel.java | 42 + .../ui/content/ref/impl/longline/HealthnessUI.jaxx | 163 ++ .../ref/impl/longline/HealthnessUIModel.java | 42 + .../content/ref/impl/longline/HookPositionUI.jaxx | 163 ++ .../ref/impl/longline/HookPositionUIModel.java | 42 + .../ui/content/ref/impl/longline/HookSizeUI.jaxx | 163 ++ .../content/ref/impl/longline/HookSizeUIModel.java | 42 + .../ui/content/ref/impl/longline/HookTypeUI.jaxx | 163 ++ .../content/ref/impl/longline/HookTypeUIModel.java | 42 + .../impl/longline/ItemHorizontalPositionUI.jaxx | 163 ++ .../longline/ItemHorizontalPositionUIModel.java | 42 + .../ref/impl/longline/ItemVerticalPositionUI.jaxx | 163 ++ .../impl/longline/ItemVerticalPositionUIModel.java | 42 + .../ref/impl/longline/LightsticksColorUI.jaxx | 163 ++ .../ref/impl/longline/LightsticksColorUIModel.java | 42 + .../ref/impl/longline/LightsticksTypeUI.jaxx | 163 ++ .../ref/impl/longline/LightsticksTypeUIModel.java | 42 + .../ui/content/ref/impl/longline/LineTypeUI.jaxx | 163 ++ .../content/ref/impl/longline/LineTypeUIModel.java | 42 + .../ref/impl/longline/MaturityStatusUI.jaxx | 179 ++ .../ref/impl/longline/MaturityStatusUI.jcss | 0 .../ref/impl/longline/MaturityStatusUIModel.java | 45 + .../ref/impl/longline/MitigationTypeUI.jaxx | 163 ++ .../ref/impl/longline/MitigationTypeUIModel.java | 42 + .../content/ref/impl/longline/SensorBrandUI.jaxx | 108 + .../content/ref/impl/longline/SensorBrandUI.jcss | 0 .../ref/impl/longline/SensorBrandUIModel.java | 45 + .../ref/impl/longline/SensorDataFormatUI.jaxx | 163 ++ .../ref/impl/longline/SensorDataFormatUIModel.java | 42 + .../ui/content/ref/impl/longline/SensorTypeUI.jaxx | 163 ++ .../ref/impl/longline/SensorTypeUIModel.java | 42 + .../content/ref/impl/longline/SettingShapeUI.jaxx | 163 ++ .../ref/impl/longline/SettingShapeUIModel.java | 42 + .../ref/impl/longline/SizeMeasureTypeUI.jaxx | 163 ++ .../ref/impl/longline/SizeMeasureTypeUIModel.java | 42 + .../ref/impl/longline/StomacFullnessUI.jaxx | 163 ++ .../ref/impl/longline/StomacFullnessUIModel.java | 42 + .../ui/content/ref/impl/longline/TripTypeUI.jaxx | 163 ++ .../content/ref/impl/longline/TripTypeUIModel.java | 42 + .../impl/longline/VesselActivityLonglineUI.jaxx | 163 ++ .../longline/VesselActivityLonglineUIModel.java | 42 + .../ref/impl/longline/WeightMeasureTypeUI.jaxx | 163 ++ .../impl/longline/WeightMeasureTypeUIModel.java | 42 + .../ui/content/ref/impl/seine/DetectionModeUI.jaxx | 164 ++ .../ref/impl/seine/DetectionModeUIModel.java | 42 + .../ui/content/ref/impl/seine/ObjectFateUI.jaxx | 163 ++ .../content/ref/impl/seine/ObjectFateUIModel.java | 42 + .../content/ref/impl/seine/ObjectOperationUI.jaxx | 164 ++ .../ref/impl/seine/ObjectOperationUIModel.java | 42 + .../ui/content/ref/impl/seine/ObjectTypeUI.jaxx | 164 ++ .../content/ref/impl/seine/ObjectTypeUIModel.java | 42 + .../content/ref/impl/seine/ObservedSystemUI.jaxx | 176 ++ .../content/ref/impl/seine/ObservedSystemUI.jcss | 0 .../ref/impl/seine/ObservedSystemUIModel.java | 45 + .../content/ref/impl/seine/ReasonForDiscardUI.jaxx | 164 ++ .../ref/impl/seine/ReasonForDiscardUIModel.java | 42 + .../ref/impl/seine/ReasonForNoFishingUI.jaxx | 164 ++ .../ref/impl/seine/ReasonForNoFishingUIModel.java | 42 + .../content/ref/impl/seine/ReasonForNullSetUI.jaxx | 163 ++ .../ref/impl/seine/ReasonForNullSetUIModel.java | 42 + .../ui/content/ref/impl/seine/SpeciesFateUI.jaxx | 163 ++ .../content/ref/impl/seine/SpeciesFateUIModel.java | 42 + .../ui/content/ref/impl/seine/SpeciesStatusUI.jaxx | 163 ++ .../ref/impl/seine/SpeciesStatusUIModel.java | 42 + .../ref/impl/seine/SurroundingActivityUI.jaxx | 163 ++ .../ref/impl/seine/SurroundingActivityUIModel.java | 42 + .../impl/seine/TransmittingBuoyOperationUI.jaxx | 164 ++ .../seine/TransmittingBuoyOperationUIModel.java | 42 + .../ref/impl/seine/TransmittingBuoyTypeUI.jaxx | 164 ++ .../impl/seine/TransmittingBuoyTypeUIModel.java | 42 + .../ref/impl/seine/VesselActivitySeineUI.jaxx | 165 ++ .../ref/impl/seine/VesselActivitySeineUIModel.java | 42 + .../content/ref/impl/seine/WeightCategoryUI.jaxx | 197 ++ .../content/ref/impl/seine/WeightCategoryUI.jcss | 0 .../ref/impl/seine/WeightCategoryUIModel.java | 46 + .../swing/ui/content/ref/impl/seine/WindUI.jaxx | 186 ++ .../swing}/ui/content/ref/impl/seine/WindUI.jcss | 0 .../ui/content/ref/impl/seine/WindUIModel.java | 45 + .../swing}/ui/content/ref/package.html | 0 .../swing}/ui/content/table/CommonTable.jcss | 0 .../swing/ui/content/table/ContentTableMeta.java | 158 ++ .../swing/ui/content/table/ContentTableModel.java | 748 +++++++ .../swing/ui/content/table/ContentTableUI.jaxx | 201 ++ .../swing/ui/content/table/ContentTableUI.jcss | 144 ++ .../ui/content/table/ContentTableUIHandler.java | 484 +++++ .../content/table/ContentTableUIInitializer.java | 257 +++ .../ui/content/table/ContentTableUIModel.java | 313 +++ .../ui/content/table/ObserveContentTableUI.java | 68 + .../table/impl/longline/BaitsCompositionUI.jaxx | 141 ++ .../table/impl/longline/BaitsCompositionUI.jcss | 90 + .../impl/longline/BaitsCompositionUIHandler.java | 124 ++ .../impl/longline/BaitsCompositionUIModel.java | 94 + .../impl/longline/BranchlinesCompositionUI.jaxx | 130 ++ .../impl/longline/BranchlinesCompositionUI.jcss | 78 + .../longline/BranchlinesCompositionUIHandler.java | 121 ++ .../longline/BranchlinesCompositionUIModel.java | 93 + .../impl/longline/CatchAcquisitionModeEnum.java | 66 + .../CatchLonglineContentTableUIInitializer.java | 65 + .../impl/longline/CatchLonglineTableModel.java | 161 ++ .../table/impl/longline/CatchLonglineUI.jaxx | 434 +++++ .../table/impl/longline/CatchLonglineUI.jcss | 475 +++++ .../impl/longline/CatchLonglineUIHandler.java | 938 +++++++++ .../table/impl/longline/CatchLonglineUIModel.java | 233 +++ .../content/table/impl/longline/EncounterUI.jaxx | 129 ++ .../content/table/impl/longline/EncounterUI.jcss | 67 + .../table/impl/longline/EncounterUIHandler.java | 161 ++ .../table/impl/longline/EncounterUIModel.java | 92 + .../impl/longline/FloatlinesCompositionUI.jaxx | 121 ++ .../impl/longline/FloatlinesCompositionUI.jcss | 67 + .../longline/FloatlinesCompositionUIHandler.java | 117 ++ .../longline/FloatlinesCompositionUIModel.java | 90 + .../GearUseFeaturesLonglineTableModel.java | 175 ++ .../impl/longline/GearUseFeaturesLonglineUI.jaxx | 155 ++ .../impl/longline/GearUseFeaturesLonglineUI.jcss | 105 + .../longline/GearUseFeaturesLonglineUIHandler.java | 508 +++++ .../longline/GearUseFeaturesLonglineUIModel.java | 106 + ...rUseFeaturesMeasurementLonglinesTableModel.java | 136 ++ .../table/impl/longline/HooksCompositionUI.jaxx | 131 ++ .../table/impl/longline/HooksCompositionUI.jcss | 79 + .../impl/longline/HooksCompositionUIHandler.java | 120 ++ .../impl/longline/HooksCompositionUIModel.java | 92 + .../impl/longline/LonglinePositionHelper.java | 318 +++ .../content/table/impl/longline/SensorUsedUI.jaxx | 163 ++ .../content/table/impl/longline/SensorUsedUI.jcss | 0 .../table/impl/longline/SensorUsedUIHandler.java | 220 +++ .../table/impl/longline/SensorUsedUIModel.java | 96 + .../impl/longline/SizeMeasuresTableModel.java | 104 + .../ui/content/table/impl/longline/TdrUI.jaxx | 396 ++++ .../ui/content/table/impl/longline/TdrUI.jcss | 370 ++++ .../content/table/impl/longline/TdrUIHandler.java | 485 +++++ .../ui/content/table/impl/longline/TdrUIModel.java | 227 +++ .../impl/longline/WeightMeasuresTableModel.java | 105 + .../content/table/impl/seine/AbstractSampleUI.jcss | 90 + .../content/table/impl/seine/CodeMesureEnum.java | 51 + .../seine/GearUseFeatureMeasurementCellEditor.java | 173 ++ .../GearUseFeatureMeasurementCellRenderer.java | 111 ++ ...GearUseFeaturesMeasurementSeinesTableModel.java | 133 ++ .../impl/seine/GearUseFeaturesSeineTableModel.java | 177 ++ .../table/impl/seine/GearUseFeaturesSeineUI.jaxx | 155 ++ .../table/impl/seine/GearUseFeaturesSeineUI.jcss | 103 + .../impl/seine/GearUseFeaturesSeineUIHandler.java | 506 +++++ .../impl/seine/GearUseFeaturesSeineUIModel.java | 109 ++ .../impl/seine/ModeSaisieEchantillonEnum.java | 76 + .../content/table/impl/seine/NonTargetCatchUI.jaxx | 195 ++ .../content/table/impl/seine/NonTargetCatchUI.jcss | 139 ++ .../table/impl/seine/NonTargetCatchUIHandler.java | 403 ++++ .../table/impl/seine/NonTargetCatchUIModel.java | 105 + .../table/impl/seine/NonTargetSampleUI.jaxx | 221 +++ .../table/impl/seine/NonTargetSampleUI.jcss | 113 ++ .../table/impl/seine/NonTargetSampleUIHandler.java | 336 ++++ .../table/impl/seine/NonTargetSampleUIModel.java | 106 + .../table/impl/seine/ObjectObservedSpeciesUI.jaxx | 125 ++ .../table/impl/seine/ObjectObservedSpeciesUI.jcss | 61 + .../impl/seine/ObjectObservedSpeciesUIHandler.java | 153 ++ .../impl/seine/ObjectObservedSpeciesUIModel.java | 92 + .../table/impl/seine/ObjectSchoolEstimateUI.jaxx | 113 ++ .../table/impl/seine/ObjectSchoolEstimateUI.jcss | 51 + .../impl/seine/ObjectSchoolEstimateUIHandler.java | 148 ++ .../impl/seine/ObjectSchoolEstimateUIModel.java | 90 + .../content/table/impl/seine/SchoolEstimateUI.jaxx | 129 ++ .../content/table/impl/seine/SchoolEstimateUI.jcss | 64 + .../table/impl/seine/SchoolEstimateUIHandler.java | 179 ++ .../table/impl/seine/SchoolEstimateUIModel.java | 92 + .../ui/content/table/impl/seine/TargetCatchUI.jaxx | 141 ++ .../ui/content/table/impl/seine/TargetCatchUI.jcss | 88 + .../table/impl/seine/TargetCatchUIHandler.java | 329 ++++ .../table/impl/seine/TargetCatchUIModel.java | 98 + .../table/impl/seine/TargetDiscardCatchUI.jaxx | 151 ++ .../table/impl/seine/TargetDiscardCatchUI.jcss | 100 + .../impl/seine/TargetDiscardCatchUIHandler.java | 541 +++++ .../impl/seine/TargetDiscardCatchUIModel.java | 98 + .../table/impl/seine/TargetSampleCaptureUI.jaxx | 0 .../table/impl/seine/TargetSampleCaptureUI.jcss | 0 .../table/impl/seine/TargetSampleRejeteUI.jaxx | 0 .../table/impl/seine/TargetSampleRejeteUI.jcss | 0 .../content/table/impl/seine/TargetSampleUI.jaxx | 185 ++ .../content/table/impl/seine/TargetSampleUI.jcss | 87 + .../table/impl/seine/TargetSampleUIHandler.java | 354 ++++ .../table/impl/seine/TargetSampleUIModel.java | 99 + .../swing}/ui/content/table/package.html | 0 .../{ => application/swing}/ui/package.html | 0 .../swing/ui/storage/ObstunaAdminAction.java | 352 ++++ .../swing/ui/storage/RemoteUILauncher.java | 142 ++ .../swing/ui/storage/StorageBackupUILauncher.java | 119 ++ .../application/swing/ui/storage/StorageStep.java | 113 ++ .../application/swing/ui/storage/StorageUI.jaxx | 189 ++ .../swing}/ui/storage/StorageUI.jcss | 0 .../swing/ui/storage/StorageUIHandler.java | 813 ++++++++ .../swing/ui/storage/StorageUILauncher.java | 520 +++++ .../swing/ui/storage/StorageUIModel.java | 2058 ++++++++++++++++++++ .../swing}/ui/storage/package.html | 0 .../swing/ui/storage/tabs/BackupUI.jaxx | 86 + .../swing}/ui/storage/tabs/BackupUI.jcss | 0 .../swing/ui/storage/tabs/ChooseDbModeUI.jaxx | 109 ++ .../swing}/ui/storage/tabs/ChooseDbModeUI.jcss | 0 .../swing/ui/storage/tabs/ConfigDataUI.jaxx | 174 ++ .../swing}/ui/storage/tabs/ConfigDataUI.jcss | 0 .../swing/ui/storage/tabs/ConfigReferentielUI.jaxx | 181 ++ .../ui/storage/tabs/ConfigReferentielUI.jcss | 0 .../swing/ui/storage/tabs/ConfigUI.jaxx | 293 +++ .../swing}/ui/storage/tabs/ConfigUI.jcss | 0 .../swing/ui/storage/tabs/ConfirmUI.jaxx | 51 + .../swing}/ui/storage/tabs/ConfirmUI.jcss | 0 .../swing/ui/storage/tabs/DataSelectionModel.java | 566 ++++++ .../swing/ui/storage/tabs/RolesTableModel.java | 190 ++ .../application/swing/ui/storage/tabs/RolesUI.jaxx | 72 + .../swing}/ui/storage/tabs/RolesUI.jcss | 0 .../swing/ui/storage/tabs/SecurityModel.java | 173 ++ .../swing/ui/storage/tabs/SelectDataUI.jaxx | 65 + .../swing}/ui/storage/tabs/SelectDataUI.jcss | 0 .../swing/ui/storage/tabs/StorageTabUI.jaxx | 96 + .../swing}/ui/storage/tabs/StorageTabUI.jcss | 0 .../swing/ui/storage/tabs/StorageTabUIHandler.java | 491 +++++ .../swing}/ui/storage/tabs/package.html | 0 .../ui/tree/AbstractObserveTreeCellRenderer.java | 432 ++++ .../swing/ui/tree/AbstrctReferenceNodeSupport.java | 115 ++ .../swing/ui/tree/ActivityLonglineNode.java | 52 + .../swing/ui/tree/ActivitySeineNode.java | 52 + .../swing/ui/tree/DataReferenceNodeSupport.java | 97 + .../ui/tree/DataSelectionTreeCellRenderer.java | 138 ++ .../ui/tree/DataSelectionTreeSelectionModel.java | 706 +++++++ .../swing/ui/tree/FloatingObjectSeineNode.java | 52 + .../swing/ui/tree/NavigationTreeCellRenderer.java | 99 + .../ui/tree/NavigationTreeSelectionModel.java | 118 ++ .../swing/ui/tree/ObserveDataProvider.java | 83 + .../tree/ObserveNavigationTreeShowPopupAction.java | 392 ++++ .../application/swing/ui/tree/ObserveNode.java | 119 ++ .../swing/ui/tree/ObserveTreeBridge.java | 141 ++ .../swing/ui/tree/ObserveTreeHelper.java | 669 +++++++ .../swing/ui/tree/ProgramLonglineNode.java | 57 + .../swing/ui/tree/ProgramSeineNode.java | 56 + .../ui/tree/ReferentialReferenceNodeSupport.java | 84 + .../application/swing/ui/tree/RouteSeineNode.java | 50 + .../application/swing/ui/tree/SetLonglineNode.java | 52 + .../application/swing/ui/tree/SetSeineNode.java | 52 + .../swing/ui/tree/TripLonglineNode.java | 51 + .../application/swing/ui/tree/TripSeineNode.java | 51 + .../actions/ChangeActivityRouteActionListener.java | 89 + .../actions/ChangeActivityTripActionListener.java | 91 + .../actions/ChangeRouteTripActionListener.java | 88 + .../actions/ChangeTripProgramActionListener.java | 95 + .../ui/tree/actions/NodeChangeActionListener.java | 107 + .../loadors/AbstractDataReferenceChildLoador.java | 39 + .../ui/tree/loadors/AbstractNodeChildLoador.java | 57 + .../loadors/ActivityLonglineNodeChildLoador.java | 121 ++ .../loadors/ActivityLonglinesNodeChildLoador.java | 73 + .../tree/loadors/ActivitySeineNodeChildLoador.java | 125 ++ .../loadors/ActivitySeinesNodeChildLoador.java | 71 + .../loadors/FloatingObjectNodeChildLoador.java | 77 + .../loadors/ProgramLonglineNodeChildLoador.java | 145 ++ .../tree/loadors/ProgramSeineNodeChildLoador.java | 139 ++ .../loadors/ReferenceCommonNodeChildLoador.java | 95 + .../loadors/ReferenceLonglineNodeChildLoador.java | 101 + .../loadors/ReferenceSeineNodeChildLoador.java | 92 + .../swing/ui/tree/loadors/RootNodeChildLoador.java | 160 ++ .../ui/tree/loadors/RoutesNodeChildLoador.java | 86 + .../tree/loadors/SetLonglineNodeChildLoador.java | 79 + .../ui/tree/loadors/SetSeineNodeChildLoador.java | 85 + .../MoveActivityLonglineNodeMenuPopulator.java | 85 + .../menu/MoveActivitySeineNodeMenuPopulator.java | 85 + .../swing/ui/tree/menu/MoveNodeMenuPopulator.java | 62 + .../ui/tree/menu/MoveRouteNodeMenuPopulator.java | 85 + .../ui/tree/menu/MoveTripNodeMenuPopulator.java | 105 + .../application/swing/ui/usage/UsagesUI.jaxx | 91 + .../swing/ui/usage/UsagesUIHandler.java | 168 ++ .../application/swing/ui/util/BooleanEditor.java | 180 ++ .../swing/ui/util/DecoratedNodeEntity.java | 60 + .../application/swing/ui/util/FloatConverter.java | 87 + .../swing/ui/util/JVetoableTabbedPane.java | 102 + .../ObserveSwingValidatorMessageTableModel.java | 84 + .../ObserveValidationMessageTableRenderer.java | 147 ++ .../util/ObserveValidatorMessageTableRenderer.java | 104 + .../application/swing/ui/util/SpringUtilities.java | 250 +++ .../ui/util/table/AbstractSelectTableAction.java | 119 ++ .../AutotSelectRowAndShowPopupActionSupport.java | 227 +++ .../swing/ui/util/table/EditableList.java | 65 + .../ui/util/table/EditableTableModelSupport.java | 629 ++++++ .../EditableTableWithCacheTableModelSupport.java | 151 ++ ...nlineTableAutotSelectRowAndShowPopupAction.java | 74 + .../util/table/MoveToNextEditableCellAction.java | 100 + .../ui/util/table/MoveToNextEditableRowAction.java | 92 + .../table/MoveToPreviousEditableCellAction.java | 80 + .../table/MoveToPreviousEditableRowAction.java | 71 + .../table/ObserveBooleanTableCellRenderer.java | 93 + .../swing/ui/util/tripMap/ObserveMapPane.java | 366 ++++ .../ui/util/tripMap/ObserveMapPaneLegendItem.java | 90 + .../util/tripMap/ObserverMapPanLegendDrawer.java | 111 ++ .../ui/util/tripMap/TripMapContentBuilder.java | 477 +++++ .../swing/ui/util/tripMap/TripMapUI.jaxx | 53 + .../swing}/ui/util/tripMap/TripMapUI.jcss | 0 .../swing/ui/util/tripMap/TripMapUIHandler.java | 363 ++++ .../swing/validation/ObserveSwingValidator.java | 179 ++ .../swing/validation/ValidationContext.java | 317 +++ .../swing/validation/ValidationModelMode.java | 85 + .../swing/validation/ValidationService.java | 155 ++ .../swing/validation/ValidatorsMap.java | 121 ++ .../ObserveSwingApplicationConfig.java | 1168 ----------- .../ObserveSwingApplicationConfigOption.java | 943 --------- .../ObserveSwingApplicationConfigProvider.java | 60 - .../main/java/fr/ird/observe/db/DataContext.java | 778 -------- .../fr/ird/observe/db/ObserveSwingDataSource.java | 723 ------- .../ird/observe/db/constants/ConnexionStatus.java | 66 - .../fr/ird/observe/db/constants/CreationMode.java | 108 - .../ird/observe/db/constants/DataContextType.java | 331 ---- .../java/fr/ird/observe/db/constants/DbMode.java | 70 - .../db/event/ObserveSwingDataSourceEvent.java | 83 - .../db/event/ObserveSwingDataSourceListener.java | 75 - .../ObserveSwingDataSourceListenerAdapter.java | 56 - .../src/main/java/fr/ird/observe/package.html | 36 - .../main/java/fr/ird/observe/ui/ObserveCommon.jcss | 94 - .../main/java/fr/ird/observe/ui/ObserveMainUI.jaxx | 341 ---- .../main/java/fr/ird/observe/ui/ObserveMainUI.jcss | 474 ----- .../fr/ird/observe/ui/ObserveMainUIHandler.java | 512 ----- .../java/fr/ird/observe/ui/ObserveUICallback.java | 115 -- .../main/java/fr/ird/observe/ui/ObserveUIMode.java | 43 - .../src/main/java/fr/ird/observe/ui/UIHelper.java | 595 ------ .../observe/ui/actions/AbstractObserveAction.java | 54 - .../actions/ChangeApplicationLanguageAction.java | 82 - .../observe/ui/actions/ChangeDbLanguageAction.java | 83 - .../observe/ui/actions/ChangeStorageAction.java | 97 - .../observe/ui/actions/CloseApplicationAction.java | 87 - .../fr/ird/observe/ui/actions/CloseHelpAction.java | 76 - .../ird/observe/ui/actions/CloseStorageAction.java | 86 - .../fr/ird/observe/ui/actions/GotoSiteAction.java | 87 - .../ui/actions/ImportStorageFromFileAction.java | 105 - .../ird/observe/ui/actions/LaunchAdminAction.java | 79 - .../ui/actions/ReloadApplicationAction.java | 73 - .../actions/ReloadDefaultConfigurationAction.java | 95 - .../observe/ui/actions/ReloadResourcesAction.java | 109 -- .../observe/ui/actions/ReloadStorageAction.java | 125 -- .../ui/actions/SaveStorageToFileAction.java | 92 - .../fr/ird/observe/ui/actions/ShowAboutAction.java | 126 -- .../ird/observe/ui/actions/ShowConfigAction.java | 500 ----- .../observe/ui/actions/ShowStorageInfoAction.java | 81 - .../observe/ui/actions/StartH2WebServerAction.java | 100 - .../observe/ui/actions/StartServerModeAction.java | 127 -- .../observe/ui/actions/StopH2WebServerAction.java | 82 - .../observe/ui/actions/StopServerModeAction.java | 105 - .../ui/actions/shared/AbstractUIAction.java | 113 -- .../ui/actions/shared/CancelCreateUIAction.java | 72 - .../ui/actions/shared/CloseAndCreateUIAction.java | 157 -- .../ui/actions/shared/CloseOpenUIAction.java | 173 -- .../ui/actions/shared/DeleteDataUIAction.java | 80 - .../ui/actions/shared/DeleteReferenceUIAction.java | 74 - .../observe/ui/actions/shared/GoDownUIAction.java | 151 -- .../observe/ui/actions/shared/GoUpUIAction.java | 129 -- .../shared/MoveActivityLonglinesUIAction.java | 197 -- .../actions/shared/MoveActivitySeinesUIAction.java | 192 -- .../ui/actions/shared/MoveRoutesUIAction.java | 199 -- .../actions/shared/MoveTripLonglinesUIAction.java | 85 - .../ui/actions/shared/MoveTripSeinesUIAction.java | 85 - .../ui/actions/shared/MoveTripsUIAction.java | 197 -- .../observe/ui/actions/shared/ReOpenUIAction.java | 103 - .../ui/actions/shared/ResetEditUIAction.java | 69 - .../ui/actions/shared/SaveEditUIAction.java | 69 - .../ui/actions/shared/SelectNodeUIAction.java | 62 - .../ui/actions/shared/SelectOpenNodeUIAction.java | 58 - .../fr/ird/observe/ui/admin/AdminActionModel.java | 38 - .../fr/ird/observe/ui/admin/AdminActionWorker.java | 57 - .../java/fr/ird/observe/ui/admin/AdminStep.java | 451 ----- .../java/fr/ird/observe/ui/admin/AdminTabUI.jaxx | 208 -- .../fr/ird/observe/ui/admin/AdminTabUIHandler.java | 242 --- .../main/java/fr/ird/observe/ui/admin/AdminUI.jaxx | 203 -- .../fr/ird/observe/ui/admin/AdminUIHandler.java | 381 ---- .../fr/ird/observe/ui/admin/AdminUILauncher.java | 275 --- .../java/fr/ird/observe/ui/admin/AdminUIModel.java | 1493 -------------- .../fr/ird/observe/ui/admin/config/ConfigUI.jaxx | 199 -- .../observe/ui/admin/config/ConfigUIHandler.java | 186 -- .../ird/observe/ui/admin/config/SelectDataUI.jaxx | 87 - .../ui/admin/consolidate/ConsolidateModel.java | 56 - .../ui/admin/consolidate/ConsolidateUI.jaxx | 65 - .../ui/admin/consolidate/ConsolidateUIHandler.java | 186 -- .../ird/observe/ui/admin/export/ExportModel.java | 179 -- .../fr/ird/observe/ui/admin/export/ExportUI.jaxx | 89 - .../observe/ui/admin/export/ExportUIHandler.java | 334 ---- .../fr/ird/observe/ui/admin/export/TripEntry.java | 59 - .../ui/admin/export/TripToExportTableModel.java | 170 -- .../observe/ui/admin/report/ReportConfigUI.jaxx | 70 - .../ird/observe/ui/admin/report/ReportModel.java | 248 --- .../fr/ird/observe/ui/admin/report/ReportUI.jaxx | 122 -- .../observe/ui/admin/report/ReportUIHandler.java | 504 ----- .../observe/ui/admin/report/ResultTableModel.java | 199 -- .../ird/observe/ui/admin/resume/ShowResumeUI.jaxx | 94 - .../ui/admin/resume/ShowResumeUIHandler.java | 108 - .../ird/observe/ui/admin/save/SaveLocalModel.java | 140 -- .../fr/ird/observe/ui/admin/save/SaveLocalUI.jaxx | 122 -- .../observe/ui/admin/save/SaveLocalUIHandler.java | 193 -- .../admin/synchronize/data/DataSynchroModel.java | 119 -- .../ui/admin/synchronize/data/DataSynchroUI.jaxx | 139 -- .../synchronize/data/DataSynchroUIHandler.java | 301 --- .../data/DataSynchronizeTaskListCellRenderer.java | 29 - .../data/task/CopyToLeftDataSynchronizeTask.java | 33 - .../data/task/CopyToRightDataSynchronizeTask.java | 33 - .../data/task/DataSynchronizeTaskSupport.java | 56 - .../task/DeleteFromLeftDataSynchronizeTask.java | 25 - .../task/DeleteFromRightDataSynchronizeTask.java | 25 - .../legacy/ObsoleteReferentialReference.java | 74 - ...soleteReferentialReferenceListCellRenderer.java | 72 - .../referential/legacy/SynchronizeModel.java | 124 -- .../referential/legacy/SynchronizeUI.jaxx | 120 -- .../referential/legacy/SynchronizeUIHandler.java | 356 ---- .../ng/ReferentialReplaceUIHandler.java | 40 - .../referential/ng/ReferentialSynchroConfigUI.jaxx | 80 - .../referential/ng/ReferentialSynchroModel.java | 299 --- .../referential/ng/ReferentialSynchroUI.jaxx | 144 -- .../ng/ReferentialSynchroUIHandler.java | 191 -- .../ng/ReferentialSynchronizeResources.java | 161 -- ...ReferentialSynchronizeTaskListCellRenderer.java | 29 - .../ng/ReferentialSynchronizeTaskListModel.java | 52 - .../referential/ng/action/ApplyAction.java | 86 - .../ng/action/RegisterAddTaskAction.java | 42 - .../ng/action/RegisterCopyTaskAction.java | 41 - .../ng/action/RegisterDeleteTaskAction.java | 34 - .../ng/action/RegisterDesactivateTaskAction.java | 34 - .../ng/action/RegisterRevertTaskAction.java | 27 - .../ng/action/RegisterSkipTaskAction.java | 27 - .../ng/action/RegisterTasksActionSupport.java | 190 -- .../ng/action/RegisterUpdateTaskAction.java | 43 - .../ng/task/AddReferentialSynchronizeTask.java | 19 - .../ng/task/DeleteReferentialSynchronizeTask.java | 19 - .../DesactivateReferentialSynchronizeTask.java | 40 - .../ng/task/ReferentialSynchronizeTaskSupport.java | 79 - ...ferentialSynchronizeTaskWithReplaceSupport.java | 39 - .../ng/task/RevertReferentialSynchronizeTask.java | 19 - .../ng/task/SkipReferentialSynchronizeTask.java | 24 - .../ng/task/UpdateReferentialSynchronizeTask.java | 19 - .../ReferentialSynchronizeTreeCellRenderer.java | 122 -- .../ng/tree/ReferentialSynchronizeTreeModel.java | 393 ---- .../ReferentialSynchronizeTreeModelsBuilder.java | 171 -- .../node/AddedReferenceReferentialSynchroNode.java | 20 - .../ReferenceReferentialSynchroNodeSupport.java | 61 - .../tree/node/ReferentialSynchroNodeSupport.java | 38 - .../ng/tree/node/RootReferentialSynchroNode.java | 55 - .../ng/tree/node/TypeReferentialSynchroNode.java | 42 - .../UpdatedReferenceReferentialSynchroNode.java | 19 - .../ui/admin/validate/ValidateConfigUI.jaxx | 184 -- .../validate/ValidateEntityListCellRenderer.java | 158 -- .../observe/ui/admin/validate/ValidateModel.java | 261 --- .../ird/observe/ui/admin/validate/ValidateUI.jaxx | 127 -- .../ui/admin/validate/ValidateUIHandler.java | 603 ------ .../validate/ValidationMessageTableModel.java | 115 -- .../fr/ird/observe/ui/content/ContentMode.java | 38 - .../java/fr/ird/observe/ui/content/ContentUI.jaxx | 160 -- .../ird/observe/ui/content/ContentUIHandler.java | 1122 ----------- .../observe/ui/content/ContentUIInitializer.java | 853 -------- .../ird/observe/ui/content/ContentUIManager.java | 447 ----- .../fr/ird/observe/ui/content/ContentUIModel.java | 335 ---- .../ird/observe/ui/content/ObserveContentUI.java | 81 - .../content/impl/longline/BasketsTableModel.java | 168 -- .../ui/content/impl/longline/BranchlineUI.jaxx | 254 --- .../ui/content/impl/longline/BranchlineUI.jcss | 245 --- .../content/impl/longline/BranchlineUIHandler.java | 354 ---- .../content/impl/longline/BranchlineUIModel.java | 110 -- .../impl/longline/BranchlinesTableModel.java | 180 -- .../LonglineCompositionTableModelSupport.java | 215 -- .../impl/longline/LonglineDetailCompositionUI.jaxx | 205 -- .../LonglineDetailCompositionUIHandler.java | 1369 ------------- .../LonglineDetailCompositionUIInitializer.java | 398 ---- .../longline/LonglineDetailCompositionUIModel.java | 132 -- ...onglineDetailCompositionUIValidationHelper.java | 165 -- ...LonglineDetailCompositionValidationContext.java | 116 -- .../LonglineDetailCompositionValidatorService.java | 155 -- .../impl/longline/LonglineGlobalCompositionUI.jaxx | 157 -- .../LonglineGlobalCompositionUIHandler.java | 248 --- .../longline/LonglineGlobalCompositionUIModel.java | 42 - .../impl/longline/SectionTemplatesTableModel.java | 158 -- .../content/impl/longline/SectionsTableModel.java | 180 -- .../ui/content/impl/longline/SetLonglineUI.jaxx | 428 ---- .../ui/content/impl/longline/SetLonglineUI.jcss | 398 ---- .../impl/longline/SetLonglineUIHandler.java | 470 ----- .../content/impl/longline/SetLonglineUIModel.java | 132 -- .../impl/seine/ActivitySeineObservedSystemUI.jaxx | 113 -- .../impl/seine/ActivitySeineObservedSystemUI.jcss | 78 - .../ActivitySeineObservedSystemUIHandler.java | 123 -- .../seine/ActivitySeineObservedSystemUIModel.java | 42 - .../FloatingObjectTransmittingBuoyOperationUI.jaxx | 257 --- ...ngObjectTransmittingBuoyOperationUIHandler.java | 376 ---- ...tingObjectTransmittingBuoyOperationUIModel.java | 42 - .../ui/content/impl/seine/FloatingObjectUI.jaxx | 136 -- .../ui/content/impl/seine/FloatingObjectUI.jcss | 126 -- .../impl/seine/FloatingObjectUIHandler.java | 225 --- .../content/impl/seine/FloatingObjectUIModel.java | 42 - .../observe/ui/content/impl/seine/SetSeineUI.jaxx | 255 --- .../observe/ui/content/impl/seine/SetSeineUI.jcss | 226 --- .../ui/content/impl/seine/SetSeineUIHandler.java | 345 ---- .../ui/content/impl/seine/SetSeineUIModel.java | 94 - .../ird/observe/ui/content/list/ContentListUI.jaxx | 119 -- .../ui/content/list/ContentListUIHandler.java | 283 --- .../ui/content/list/ContentListUIModel.java | 134 -- .../list/impl/longline/ActivityLonglinesUI.jaxx | 69 - .../impl/longline/ActivityLonglinesUIHandler.java | 126 -- .../impl/longline/ActivityLonglinesUIModel.java | 43 - .../list/impl/longline/TripLonglinesUI.jaxx | 67 - .../list/impl/longline/TripLonglinesUIHandler.java | 112 -- .../list/impl/longline/TripLonglinesUIModel.java | 51 - .../content/list/impl/seine/ActivitySeinesUI.jaxx | 69 - .../list/impl/seine/ActivitySeinesUIHandler.java | 123 -- .../list/impl/seine/ActivitySeinesUIModel.java | 43 - .../ui/content/list/impl/seine/RoutesUI.jaxx | 68 - .../content/list/impl/seine/RoutesUIHandler.java | 121 -- .../ui/content/list/impl/seine/RoutesUIModel.java | 43 - .../ui/content/list/impl/seine/TripSeinesUI.jaxx | 77 - .../list/impl/seine/TripSeinesUIHandler.java | 109 -- .../content/list/impl/seine/TripSeinesUIModel.java | 52 - .../observe/ui/content/open/ContentOpenableUI.jaxx | 114 -- .../ui/content/open/ContentOpenableUIHandler.java | 314 --- .../ui/content/open/ContentOpenableUIModel.java | 68 - .../open/impl/longline/ActivityLonglineUI.jaxx | 147 -- .../open/impl/longline/ActivityLonglineUI.jcss | 100 - .../impl/longline/ActivityLonglineUIHandler.java | 363 ---- .../impl/longline/ActivityLonglineUIModel.java | 89 - .../content/open/impl/longline/TripLonglineUI.jaxx | 242 --- .../content/open/impl/longline/TripLonglineUI.jcss | 196 -- .../open/impl/longline/TripLonglineUIHandler.java | 373 ---- .../open/impl/longline/TripLonglineUIModel.java | 42 - .../content/open/impl/seine/ActivitySeineUI.jaxx | 290 --- .../content/open/impl/seine/ActivitySeineUI.jcss | 226 --- .../open/impl/seine/ActivitySeineUIHandler.java | 378 ---- .../open/impl/seine/ActivitySeineUIModel.java | 121 -- .../ui/content/open/impl/seine/RouteUI.jaxx | 102 - .../ui/content/open/impl/seine/RouteUI.jcss | 92 - .../ui/content/open/impl/seine/RouteUIHandler.java | 466 ----- .../ui/content/open/impl/seine/RouteUIModel.java | 42 - .../ui/content/open/impl/seine/TripSeineUI.jaxx | 256 --- .../ui/content/open/impl/seine/TripSeineUI.jcss | 225 --- .../open/impl/seine/TripSeineUIHandler.java | 370 ---- .../content/open/impl/seine/TripSeineUIModel.java | 42 - .../observe/ui/content/ref/ContentReferenceUI.jaxx | 201 -- .../ui/content/ref/ContentReferenceUIHandler.java | 828 -------- .../ui/content/ref/ContentReferenceUIModel.java | 259 --- .../observe/ui/content/ref/ReferenceHomeUI.jaxx | 46 - .../ui/content/ref/ReferenceHomeUIHandler.java | 53 - .../ui/content/ref/ReferenceHomeUIModel.java | 42 - .../ref/ReferentialContentUIInitializer.java | 57 - .../ui/content/ref/UniqueKeyTableModel.java | 87 - .../ird/observe/ui/content/ref/impl/CountryUI.jaxx | 185 -- .../ui/content/ref/impl/CountryUIModel.java | 45 - .../ird/observe/ui/content/ref/impl/FpaZoneUI.jaxx | 181 -- .../ui/content/ref/impl/FpaZoneUIModel.java | 45 - .../content/ref/impl/GearCaracteristicTypeUI.jaxx | 162 -- .../ref/impl/GearCaracteristicTypeUIModel.java | 42 - .../ui/content/ref/impl/GearCaracteristicUI.jaxx | 187 -- .../content/ref/impl/GearCaracteristicUIModel.java | 49 - .../fr/ird/observe/ui/content/ref/impl/GearUI.jaxx | 200 -- .../observe/ui/content/ref/impl/GearUIHandler.java | 102 - .../observe/ui/content/ref/impl/GearUIModel.java | 92 - .../ird/observe/ui/content/ref/impl/HarbourUI.jaxx | 149 -- .../ui/content/ref/impl/HarbourUIModel.java | 55 - .../content/ref/impl/LengthWeightParameterUI.jaxx | 300 --- .../ref/impl/LengthWeightParameterUIHandler.java | 102 - .../ref/impl/LengthWeightParameterUIModel.java | 102 - .../ird/observe/ui/content/ref/impl/OceanUI.jaxx | 164 -- .../observe/ui/content/ref/impl/OceanUIModel.java | 42 - .../observe/ui/content/ref/impl/OrganismUI.jaxx | 189 -- .../ui/content/ref/impl/OrganismUIModel.java | 45 - .../ird/observe/ui/content/ref/impl/PersonUI.jaxx | 169 -- .../observe/ui/content/ref/impl/PersonUIModel.java | 61 - .../content/ref/impl/ProgramObservationEnum.java | 60 - .../ird/observe/ui/content/ref/impl/ProgramUI.jaxx | 339 ---- .../ui/content/ref/impl/ProgramUIHandler.java | 102 - .../ui/content/ref/impl/ProgramUIModel.java | 126 -- .../fr/ird/observe/ui/content/ref/impl/SexUI.jaxx | 164 -- .../observe/ui/content/ref/impl/SexUIModel.java | 42 - .../ui/content/ref/impl/SpeciesGroupUI.jaxx | 166 -- .../ui/content/ref/impl/SpeciesGroupUIModel.java | 42 - .../observe/ui/content/ref/impl/SpeciesListUI.jaxx | 206 -- .../ui/content/ref/impl/SpeciesListUIHandler.java | 102 - .../ui/content/ref/impl/SpeciesListUIModel.java | 94 - .../ird/observe/ui/content/ref/impl/SpeciesUI.jaxx | 282 --- .../ui/content/ref/impl/SpeciesUIHandler.java | 102 - .../ui/content/ref/impl/SpeciesUIModel.java | 124 -- .../ui/content/ref/impl/VesselSizeCategoryUI.jaxx | 121 -- .../ref/impl/VesselSizeCategoryUIModel.java | 50 - .../observe/ui/content/ref/impl/VesselTypeUI.jaxx | 164 -- .../ui/content/ref/impl/VesselTypeUIModel.java | 42 - .../ird/observe/ui/content/ref/impl/VesselUI.jaxx | 297 --- .../ui/content/ref/impl/VesselUIHandler.java | 102 - .../observe/ui/content/ref/impl/VesselUIModel.java | 126 -- .../ref/impl/longline/BaitHaulingStatusUI.jaxx | 163 -- .../impl/longline/BaitHaulingStatusUIModel.java | 42 - .../ref/impl/longline/BaitSettingStatusUI.jaxx | 163 -- .../impl/longline/BaitSettingStatusUIModel.java | 42 - .../ui/content/ref/impl/longline/BaitTypeUI.jaxx | 163 -- .../content/ref/impl/longline/BaitTypeUIModel.java | 42 - .../ref/impl/longline/CatchFateLonglineUI.jaxx | 163 -- .../impl/longline/CatchFateLonglineUIModel.java | 42 - .../content/ref/impl/longline/EncounterTypeUI.jaxx | 163 -- .../ref/impl/longline/EncounterTypeUIModel.java | 42 - .../ui/content/ref/impl/longline/HealthnessUI.jaxx | 163 -- .../ref/impl/longline/HealthnessUIModel.java | 42 - .../content/ref/impl/longline/HookPositionUI.jaxx | 163 -- .../ref/impl/longline/HookPositionUIModel.java | 42 - .../ui/content/ref/impl/longline/HookSizeUI.jaxx | 163 -- .../content/ref/impl/longline/HookSizeUIModel.java | 42 - .../ui/content/ref/impl/longline/HookTypeUI.jaxx | 163 -- .../content/ref/impl/longline/HookTypeUIModel.java | 42 - .../impl/longline/ItemHorizontalPositionUI.jaxx | 163 -- .../longline/ItemHorizontalPositionUIModel.java | 42 - .../ref/impl/longline/ItemVerticalPositionUI.jaxx | 163 -- .../impl/longline/ItemVerticalPositionUIModel.java | 42 - .../ref/impl/longline/LightsticksColorUI.jaxx | 163 -- .../ref/impl/longline/LightsticksColorUIModel.java | 42 - .../ref/impl/longline/LightsticksTypeUI.jaxx | 163 -- .../ref/impl/longline/LightsticksTypeUIModel.java | 42 - .../ui/content/ref/impl/longline/LineTypeUI.jaxx | 163 -- .../content/ref/impl/longline/LineTypeUIModel.java | 42 - .../ref/impl/longline/MaturityStatusUI.jaxx | 179 -- .../ref/impl/longline/MaturityStatusUIModel.java | 45 - .../ref/impl/longline/MitigationTypeUI.jaxx | 163 -- .../ref/impl/longline/MitigationTypeUIModel.java | 42 - .../content/ref/impl/longline/SensorBrandUI.jaxx | 108 - .../ref/impl/longline/SensorBrandUIModel.java | 45 - .../ref/impl/longline/SensorDataFormatUI.jaxx | 163 -- .../ref/impl/longline/SensorDataFormatUIModel.java | 42 - .../ui/content/ref/impl/longline/SensorTypeUI.jaxx | 163 -- .../ref/impl/longline/SensorTypeUIModel.java | 42 - .../content/ref/impl/longline/SettingShapeUI.jaxx | 163 -- .../ref/impl/longline/SettingShapeUIModel.java | 42 - .../ref/impl/longline/SizeMeasureTypeUI.jaxx | 163 -- .../ref/impl/longline/SizeMeasureTypeUIModel.java | 42 - .../ref/impl/longline/StomacFullnessUI.jaxx | 163 -- .../ref/impl/longline/StomacFullnessUIModel.java | 42 - .../ui/content/ref/impl/longline/TripTypeUI.jaxx | 163 -- .../content/ref/impl/longline/TripTypeUIModel.java | 42 - .../impl/longline/VesselActivityLonglineUI.jaxx | 163 -- .../longline/VesselActivityLonglineUIModel.java | 42 - .../ref/impl/longline/WeightMeasureTypeUI.jaxx | 163 -- .../impl/longline/WeightMeasureTypeUIModel.java | 42 - .../ui/content/ref/impl/seine/DetectionModeUI.jaxx | 164 -- .../ref/impl/seine/DetectionModeUIModel.java | 42 - .../ui/content/ref/impl/seine/ObjectFateUI.jaxx | 163 -- .../content/ref/impl/seine/ObjectFateUIModel.java | 42 - .../content/ref/impl/seine/ObjectOperationUI.jaxx | 164 -- .../ref/impl/seine/ObjectOperationUIModel.java | 42 - .../ui/content/ref/impl/seine/ObjectTypeUI.jaxx | 164 -- .../content/ref/impl/seine/ObjectTypeUIModel.java | 42 - .../content/ref/impl/seine/ObservedSystemUI.jaxx | 176 -- .../ref/impl/seine/ObservedSystemUIModel.java | 45 - .../content/ref/impl/seine/ReasonForDiscardUI.jaxx | 164 -- .../ref/impl/seine/ReasonForDiscardUIModel.java | 42 - .../ref/impl/seine/ReasonForNoFishingUI.jaxx | 164 -- .../ref/impl/seine/ReasonForNoFishingUIModel.java | 42 - .../content/ref/impl/seine/ReasonForNullSetUI.jaxx | 163 -- .../ref/impl/seine/ReasonForNullSetUIModel.java | 42 - .../ui/content/ref/impl/seine/SpeciesFateUI.jaxx | 163 -- .../content/ref/impl/seine/SpeciesFateUIModel.java | 42 - .../ui/content/ref/impl/seine/SpeciesStatusUI.jaxx | 163 -- .../ref/impl/seine/SpeciesStatusUIModel.java | 42 - .../ref/impl/seine/SurroundingActivityUI.jaxx | 163 -- .../ref/impl/seine/SurroundingActivityUIModel.java | 42 - .../impl/seine/TransmittingBuoyOperationUI.jaxx | 164 -- .../seine/TransmittingBuoyOperationUIModel.java | 42 - .../ref/impl/seine/TransmittingBuoyTypeUI.jaxx | 164 -- .../impl/seine/TransmittingBuoyTypeUIModel.java | 42 - .../ref/impl/seine/VesselActivitySeineUI.jaxx | 165 -- .../ref/impl/seine/VesselActivitySeineUIModel.java | 42 - .../content/ref/impl/seine/WeightCategoryUI.jaxx | 197 -- .../ref/impl/seine/WeightCategoryUIModel.java | 46 - .../observe/ui/content/ref/impl/seine/WindUI.jaxx | 186 -- .../ui/content/ref/impl/seine/WindUIModel.java | 45 - .../observe/ui/content/table/ContentTableMeta.java | 158 -- .../ui/content/table/ContentTableModel.java | 748 ------- .../observe/ui/content/table/ContentTableUI.jaxx | 201 -- .../observe/ui/content/table/ContentTableUI.jcss | 144 -- .../ui/content/table/ContentTableUIHandler.java | 484 ----- .../content/table/ContentTableUIInitializer.java | 257 --- .../ui/content/table/ContentTableUIModel.java | 313 --- .../ui/content/table/ObserveContentTableUI.java | 68 - .../table/impl/longline/BaitsCompositionUI.jaxx | 141 -- .../table/impl/longline/BaitsCompositionUI.jcss | 90 - .../impl/longline/BaitsCompositionUIHandler.java | 124 -- .../impl/longline/BaitsCompositionUIModel.java | 94 - .../impl/longline/BranchlinesCompositionUI.jaxx | 130 -- .../impl/longline/BranchlinesCompositionUI.jcss | 78 - .../longline/BranchlinesCompositionUIHandler.java | 121 -- .../longline/BranchlinesCompositionUIModel.java | 93 - .../impl/longline/CatchAcquisitionModeEnum.java | 66 - .../CatchLonglineContentTableUIInitializer.java | 65 - .../impl/longline/CatchLonglineTableModel.java | 161 -- .../table/impl/longline/CatchLonglineUI.jaxx | 434 ----- .../table/impl/longline/CatchLonglineUI.jcss | 475 ----- .../impl/longline/CatchLonglineUIHandler.java | 938 --------- .../table/impl/longline/CatchLonglineUIModel.java | 233 --- .../content/table/impl/longline/EncounterUI.jaxx | 129 -- .../content/table/impl/longline/EncounterUI.jcss | 67 - .../table/impl/longline/EncounterUIHandler.java | 161 -- .../table/impl/longline/EncounterUIModel.java | 92 - .../impl/longline/FloatlinesCompositionUI.jaxx | 121 -- .../impl/longline/FloatlinesCompositionUI.jcss | 67 - .../longline/FloatlinesCompositionUIHandler.java | 117 -- .../longline/FloatlinesCompositionUIModel.java | 90 - .../GearUseFeaturesLonglineTableModel.java | 175 -- .../impl/longline/GearUseFeaturesLonglineUI.jaxx | 155 -- .../impl/longline/GearUseFeaturesLonglineUI.jcss | 105 - .../longline/GearUseFeaturesLonglineUIHandler.java | 508 ----- .../longline/GearUseFeaturesLonglineUIModel.java | 106 - ...rUseFeaturesMeasurementLonglinesTableModel.java | 136 -- .../table/impl/longline/HooksCompositionUI.jaxx | 131 -- .../table/impl/longline/HooksCompositionUI.jcss | 79 - .../impl/longline/HooksCompositionUIHandler.java | 120 -- .../impl/longline/HooksCompositionUIModel.java | 92 - .../impl/longline/LonglinePositionHelper.java | 318 --- .../content/table/impl/longline/SensorUsedUI.jaxx | 163 -- .../table/impl/longline/SensorUsedUIHandler.java | 220 --- .../table/impl/longline/SensorUsedUIModel.java | 96 - .../impl/longline/SizeMeasuresTableModel.java | 104 - .../ui/content/table/impl/longline/TdrUI.jaxx | 396 ---- .../ui/content/table/impl/longline/TdrUI.jcss | 370 ---- .../content/table/impl/longline/TdrUIHandler.java | 485 ----- .../ui/content/table/impl/longline/TdrUIModel.java | 227 --- .../impl/longline/WeightMeasuresTableModel.java | 105 - .../content/table/impl/seine/AbstractSampleUI.jcss | 90 - .../content/table/impl/seine/CodeMesureEnum.java | 51 - .../seine/GearUseFeatureMeasurementCellEditor.java | 173 -- .../GearUseFeatureMeasurementCellRenderer.java | 111 -- ...GearUseFeaturesMeasurementSeinesTableModel.java | 133 -- .../impl/seine/GearUseFeaturesSeineTableModel.java | 177 -- .../table/impl/seine/GearUseFeaturesSeineUI.jaxx | 155 -- .../table/impl/seine/GearUseFeaturesSeineUI.jcss | 103 - .../impl/seine/GearUseFeaturesSeineUIHandler.java | 506 ----- .../impl/seine/GearUseFeaturesSeineUIModel.java | 109 -- .../impl/seine/ModeSaisieEchantillonEnum.java | 76 - .../content/table/impl/seine/NonTargetCatchUI.jaxx | 195 -- .../content/table/impl/seine/NonTargetCatchUI.jcss | 139 -- .../table/impl/seine/NonTargetCatchUIHandler.java | 403 ---- .../table/impl/seine/NonTargetCatchUIModel.java | 105 - .../table/impl/seine/NonTargetSampleUI.jaxx | 221 --- .../table/impl/seine/NonTargetSampleUI.jcss | 113 -- .../table/impl/seine/NonTargetSampleUIHandler.java | 336 ---- .../table/impl/seine/NonTargetSampleUIModel.java | 106 - .../table/impl/seine/ObjectObservedSpeciesUI.jaxx | 125 -- .../table/impl/seine/ObjectObservedSpeciesUI.jcss | 61 - .../impl/seine/ObjectObservedSpeciesUIHandler.java | 153 -- .../impl/seine/ObjectObservedSpeciesUIModel.java | 92 - .../table/impl/seine/ObjectSchoolEstimateUI.jaxx | 113 -- .../table/impl/seine/ObjectSchoolEstimateUI.jcss | 51 - .../impl/seine/ObjectSchoolEstimateUIHandler.java | 148 -- .../impl/seine/ObjectSchoolEstimateUIModel.java | 90 - .../content/table/impl/seine/SchoolEstimateUI.jaxx | 129 -- .../content/table/impl/seine/SchoolEstimateUI.jcss | 64 - .../table/impl/seine/SchoolEstimateUIHandler.java | 179 -- .../table/impl/seine/SchoolEstimateUIModel.java | 92 - .../ui/content/table/impl/seine/TargetCatchUI.jaxx | 141 -- .../ui/content/table/impl/seine/TargetCatchUI.jcss | 88 - .../table/impl/seine/TargetCatchUIHandler.java | 329 ---- .../table/impl/seine/TargetCatchUIModel.java | 98 - .../table/impl/seine/TargetDiscardCatchUI.jaxx | 151 -- .../table/impl/seine/TargetDiscardCatchUI.jcss | 100 - .../impl/seine/TargetDiscardCatchUIHandler.java | 541 ----- .../impl/seine/TargetDiscardCatchUIModel.java | 98 - .../content/table/impl/seine/TargetSampleUI.jaxx | 185 -- .../content/table/impl/seine/TargetSampleUI.jcss | 87 - .../table/impl/seine/TargetSampleUIHandler.java | 354 ---- .../table/impl/seine/TargetSampleUIModel.java | 99 - .../ird/observe/ui/storage/ObstunaAdminAction.java | 352 ---- .../ird/observe/ui/storage/RemoteUILauncher.java | 142 -- .../ui/storage/StorageBackupUILauncher.java | 119 -- .../fr/ird/observe/ui/storage/StorageStep.java | 113 -- .../java/fr/ird/observe/ui/storage/StorageUI.jaxx | 189 -- .../ird/observe/ui/storage/StorageUIHandler.java | 813 -------- .../ird/observe/ui/storage/StorageUILauncher.java | 520 ----- .../fr/ird/observe/ui/storage/StorageUIModel.java | 2058 -------------------- .../fr/ird/observe/ui/storage/tabs/BackupUI.jaxx | 86 - .../observe/ui/storage/tabs/ChooseDbModeUI.jaxx | 109 -- .../ird/observe/ui/storage/tabs/ConfigDataUI.jaxx | 174 -- .../ui/storage/tabs/ConfigReferentielUI.jaxx | 181 -- .../fr/ird/observe/ui/storage/tabs/ConfigUI.jaxx | 293 --- .../fr/ird/observe/ui/storage/tabs/ConfirmUI.jaxx | 51 - .../ui/storage/tabs/DataSelectionModel.java | 566 ------ .../observe/ui/storage/tabs/RolesTableModel.java | 190 -- .../fr/ird/observe/ui/storage/tabs/RolesUI.jaxx | 72 - .../ird/observe/ui/storage/tabs/SecurityModel.java | 173 -- .../ird/observe/ui/storage/tabs/SelectDataUI.jaxx | 65 - .../ird/observe/ui/storage/tabs/StorageTabUI.jaxx | 96 - .../ui/storage/tabs/StorageTabUIHandler.java | 491 ----- .../ui/tree/AbstractObserveTreeCellRenderer.java | 432 ---- .../ui/tree/AbstrctReferenceNodeSupport.java | 115 -- .../ird/observe/ui/tree/ActivityLonglineNode.java | 52 - .../fr/ird/observe/ui/tree/ActivitySeineNode.java | 52 - .../observe/ui/tree/DataReferenceNodeSupport.java | 97 - .../ui/tree/DataSelectionTreeCellRenderer.java | 138 -- .../ui/tree/DataSelectionTreeSelectionModel.java | 706 ------- .../observe/ui/tree/FloatingObjectSeineNode.java | 52 - .../ui/tree/NavigationTreeCellRenderer.java | 99 - .../ui/tree/NavigationTreeSelectionModel.java | 118 -- .../ird/observe/ui/tree/ObserveDataProvider.java | 83 - .../tree/ObserveNavigationTreeShowPopupAction.java | 392 ---- .../java/fr/ird/observe/ui/tree/ObserveNode.java | 119 -- .../fr/ird/observe/ui/tree/ObserveTreeBridge.java | 141 -- .../fr/ird/observe/ui/tree/ObserveTreeHelper.java | 669 ------- .../ird/observe/ui/tree/ProgramLonglineNode.java | 57 - .../fr/ird/observe/ui/tree/ProgramSeineNode.java | 56 - .../ui/tree/ReferentialReferenceNodeSupport.java | 84 - .../fr/ird/observe/ui/tree/RouteSeineNode.java | 50 - .../fr/ird/observe/ui/tree/SetLonglineNode.java | 52 - .../java/fr/ird/observe/ui/tree/SetSeineNode.java | 52 - .../fr/ird/observe/ui/tree/TripLonglineNode.java | 51 - .../java/fr/ird/observe/ui/tree/TripSeineNode.java | 51 - .../actions/ChangeActivityRouteActionListener.java | 89 - .../actions/ChangeActivityTripActionListener.java | 91 - .../actions/ChangeRouteTripActionListener.java | 88 - .../actions/ChangeTripProgramActionListener.java | 95 - .../ui/tree/actions/NodeChangeActionListener.java | 107 - .../loadors/AbstractDataReferenceChildLoador.java | 39 - .../ui/tree/loadors/AbstractNodeChildLoador.java | 57 - .../loadors/ActivityLonglineNodeChildLoador.java | 121 -- .../loadors/ActivityLonglinesNodeChildLoador.java | 73 - .../tree/loadors/ActivitySeineNodeChildLoador.java | 125 -- .../loadors/ActivitySeinesNodeChildLoador.java | 71 - .../loadors/FloatingObjectNodeChildLoador.java | 77 - .../loadors/ProgramLonglineNodeChildLoador.java | 145 -- .../tree/loadors/ProgramSeineNodeChildLoador.java | 139 -- .../loadors/ReferenceCommonNodeChildLoador.java | 95 - .../loadors/ReferenceLonglineNodeChildLoador.java | 101 - .../loadors/ReferenceSeineNodeChildLoador.java | 92 - .../ui/tree/loadors/RootNodeChildLoador.java | 160 -- .../ui/tree/loadors/RoutesNodeChildLoador.java | 86 - .../tree/loadors/SetLonglineNodeChildLoador.java | 79 - .../ui/tree/loadors/SetSeineNodeChildLoador.java | 85 - .../MoveActivityLonglineNodeMenuPopulator.java | 85 - .../menu/MoveActivitySeineNodeMenuPopulator.java | 85 - .../ui/tree/menu/MoveNodeMenuPopulator.java | 62 - .../ui/tree/menu/MoveRouteNodeMenuPopulator.java | 85 - .../ui/tree/menu/MoveTripNodeMenuPopulator.java | 105 - .../java/fr/ird/observe/ui/usage/UsagesUI.jaxx | 91 - .../fr/ird/observe/ui/usage/UsagesUIHandler.java | 168 -- .../java/fr/ird/observe/ui/util/BooleanEditor.java | 180 -- .../ird/observe/ui/util/DecoratedNodeEntity.java | 60 - .../fr/ird/observe/ui/util/FloatConverter.java | 87 - .../ird/observe/ui/util/JVetoableTabbedPane.java | 102 - .../ObserveSwingValidatorMessageTableModel.java | 84 - .../ObserveValidationMessageTableRenderer.java | 147 -- .../util/ObserveValidatorMessageTableRenderer.java | 104 - .../fr/ird/observe/ui/util/SpringUtilities.java | 250 --- .../ui/util/table/AbstractSelectTableAction.java | 119 -- .../AutotSelectRowAndShowPopupActionSupport.java | 227 --- .../fr/ird/observe/ui/util/table/EditableList.java | 65 - .../ui/util/table/EditableTableModelSupport.java | 629 ------ .../EditableTableWithCacheTableModelSupport.java | 151 -- ...nlineTableAutotSelectRowAndShowPopupAction.java | 74 - .../util/table/MoveToNextEditableCellAction.java | 100 - .../ui/util/table/MoveToNextEditableRowAction.java | 92 - .../table/MoveToPreviousEditableCellAction.java | 80 - .../table/MoveToPreviousEditableRowAction.java | 71 - .../table/ObserveBooleanTableCellRenderer.java | 93 - .../observe/ui/util/tripMap/ObserveMapPane.java | 366 ---- .../ui/util/tripMap/ObserveMapPaneLegendItem.java | 90 - .../util/tripMap/ObserverMapPanLegendDrawer.java | 111 -- .../ui/util/tripMap/TripMapContentBuilder.java | 477 ----- .../fr/ird/observe/ui/util/tripMap/TripMapUI.jaxx | 53 - .../observe/ui/util/tripMap/TripMapUIHandler.java | 363 ---- .../observe/validation/ObserveSwingValidator.java | 179 -- .../ird/observe/validation/ValidationContext.java | 317 --- .../observe/validation/ValidationModelMode.java | 85 - .../ird/observe/validation/ValidationService.java | 155 -- .../fr/ird/observe/validation/ValidatorsMap.java | 121 -- .../org.nuiton.config.ApplicationConfigProvider | 2 +- .../src/main/resources/log4j.properties | 12 +- .../src/main/resources/observe-log4j.properties | 12 +- ...glineDetailCompositionValidatorServiceTest.java | 215 ++ ...glineDetailCompositionValidatorServiceTest.java | 215 -- 1229 files changed, 96549 insertions(+), 96560 deletions(-) diff --git a/observe-application-swing/pom.xml b/observe-application-swing/pom.xml index ed97561..59cf3d0 100644 --- a/observe-application-swing/pom.xml +++ b/observe-application-swing/pom.xml @@ -46,15 +46,15 @@ <jaxx.autoImportCss>true</jaxx.autoImportCss> <jaxx.autoRecurseInCss>false</jaxx.autoRecurseInCss> <jaxx.validatorFactoryFQN> - fr.ird.observe.validation.ObserveSwingValidator + fr.ird.observe.application.swing.validation.ObserveSwingValidator </jaxx.validatorFactoryFQN> <jaxx.commonCss> - ${project.basedir}/src/main/java/fr/ird/observe/ui/ObserveCommon.jcss + ${project.basedir}/src/main/java/fr/ird/observe/application/swing/ui/ObserveCommon.jcss </jaxx.commonCss> <jaxx.cssExtension>jcss</jaxx.cssExtension> <!-- main class in JAR --> - <maven.jar.main.class>fr.ird.observe.ObserveAdminCLI</maven.jar.main.class> + <maven.jar.main.class>fr.ird.observe.application.swing.ObserveAdminCLI</maven.jar.main.class> <i18n.bundleOutputName>${projectId}-i18n</i18n.bundleOutputName> <i18n.bundleCsvFile>${projectId}-i18n.csv</i18n.bundleCsvFile> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ObserveActionExecutor.java b/observe-application-swing/src/main/java/fr/ird/observe/ObserveActionExecutor.java deleted file mode 100644 index bf33847..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ObserveActionExecutor.java +++ /dev/null @@ -1,318 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe; - -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.admin.AdminActionWorker; -import fr.ird.observe.ui.admin.AdminUIModel; -import jaxx.runtime.swing.application.ActionExecutor; -import jaxx.runtime.swing.application.ActionWorker; -import jaxx.runtime.swing.wizard.ext.WizardState; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.Date; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; - -/** - * Action executor. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ObserveActionExecutor extends ActionExecutor { - - /** Logger */ - private static final Log log = - LogFactory.getLog(ObserveActionExecutor.class); - - public ObserveActionExecutor() { - } - - @Override - public void onActionStart(ActionWorker<?, ?> source) { - if (log.isDebugEnabled()) { - log.debug("Action [" + source.getActionLabel() + "] was started at " + new Date(source.getStartTime())); - } - if (source instanceof ObserveCLAction.CommandLineActionWorker) { - if (log.isInfoEnabled()) { - log.info("Action [" + source.getActionLabel() + "] démarrée à " + new Date(source.getStartTime())); - } - - return; - } - if (ObserveSwingApplicationContext.get().isClosed()) { - - // l'application est déjà fermée, on ne fait rien - return; - } - if (source instanceof AdminActionWorker) { - AdminActionWorker admin = (AdminActionWorker) source; - AdminUIModel model = admin.getHandler().getModel(); - model.setBusy(true); - model.setStepState(WizardState.RUNNING); -// return; - } - ObserveMainUI ui = ObserveSwingApplicationContext.get().getMainUI(); - if (ui != null) { - ui.setBusy(true); - } - } - - @Override - public void onActionFail(ActionWorker<?, ?> source) { - Exception error = source.getError(); - if (log.isInfoEnabled()) { - if (log.isErrorEnabled()) { - log.error("Action [" + source.getActionLabel() + - "] failed with error " + error.getCause(), error); - } - } - if (ObserveSwingApplicationContext.get().isClosed()) { - - // l'application est déjà fermée, on ne fait rien - return; - } - if (source instanceof AdminActionWorker) { - AdminActionWorker admin = (AdminActionWorker) source; - AdminUIModel model = admin.getHandler().getModel(); - model.getStepModel(model.getOperation()).setError(error); - model.setStepState(WizardState.FAILED); - return; - } - ObserveMainUI ui = ObserveSwingApplicationContext.get().getMainUI(); - if (ui != null) { - ui.getStatus().setStatus("Action [" + source.getActionLabel() + "] arrêté à cause d'un erreur " + error.getMessage()); - } - } - - @Override - public void onActionCancel(ActionWorker<?, ?> source) { - if (log.isDebugEnabled()) { - log.debug("Action [" + source.getActionLabel() + "] was canceled"); - } - if (ObserveSwingApplicationContext.get().isClosed()) { - - // l'application est déjà fermée, on ne fait rien - return; - } - if (source instanceof AdminActionWorker) { - AdminActionWorker admin = (AdminActionWorker) source; - admin.getHandler().getModel().setStepState(WizardState.CANCELED); - return; - } - ObserveMainUI ui = ObserveSwingApplicationContext.get().getMainUI(); - if (ui != null) { - ui.getStatus().setStatus("Action [" + source.getActionLabel() + "] annulée"); - } - } - - @Override - public void onActionEnd(ActionWorker<?, ?> source) { - if (log.isDebugEnabled()) { - log.debug("Action [" + source.getActionLabel() + " ] was done in " + source.getTime()); - } - if (ObserveSwingApplicationContext.get().isClosed()) { - - // l'application est déjà fermée, on ne fait rien - return; - } - if (source instanceof AdminActionWorker) { - AdminActionWorker admin = (AdminActionWorker) source; - WizardState state; - try { - state = admin.get(); - admin.getHandler().getModel().setStepState(state); - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error("Could not retrive data from worker " + admin, e); - } - } - return; - } - ObserveMainUI ui = ObserveSwingApplicationContext.get().getMainUI(); - if (ui != null) { - ui.getStatus().setStatus("Action [" + source.getActionLabel() + "] terminée."); - } - } - - @Override - public void onAfterAction(ActionWorker<?, ?> source) { - long count = getNbActions(); - if (log.isDebugEnabled()) { - log.debug("Action [" + source.getActionLabel() + " ] is consumed (still " + count + " tasks to treat)."); - } - if (ObserveSwingApplicationContext.get().isClosed()) { - - // l'application est déjà fermée, on ne fait rien - return; - } - if (source instanceof ObserveCLAction.CommandLineActionWorker) { - - if (log.isInfoEnabled()) { - log.info("Action [" + source.getActionLabel() + "] terminée à " + new Date(source.getStartTime())); - } - - ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); - if (log.isDebugEnabled()) { - log.debug("Unlock main context " + context); - } - context.releaseLock(); - return; - } - if (source instanceof AdminActionWorker) { - AdminActionWorker admin = (AdminActionWorker) source; - admin.getHandler().getModel().setBusy(false); - //admin.getHandler().getUi().removePropertyChangeListener(admin.getHandler().getUi()); -// return; - } - ObserveMainUI ui = ObserveSwingApplicationContext.get().getMainUI(); - if (count < 1 && ui != null) { - ui.setBusy(false); - } - } - - /** - * Add an new worker to perform. - * - * @param worker the worker to run - * @return the worker that will launch the action - */ - public ActionWorker<?, ?> addAction(ActionWorker<?, ?> worker) { - addAction(worker.getActionLabel(), worker); - return worker; - } - - /** - * Add an new action to perform. - * - * @param actionLabel the name of the action to perform - * @param action the action to perform - * @return the worker that will launch the action - */ - public ActionWorker<?, ?> addAction(String actionLabel, Runnable action) { - - ActionWorker<?, ?> worker; - if (action instanceof ActionWorker) { - - worker = (ActionWorker<?, ?>) action; - } else { - - worker = new ActionWorker(actionLabel, action); - } - worker.addPropertyChangeListener(workerListener); - tasks.add(worker); - if (log.isDebugEnabled()) { - log.debug("Launch worker [" + actionLabel + "] now..."); - } - getWorkersExecutorService().execute(worker); - if (log.isDebugEnabled()) { - log.debug("Launch worker [" + actionLabel + "] is on..."); - } - return worker; - } - - private static ExecutorService executorService; - - /** - * On surcharge celui offer par SwingWorker car le corepool est à 1 et cela - * ne permet pas d'exécuter plusieurs actions en même temps... - * returns workersExecutorService. - * - * returns the service stored in the appContext or creates it if - * necessary. - * - * @return ExecutorService for the {@code SwingWorkers} - */ - private static ExecutorService getWorkersExecutorService() { -// AppContext appContext = AppContext.getAppContext(); -// ExecutorService executorService = -// (ExecutorService) appContext.get(ActionWorker.class); - if (executorService == null) { - //this creates daemon threads. - ThreadFactory threadFactory = - new ThreadFactory() { - final ThreadFactory defaultFactory = - Executors.defaultThreadFactory(); - - public Thread newThread(Runnable r) { - Thread thread = - defaultFactory.newThread(r); - thread.setName("ActionWorker-" - + thread.getName()); - thread.setDaemon(true); - return thread; - } - }; - - executorService = - new ThreadPoolExecutor(5, 10, - 10L, TimeUnit.MINUTES, - new LinkedBlockingQueue<>(), - threadFactory); - -// appContext.put(ActionWorker.class, executorService); - - // Don't use ShutdownHook here as it's not enough. We should track - // AppContext disposal instead of JVM shutdown, see 6799345 for details -// final ExecutorService es = executorService; - Runtime.getRuntime().addShutdownHook(new Thread() { - @Override - public void run() { - if (executorService != null) { - executorService.shutdownNow(); - } - } - }); -// appContext.addPropertyChangeListener(AppContext.DISPOSED_PROPERTY_NAME, -// new PropertyChangeListener() { -// @Override -// public void propertyChange(PropertyChangeEvent pce) { -// boolean disposed = (Boolean) pce.getNewValue(); -// if (disposed) { -// WeakReference<ExecutorService> executorServiceRef = -// new WeakReference<ExecutorService>(es); -// final ExecutorService executorService = -// executorServiceRef.get(); -// if (executorService != null) { -// AccessController.doPrivileged( -// new PrivilegedAction<Void>() { -// public Void run() { -// executorService.shutdown(); -// return null; -// } -// } -// ); -// } -// } -// } -// } -// ); - } - return executorService; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ObserveAdminCLI.java b/observe-application-swing/src/main/java/fr/ird/observe/ObserveAdminCLI.java deleted file mode 100644 index e474a4b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ObserveAdminCLI.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe; - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.Arrays; -import java.util.Date; - -/** - * Pour lancer le client swing {@code ObServe} en mode administrateur. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ObserveAdminCLI extends ObserveRunner { - - /** Logger */ - private static final Log log = LogFactory.getLog(ObserveAdminCLI.class); - - @Override - public String getRunnerName() { - return "observe"; - } - - public ObserveAdminCLI(String... args) { - super(args); - } - - public static void main(String... args) { - - log.info("ObServe admin client launch at " + - new Date() + " args: " + Arrays.toString(args)); - - new ObserveAdminCLI(args).launch(); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ObserveCLAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ObserveCLAction.java deleted file mode 100644 index 1f2b617..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ObserveCLAction.java +++ /dev/null @@ -1,399 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe; - -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.configuration.ObserveSwingApplicationConfigOption; -import fr.ird.observe.ui.ObserveMainUIHandler; -import fr.ird.observe.ui.admin.AdminStep; -import fr.ird.observe.ui.admin.AdminUILauncher; -import fr.ird.observe.ui.storage.ObstunaAdminAction; -import fr.ird.observe.ui.storage.RemoteUILauncher; -import jaxx.runtime.swing.application.ActionWorker; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.config.ConfigActionDef; - -import java.io.Console; -import java.io.IOException; -import java.util.Arrays; -import java.util.EnumSet; - -import static org.nuiton.i18n.I18n.t; - -/** - * Les actions appellables via {@link ObserveRunner}. - * - * Consulter la classe {@link ActionDefinition} pour connaitre les actions - * possibles. - * - * @author Tony Chemit - chemit@codelutin.com - * @see ObserveSwingApplicationConfig - * @see ObserveRunner - * @since 1.0 - */ -public class ObserveCLAction { - - /** Logger */ - private static final Log log = LogFactory.getLog(ObserveCLAction.class); - - /** - * Les actions appellables en ligne de commande. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ - public enum ActionDefinition implements ConfigActionDef { - /** - * Afficher l'aide dans la console. - * - * @since 1.0 - */ - HELP(false, t("observe.action.commandline.help"), - ObserveCLAction.class.getName() + "#help", "-h", "--help"), - /** - * Afficher l'aide embarqué de l'application (dans une interface - * graphique). - * - * @since 1.0 - */ - HELP_UI(false, t("observe.action.commandline.help.ui"), - ObserveCLAction.class.getName() + "#helpUI", "--help-ui"), - /** - * Pour désactiver le lancement de l'application graphique. - * - * @since 1.0 - */ - NO_MAIN_UI(false, t("observe.action.commandline.disable.main.ui"), - ObserveCLAction.class.getName() + "#disableMainUI", "-n", - "--no-main"), - /** - * Pour lancer l'interface graphique du configuration de l'application. - * - * @since 1.0 - */ - CONFIGURE_UI(false, t("observe.action.commandline.configure.ui"), - ObserveCLAction.class.getName() + "#configure", - "--configure"), - /** - * Pour lancer une opération d'administration via un assistant - * graphique. - * - * @since 1.4 - */ - ADMIN_UI(true, t("observe.action.commandline.launch.admin.ui"), - ObserveCLAction.class.getName() + "#launchAdminUI", "-a", - "--admin"), - /** - * Pour lancer une opération d'administration via un assistant - * graphique. - * - * @since 1.4 - */ - OBSTUNA_ADMIN_UI(true, t("observe.action.commandline.launch.obstuna.admin.ui"), - ObserveCLAction.class.getName() + "#launchObstunaAdminUI", - "--obstuna-admin"), - - /** - * Pour lancer la base locale en mode serveur. - * - * @since 2.1 - */ - H2_SERVER_MODE(true, t("observe.action.commandline.launch.h2.server.mode"), - ObserveCLAction.class.getName() + "#launchH2ServerMode", - "--h2-server"), - /** - * Pour activer le support JMX pour les source de données. - * - * @since 1.4 - */ - USE_JMX(true, t("observe.action.commandline.use.jmx"), - ObserveCLAction.class.getName() + "#useJMX", - "--jmx"), - - CREATE_ID(true, - t("observe.action.commandline.create.id"), - ObserveCLAction.class.getName() + "#createId", - "--create-id"); - - - public final String description; - - public final String action; - - public final String[] aliases; - - public final boolean admin; - - ActionDefinition(boolean admin, String description, String action, String... aliases) { - this.description = description; - this.action = action; - this.aliases = aliases; - this.admin = admin; - } - - public String getDescription() { - return description; - } - - public String getAction() { - return action; - } - - public String[] getAliases() { - return aliases; - } - - public boolean isAdmin() { - return admin; - } - } - - /** La configuration de l'application. */ - protected ObserveSwingApplicationConfig config; - - public ObserveCLAction() { - } - - /** Désactiver la possiblite de lancer l'ui principale. */ - public void disableMainUI() { - if (log.isDebugEnabled()) { - log.debug(this); - } - getConfig().setDisplayMainUI(false); - } - - @SuppressWarnings("unused") - public void help() { - disableMainUI(); - - StringBuilder out = new StringBuilder(); - - out.append(t("observe.message.help.usage", getConfig().getVersion())); - out.append('\n'); - out.append("Options (set with --option <key> <value>:"); - out.append('\n'); - for (ObserveSwingApplicationConfigOption o : ObserveSwingApplicationConfigOption.values()) { - - out.append("\t"); - out.append(o.getKey()); - out.append("("); - out.append(o.getDefaultValue()); - out.append(") :"); - out.append(t(o.getDescription())); - out.append('\n'); - } - - out.append("Actions:"); - out.append('\n'); - for (ActionDefinition a : ActionDefinition.values()) { - out.append("\t"); - out.append(Arrays.toString(a.aliases)); - out.append("("); - out.append(a.action); - out.append("):"); - out.append(t(a.description)); - out.append('\n'); - } - Console cons; - - if ((cons = System.console()) != null) { - cons.printf(out.toString()); - } - } - - public void configure() throws InterruptedException { - disableMainUI(); - ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); - - ObserveMainUIHandler handler = context.getContextValue(ObserveMainUIHandler.class); - - Runnable runnable = createRunnable(handler, "showConfig", context); - - launchAction(t("observe.action.showConfig.title"), runnable); - } - - @SuppressWarnings("unused") - public void launchAdminUI(String operationName) throws InterruptedException { - - disableMainUI(); - - EnumSet<AdminStep> operations = AdminStep.getOperations(); - - AdminStep operation = AdminStep.valueOfIgnoreCase(operationName); - if (operation == null) { - if (log.isErrorEnabled()) { - log.error(operationName + " is not a known admin operation."); - log.error("Use one of these ones : " + operations); - } - return; - } - - if (!operation.isOperation()) { - if (log.isErrorEnabled()) { - log.error(operation + " is not a admin operation(just a step in wizard)."); - log.error("Use one of these ones : " + operations); - } - return; - } - - ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); - - AdminUILauncher launcher = AdminUILauncher.newLauncher(context, operation); - - Runnable runnable = createRunnable(launcher, "start"); - - launchAction(t(operation.getTitle()), runnable); - } - - @SuppressWarnings("unused") - public void launchObstunaAdminUI(String operationName) throws InterruptedException { - - disableMainUI(); - - EnumSet<ObstunaAdminAction> operations = EnumSet.allOf(ObstunaAdminAction.class); - - ObstunaAdminAction operation = ObstunaAdminAction.valueOfIgnoreCase(operationName); - if (operation == null) { - if (log.isErrorEnabled()) { - log.error(operationName + " is not a known obstuna admin operation."); - log.error("Use one of these ones : " + operations); - } - return; - } - - ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); - - // FIXME -// getConfig().setOption(AbstractDataSourceMigration.AUTO_MIGRATE, "false"); - - if (operation == ObstunaAdminAction.UPDATE || - operation == ObstunaAdminAction.CREATE) { - getConfig().setOption(ObserveSwingApplicationConfigOption.OBSTUNA_CAN_MIGRATE, true); - } - - RemoteUILauncher launcher = operation.newLauncher(context, null); - - Runnable runnable = createRunnable(launcher, "start"); - launchAction(t(launcher.getTitle()), runnable); - } - - public void launchH2ServerMode() throws InterruptedException { - - if (!config.isLocalStorageExist()) { - if (log.isErrorEnabled()) { - log.error("Local database does not exist."); - } - } else { - - ObserveSwingApplicationContext.get().setContextValue( - true, - ActionDefinition.H2_SERVER_MODE.name()); - } - } - - public void createId(String className, int nbId) throws IOException { - - disableMainUI(); - -// Class<?> klazz = null; - - //FIXME -// List<ObserveEntityEnum> enums = Lists.newArrayList(Entities.ALL_ENTITIES); -// enums.remove(ObserveEntityEnum.CommentableEntity); -// enums.remove(ObserveEntityEnum.OpenableEntity); -// enums.remove(ObserveEntityEnum.I18nReferenceEntity); -// enums.remove(ObserveEntityEnum.ReferenceEntity); -// -// for (ObserveEntityEnum e : enums) { -// if (className.equals(e.name())) { -// klazz = e.getContract(); -// break; -// } -// } -// -// if (klazz == null) { -// -// Collections.sort(enums, new Comparator<ObserveEntityEnum>() { -// @Override -// public int compare(ObserveEntityEnum observeEntityEnum, ObserveEntityEnum observeEntityEnum2) { -// return observeEntityEnum.name().compareTo(observeEntityEnum2.name()); -// } -// }); -// if (log.isErrorEnabled()) { -// log.error(className + " not found! availables names :\n\t" + Joiner.on("\n\t").join(enums)); -// } -// return; -// } -// -// for (int i = 0; i < nbId; i++) { -// String topiaId = TopiaId.create(klazz); -// System.out.println(topiaId); -// } - } - - protected ObserveSwingApplicationConfig getConfig() { - if (config == null) { - config = ObserveSwingApplicationContext.get().getConfig(); - } - return config; - } - - protected Runnable createRunnable(Object invoker, String method, Object... args) { - ObserveActionExecutor executor = ObserveRunner.getActionExecutor(); - - Runnable runnable = executor.createRunnable(invoker, method, args); - return runnable; - } - - protected void launchAction(String title, Runnable target) throws InterruptedException { - ObserveActionExecutor executor = ObserveRunner.getActionExecutor(); - - CommandLineActionWorker action = new CommandLineActionWorker(title, target); - executor.addAction(action); - - // on attends la fin de l'opération - ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); - if (log.isDebugEnabled()) { - log.debug("Lock main context " + context); - } - context.lock(); - } - - /** - * Un worker pour les opération longues d'administration. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ - public class CommandLineActionWorker extends ActionWorker<Void, String> { - - public CommandLineActionWorker(String actionLabel, Runnable target) { - super(actionLabel); - setTarget(target); - } - - public ObserveCLAction getAction() { - return ObserveCLAction.this; - } - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ObserveOpenDataManager.java b/observe-application-swing/src/main/java/fr/ird/observe/ObserveOpenDataManager.java deleted file mode 100644 index 685c1e0..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ObserveOpenDataManager.java +++ /dev/null @@ -1,288 +0,0 @@ -package fr.ird.observe; - -/*- - * #%L - * ObServe :: Application Swing - * %% - * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.base.Preconditions; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.services.ObserveServicesProvider; -import fr.ird.observe.services.dto.IdDtos; -import fr.ird.observe.services.dto.referential.ProgramDto; - -import java.io.Closeable; - -/** - * Pour gérer les données ouvertes sur une source de données dans l'application. - * À l'ouverture d'une source de données rien n'est ouvert. - * Les états de cet objet sont liés au cylce de vie d'une source de données dans l'application. - * - * @author Sylvain Bavencoff - bavencoff@codelutin.com - */ -public class ObserveOpenDataManager implements Closeable { - - private final DataContext dataContext; - - public ObserveOpenDataManager(DataContext dataContext) { - this.dataContext = dataContext; - } - - // Program - public boolean canOpenProgram() { - return !dataContext.isOpenProgram(); - } - - public void openProgram(String programId) { - Preconditions.checkNotNull(programId, "id cant be null"); - Preconditions.checkState(canOpenProgram(), "a program is already opened"); - dataContext.setOpenProgramId(programId); - } - - public boolean isOpenProgram(String programId) { - Preconditions.checkNotNull(programId, "id cant be null"); - return programId.equals(dataContext.getOpenProgramId()); - } - - public void closeProgram(String programId) { - Preconditions.checkNotNull(programId, "id cant be null"); - Preconditions.checkState(isOpenProgram(programId), "this program is not opened"); - dataContext.setOpenProgramId(null); - } - - - // Trip Seine - public boolean canOpenTripSeine() { - return !dataContext.isOpenTrip(); - } - - public void openTripSeine(String programId, String tripSeineId) { - openProgram(programId); - Preconditions.checkNotNull(tripSeineId, "id cant be null"); - Preconditions.checkState(canOpenTripSeine(), "a trip is already opened"); - dataContext.setOpenTripSeineId(tripSeineId); - } - - public boolean isOpenTripSeine(String tripSeineId) { - Preconditions.checkNotNull(tripSeineId, "id cant be null"); - return tripSeineId.equals(dataContext.getOpenTripSeineId()); - } - - public void closeTripSeine(String tripSeineId) { - Preconditions.checkNotNull(tripSeineId, "id cant be null"); - Preconditions.checkState(isOpenTripSeine(tripSeineId), "this trip is not opened"); - - if (dataContext.isOpenRoute()) { - String openRouteId = dataContext.getOpenRouteId(); - closeRoute(openRouteId); - } - - dataContext.setOpenTripSeineId(null); - dataContext.setOpenProgramId(null); - } - - // Route - public boolean canOpenRoute(String parentTripSeineId) { - Preconditions.checkNotNull(parentTripSeineId, "id cant be null"); - return isOpenTripSeine(parentTripSeineId) && !dataContext.isOpenRoute(); - } - - public void openRoute(String parentTripSeineId, String routeId) { - Preconditions.checkNotNull(parentTripSeineId, "id cant be null"); - Preconditions.checkNotNull(routeId, "id cant be null"); - Preconditions.checkState(canOpenRoute(parentTripSeineId), "the trip is not opened or another route already opened"); - dataContext.setOpenRouteId(routeId); - } - - public boolean isOpenRoute(String routeId) { - Preconditions.checkNotNull(routeId, "id cant be null"); - return routeId.equals(dataContext.getOpenRouteId()); - } - - public void closeRoute(String routeId) { - Preconditions.checkNotNull(routeId, "id cant be null"); - Preconditions.checkState(isOpenRoute(routeId), "this route is not opened"); - - if (dataContext.isOpenActivitySeine()) { - String openActivitySeineId = dataContext.getOpenActivitySeineId(); - closeActivitySeine(openActivitySeineId); - } - - dataContext.setOpenRouteId(null); - } - - // Activity Seine - public boolean canOpenActivitySeine(String parentRouteId) { - Preconditions.checkNotNull(parentRouteId, "id cant be null"); - return isOpenRoute(parentRouteId) && !dataContext.isOpenActivitySeine(); - } - - public void openActivitySeine(String parentRouteId, String activitySeineId) { - Preconditions.checkNotNull(parentRouteId, "id cant be null"); - Preconditions.checkNotNull(activitySeineId, "id cant be null"); - Preconditions.checkState(canOpenActivitySeine(parentRouteId), "the route is not opened or another activity is already opened"); - dataContext.setOpenActivitySeineId(activitySeineId); - } - - public boolean isOpenActivitySeine(String activitySeineId) { - Preconditions.checkNotNull(activitySeineId, "id cant be null"); - return activitySeineId.equals(dataContext.getOpenActivitySeineId()); - } - - public void closeActivitySeine(String activitySeineId) { - Preconditions.checkNotNull(activitySeineId, "id cant be null"); - Preconditions.checkState(isOpenActivitySeine(activitySeineId), "this activity is not opened"); - dataContext.setOpenActivitySeineId(null); - } - - // Trip Longline - public boolean canOpenTripLongline() { - return !dataContext.isOpenTrip(); - } - - public void openTripLongline(String programId, String tripLongLineId) { - openProgram(programId); - Preconditions.checkNotNull(tripLongLineId, "id cant be null"); - Preconditions.checkState(canOpenTripLongline(), "a trip is already opened"); - dataContext.setOpenTripLonglineId(tripLongLineId); - } - - public boolean isOpenTripLongline(String tripLongLineId) { - Preconditions.checkNotNull(tripLongLineId, "id cant be null"); - return tripLongLineId.equals(dataContext.getOpenTripLonglineId()); - } - - public void closeTripLongline(String tripLongLineId) { - Preconditions.checkNotNull(tripLongLineId, "id cant be null"); - Preconditions.checkState(isOpenTripLongline(tripLongLineId), "this trip is not opened"); - - if (dataContext.isOpenActivityLongline()) { - String openActivityLonglineId = dataContext.getOpenActivityLonglineId(); - closeActivityLongline(openActivityLonglineId); - } - - dataContext.setOpenTripLonglineId(null); - dataContext.setOpenProgramId(null); - } - - // Activity Longline - public boolean canOpenActivityLongline(String parentTripLonglineId) { - Preconditions.checkNotNull(parentTripLonglineId, "id cant be null"); - return isOpenTripLongline(parentTripLonglineId) && !dataContext.isOpenActivityLongline(); - } - - public void openActivityLongline(String parentTripLonglineId, String activityLonglineId) { - Preconditions.checkNotNull(parentTripLonglineId, "id cant be null"); - Preconditions.checkNotNull(activityLonglineId, "id cant be null"); - Preconditions.checkState(canOpenActivityLongline(parentTripLonglineId), "the trip is not opened or another activity is already opened"); - dataContext.setOpenActivityLonglineId(activityLonglineId); - } - - public boolean isOpenActivityLongline(String activityLonglineId) { - Preconditions.checkNotNull(activityLonglineId, "id cant be null"); - return activityLonglineId.equals(dataContext.getOpenActivityLonglineId()); - } - - public void closeActivityLongline(String activityLonglineId) { - Preconditions.checkNotNull(activityLonglineId, "id cant be null"); - Preconditions.checkState(isOpenActivityLongline(activityLonglineId), "this activity is not opened"); - dataContext.setOpenActivityLonglineId(null); - } - - public boolean isOpen(String openableId) { - return isOpenTripSeine(openableId) - || isOpenRoute(openableId) - || isOpenActivitySeine(openableId) - || isOpenTripLongline(openableId) - || isOpenActivityLongline(openableId); - } - - public boolean isOpenActivity(String activityId) { - return isOpenActivitySeine(activityId) - || isOpenActivityLongline(activityId); - } - - @Override - public void close() { - dataContext.resetOpen(); - } - - public void sanitizeOpenIds(String[] ids) { - if (ids != null) { - - boolean exists = true; - - ObserveServicesProvider servicesProvider = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider(); - - for (int i = 0, l = ids.length; i < l; i++) { - String id = ids[i]; - - // si l'id précédent existe, on vérifie l'actuel - // sinon, on met à null - if (exists) { - if (IdDtos.isProgramId(id)) { - - exists = servicesProvider.newReferentialService().exists(ProgramDto.class, id); - - } else if (IdDtos.isTripSeineId(id)) { - - exists = servicesProvider.newTripSeineService().exists(id); - - } else if (IdDtos.isRouteId(id)) { - - exists = servicesProvider.newRouteService().exists(id); - - } else if (IdDtos.isActivitySeineId(id)) { - - exists = servicesProvider.newActivitySeineService().exists(id); - - } else if (IdDtos.isSetSeineId(id)) { - - exists = servicesProvider.newSetSeineService().exists(id); - - } else if (IdDtos.isFloatingObjectId(id)) { - - exists = servicesProvider.newFloatingObjectService().exists(id); - - } else if (IdDtos.isTripLonglineId(id)) { - - exists = servicesProvider.newTripLonglineService().exists(id); - - } else if (IdDtos.isActivityLonglineId(id)) { - - exists = servicesProvider.newActivityLonglineService().exists(id); - - } else if (IdDtos.isSetLonglineId(id)) { - - exists = servicesProvider.newSetLonglineService().exists(id); - - } else { - - exists = false; - } - } - - if (!exists) { - ids[i] = null; - } - } - } - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ObserveResourceManager.java b/observe-application-swing/src/main/java/fr/ird/observe/ObserveResourceManager.java deleted file mode 100644 index c176f2b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ObserveResourceManager.java +++ /dev/null @@ -1,325 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe; - -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.configuration.ObserveSwingApplicationConfigOption; -import org.apache.commons.io.IOUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.util.SortedProperties; -import org.nuiton.util.ZipUtil; - -import java.io.BufferedInputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.net.URL; -import java.util.Map; -import java.util.Properties; -import java.util.TreeMap; - -import static org.nuiton.i18n.I18n.t; - -/** - * La classe responsable du chargement de toutes les resources qui viennent de - * l'application et qui seont ensuite redispatchés dans le répertoire de - * resource de l'utilisateur. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ObserveResourceManager { - - public static final String OBSERVE_UI_PROPERTIES = "/observe-ui.properties"; - - public static final String OBSERVE_APPLICATION_PROPERTIES = "/observe-application.properties"; - - public static final String OBSERVE_REPORTS_PROPERTIES = "/observe-reports.properties"; - - public static final String OBSERVE_MAP_ARCHIVE = "/map.zip"; - - public static final String OBSERVE_LOG_CONFIGURATION_FILE_PROPERTIES = "/observe-log4j.properties"; - - /** Logger */ - private static final Log log = LogFactory.getLog(ObserveResourceManager.class); - - public enum Resource { - - ui(OBSERVE_UI_PROPERTIES), - application(OBSERVE_APPLICATION_PROPERTIES), - report(OBSERVE_REPORTS_PROPERTIES), - LOG_CONFIGURATION_FILE(OBSERVE_LOG_CONFIGURATION_FILE_PROPERTIES), - mapLayers(OBSERVE_MAP_ARCHIVE); - - private final String location; - - private URL url; - - Resource(String location) { - this.location = location; - } - - public URL getUrl() { - if (url == null) { - url = getResource(location); - } - return url; - } - - public boolean exists(File directory) { - File file = getFile(directory); - return file.exists(); - } - - public File getFile(File directory) { - File file = new File(directory, location.substring(1)); - return file; - } - - } - - protected Map<String, Properties> resources; - - public Map<String, Properties> getResources() { - if (resources == null) { - resources = new TreeMap<>(); - } - return resources; - } - - - public Properties getResource(Resource resource) throws IOException { - - URL url = resource.getUrl(); - Properties result = getResource(url); - return result; - } - - public Properties getResource(File file) throws IOException { - - URL url = file.toURI().toURL(); - - Properties result = load(url); - - return result; - } - - - public Properties getResource(URL url) throws IOException { - - String path = url.toString(); - - Properties result = getResources().get(path); - - if (result == null) { - - result = load(url); - - // on sauvegarde dans le cache - if (log.isDebugEnabled()) { - log.debug("Store configuration [" + path + "]"); - } - getResources().put(path, result); - } - - // toujours faire une copie pour eviter toute altération des - // configuration par défaut. - SortedProperties tmp = new SortedProperties(); - tmp.putAll(result); - return tmp; - } - - protected Properties load(URL url) throws IOException { - Properties result;// chargement une unique fois de la resource - InputStream in = openInternalStream(url); - - try { - result = new Properties(); - result.load(in); - - - } finally { - in.close(); - } - return result; - } - - public void copyResource(Resource resource, - File file, - String message) throws IOException { - - FileOutputStream out = new FileOutputStream(file); - try { - // on fait une copie brute en ne passant pas par un Properties - // qui perd le formatage et les commentaires - - // chargement des ressources - InputStreamReader in = - new InputStreamReader( - new BufferedInputStream( - openInternalStream(resource.getUrl())), - "utf-8"); - - // sauvegarde dans le fichier cible - try { - IOUtils.copy(in, out, "utf-8"); - } finally { - in.close(); - } - - if (log.isInfoEnabled()) { - log.info(message); - } - } finally { - out.close(); - } - } - - public void copyResource(URL resource, - File file, - String message) throws IOException { - - FileOutputStream out = new FileOutputStream(file); - try { - // on fait une copie brute en ne passant pas par un Properties - // qui perd le formatage et les commentaires - - // chargement des ressources - InputStreamReader in = - new InputStreamReader( - new BufferedInputStream( - openInternalStream(resource)), - "utf-8"); - - // sauvegarde dans le fichier cible - try { - IOUtils.copy(in, out, "utf-8"); - in.close(); - } finally { - IOUtils.closeQuietly(in); - } - - if (log.isInfoEnabled()) { - log.info(message); - } - out.close(); - } finally { - IOUtils.closeQuietly(out); - } - } - - /** - * Créer le répertoire si nécessaire à partir le l'option donnée. - * - * @param config la configuration utilisée - * @param option l'option qui représentent le répertoire. - * @return le fichier - * @throws IOException pour tout problème de création de répertoire - */ - protected File createDirectory(ObserveSwingApplicationConfig config, - ObserveSwingApplicationConfigOption option) throws IOException { - File dir = config.getOptionAsFile(option.getKey()); - createDirectory(dir); - return dir; - } - - /** - * Créer tous les répertoires parents nécessaires à partir des options sur - * répertoire ou fichier. - * - * @param config la configuration utilisée - * @param options les options qui représentent des répertoires ou fichiers. - * @throws IOException pour tout problème de création de répertoire - */ - protected void createParentDirectory(ObserveSwingApplicationConfig config, - ObserveSwingApplicationConfigOption... options) throws IOException { - for (ObserveSwingApplicationConfigOption option : options) { - File dir = config.getOptionAsFile(option.getKey()).getParentFile(); - createDirectory(dir); - } - } - - /** - * Créer un répertoire s'il n'existe pas. - * - * @param dir le répertoire à créer - * @throws IOException pour tout problème de création de répertoire - */ - protected void createDirectory(File dir) throws IOException { - - if (!dir.exists()) { - if (log.isInfoEnabled()) { - log.info(t("observe.runner.create.directory", dir)); - } else { - log.info(t("observe.runner.exists.directory", dir)); - } - boolean b = dir.mkdirs(); - if (!b) { - throw new IOException( - t("observe.error.can.not.create.directory", dir)); - } - } - } - - protected static URL getResource(String location) { - URL resource = ObserveResourceManager.class.getResource(location); - try { - // test que la resource existe bien dans le class-path - InputStream in = openInternalStream(resource); - in.close(); - return resource; - } catch (Exception e) { - throw new IllegalStateException("Could not treat internal resource " + location); - } - } - - protected static InputStream openInternalStream(URL resource) { - try { - InputStream in = resource.openStream(); - if (in == null) { - throw new IllegalStateException("Could not find internal resource " + resource); - } - - return in; - } catch (Exception e) { - throw new IllegalStateException("Could not treat internal resource " + resource); - } - } - - public File unzipToDirectory(Resource resource, ObserveSwingApplicationConfig config, ObserveSwingApplicationConfigOption option, String message) throws IOException { - - File dir = config.getOptionAsFile(option.getKey()); - createDirectory(dir); - InputStream inputStream = openInternalStream(resource.getUrl()); - try { - ZipUtil.uncompress(inputStream, dir); - return dir; - } finally { - inputStream.close(); - - } - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ObserveRunner.java b/observe-application-swing/src/main/java/fr/ird/observe/ObserveRunner.java deleted file mode 100644 index 36686b0..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ObserveRunner.java +++ /dev/null @@ -1,650 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe; - -import com.google.common.base.Preconditions; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.ObserveMainUIHandler; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.actions.StartServerModeAction; -import fr.ird.observe.ui.util.FloatConverter; -import jaxx.runtime.FileChooserUtil; -import jaxx.runtime.swing.application.ApplicationRunner; -import org.apache.commons.beanutils.ConvertUtils; -import org.apache.commons.beanutils.Converter; -import org.apache.commons.beanutils.converters.DateConverter; -import org.apache.commons.io.FileUtils; -import org.apache.commons.lang3.BooleanUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.apache.log4j.LogManager; -import org.apache.log4j.PropertyConfigurator; -import org.jdesktop.swingx.plaf.basic.CalendarHeaderHandler; -import org.jdesktop.swingx.plaf.basic.SpinningCalendarHeaderHandler; -import org.nuiton.converter.ConverterUtil; -import org.nuiton.i18n.I18n; -import org.nuiton.i18n.init.DefaultI18nInitializer; -import org.nuiton.i18n.init.UserI18nInitializer; -import org.nuiton.util.StringUtil; - -import javax.script.ScriptEngine; -import javax.script.ScriptEngineManager; -import javax.script.ScriptException; -import javax.swing.UIManager; -import java.io.File; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.util.Arrays; -import java.util.Date; -import java.util.Locale; -import java.util.Map; -import java.util.Properties; - -import static fr.ird.observe.ObserveResourceManager.Resource; -import static fr.ird.observe.ObserveSwingApplicationContext.Entries.H2_SERVER_MODE; -import static fr.ird.observe.configuration.ObserveSwingApplicationConfigOption.BACKUP_DIRECTORY; -import static fr.ird.observe.configuration.ObserveSwingApplicationConfigOption.DATA_DIRECTORY; -import static fr.ird.observe.configuration.ObserveSwingApplicationConfigOption.DB_DIRECTORY; -import static fr.ird.observe.configuration.ObserveSwingApplicationConfigOption.INITIAL_DB_DUMP; -import static fr.ird.observe.configuration.ObserveSwingApplicationConfigOption.MAP_DIRECTORY; -import static fr.ird.observe.configuration.ObserveSwingApplicationConfigOption.REPORT_DIRECTORY; -import static fr.ird.observe.configuration.ObserveSwingApplicationConfigOption.RESOURCES_DIRECTORY; -import static fr.ird.observe.configuration.ObserveSwingApplicationConfigOption.TMP_DIRECTORY; -import static fr.ird.observe.configuration.ObserveSwingApplicationConfigOption.VALIDATION_REPORT_DIRECTORY; -import static org.nuiton.i18n.I18n.t; - -/** - * Le lanceur de l'application ObServe. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public abstract class ObserveRunner extends ApplicationRunner { - - /** Logger */ - private static Log log = LogFactory.getLog(ObserveRunner.class); - - protected static ObserveResourceManager resourceManager; - - protected static ObserveActionExecutor actionExecutor; - - public static ObserveRunner getRunner() { - return (ObserveRunner) ApplicationRunner.getRunner(); - } - -// public static ObserveResourceManager getResourceManager() { -// if (resourceManager == null) { -// throw new IllegalStateException("No resourceManager initialized"); -// } -// return resourceManager; -// } - - public static ObserveActionExecutor getActionExecutor() { - if (actionExecutor == null) { - actionExecutor = new ObserveActionExecutor(); - } - return actionExecutor; - } - - public abstract String getRunnerName(); - -// public static boolean isAdmin() { -// return true; -// } - - public final boolean init; - - public ObserveRunner(String... args) { - super(args); - init = true; - initOnce(); - } - - public static void runAction(String actionLabel, Runnable action) { - getActionExecutor().addAction(actionLabel, action); - } - - public static void runAction(String actionLabel, - Object invoker, - String methodName, - Object... arguments) { - Runnable action; - try { - action = getActionExecutor().createRunnable( - invoker, - methodName, - arguments - ); - } catch (Exception e) { - throw new RuntimeException( - "could not create action " + actionLabel, e); - } - runAction(actionLabel, action); - } - - @Override - protected void initOnce() { - if (!init) { - return; - } - - // check script engine exist - checkScriptEngineFound(); - - // on veut avoir les traductions dès le début - // on charge dans un premier temps les traductions fournies - // par l'application - I18n.init(new DefaultI18nInitializer("observe-i18n"), null); - - // to enable javassist on webstart, must remove any securityManager, - // see if this can be dangerous (should not be since jnlp is signed ?) - // moreover it speeds up the loading :) -// System.setSecurityManager(null); - - resourceManager = new ObserveResourceManager(); - - // initialisation des converteurs - - Converter converter = ConverterUtil.getConverter(Date.class); - if (converter != null) { - ConvertUtils.deregister(Date.class); - } - DateConverter dateConverter = new DateConverter(); - dateConverter.setUseLocaleFormat(true); - ConvertUtils.register(dateConverter, Date.class); - - converter = ConverterUtil.getConverter(Float.class); - if (converter != null) { - ConvertUtils.deregister(Float.class); - } - ConvertUtils.register(new FloatConverter(), Float.class); - - // initialisation du thread d'action - getActionExecutor(); - - UIManager.put(CalendarHeaderHandler.uiControllerID, SpinningCalendarHeaderHandler.class.getName()); - UIManager.put(SpinningCalendarHeaderHandler.ARROWS_SURROUND_MONTH, true); - UIManager.put(SpinningCalendarHeaderHandler.FOCUSABLE_SPINNER_TEXT, true); - } - - @Override - protected void onInit() throws Exception { - - if (log.isInfoEnabled()) { - log.info(t("observe.runner.init", new Date(), - Arrays.toString(args))); - } - - long t0 = System.nanoTime(); - - // 1 - preparation de la configuration - - ObserveSwingApplicationConfig config = initConfig(); - - if (log.isInfoEnabled()) { - log.info(t("observe.runner.config.loaded", config.getVersion())); - } - - // 2 - preparation des répertoires utilisateurs - - initUserDirectories(config); - - // 3 - Chargement de la configuration des logs utilisateur - if (!config.isDevMode()) { - initLog(config); - } - - if (log.isInfoEnabled()) { - log.info(t("observe.runner.user.directories.loaded", config.getDataDirectory())); - } - - // 3 - preparation i18n - - initI18n(config); - - if (log.isInfoEnabled()) { - log.info(t("observe.runner.i18n.loaded", config.getLocale().getDisplayLanguage())); - } - - // 4 - preparation de la configuration des ui - - initUIConfiguration(config); - - // 5 - preparation du context applicatif - - ObserveSwingApplicationContext applicationContext = new ObserveSwingApplicationContext(config); - - // 6 - détection de la base locale - - detectLocalDataBase(config); - - String time = StringUtil.convertTime(t0, System.nanoTime()); - - if (log.isInfoEnabled()) { - log.info(t("observe.runner.context.loaded", time)); - } - } - - protected void initLog(ObserveSwingApplicationConfig config) throws IOException { - - File logFile = config.getLogConfigurationFile(); - Preconditions.checkState(logFile.exists(), "Le fichier de configuration des logs %s n'existe pas.", logFile); - - URL resource; - try { - resource = logFile.toURI().toURL(); - } catch (MalformedURLException mue) { - throw new ObserveSwingTechnicalException("Unable to load log configuration", mue); - } - - if (log.isInfoEnabled()) { - log.info("Chargement du fichier de de log4j depuis " + resource); - } - Properties logConfigurationProperties = resourceManager.load(resource); - Properties finalLogConfigurationProperties = new Properties(); - for (Map.Entry<Object, Object> entry : logConfigurationProperties.entrySet()) { - String key = (String) entry.getKey(); - String value = (String) entry.getValue(); - String newValue = config.replaceRecursiveOptions(value); - finalLogConfigurationProperties.setProperty(key, newValue); - } - LogManager.resetConfiguration(); - PropertyConfigurator.configure(finalLogConfigurationProperties); - - log = LogFactory.getLog(ObserveRunner.class); - if (log.isInfoEnabled()) { - log.info("Initialisation des logs depuis " + logFile); - } - - } - - @Override - protected void onStart() throws Exception { - - if (log.isInfoEnabled()) { - log.info(t("observe.runner.start", new Date(), Arrays.toString(args))); - } - - ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); - - if (log.isDebugEnabled()) { - log.debug("Will use context : " + context); - } - - // 1 - launch commandline actions - - ObserveSwingApplicationConfig config = context.getConfig(); - - if (config.containActions(ObserveSwingApplicationConfig.Step.AfterInit)) { - - config.doAction(ObserveSwingApplicationConfig.Step.AfterInit.ordinal()); - - if (log.isInfoEnabled()) { - log.info("Operation terminées..."); - } - } - - if (!config.isDisplayMainUI()) { - if (log.isInfoEnabled()) { - log.info(t("observe.runner.quit.withno.ui")); - } - - unlock(); - return; - } - - // 2 - init ui - - ObserveMainUI ui = startUI(context, config); - - if (log.isInfoEnabled()) { - log.info(t("observe.runner.ui.loaded")); - } - - Boolean h2ServerMode = H2_SERVER_MODE.get(); - - if (BooleanUtils.isTrue(h2ServerMode)) { - - // starts in h2 server mode - - ObserveSwingApplicationContext.get().removeH2ServerMode(); - - new StartServerModeAction(ui).run(); - - // on ne charge rien au démarrage - ui.getStatus().setStatus(t("observe.runner.loaded", config.getVersion())); - - return; - } - if (!config.isLoadLocalStorage()) { - - // on ne charge rien au démarrage - ui.getStatus().setStatus(t("observe.runner.loaded", config.getVersion())); - return; - } - - // 3 - init storage - - runAction(t("observe.runner.load.database"), context, "initStorage", config, ui, true); - - } - - @Override - protected void onClose(boolean reload) throws Exception { - if (ObserveSwingApplicationContext.isInit()) { - - if (log.isDebugEnabled()) { - log.debug("Will close context..."); - } - ObserveSwingApplicationContext.get().close(); - } - } - - @Override - protected void onShutdown() throws Exception { - if (log.isInfoEnabled()) { - log.info("ObServe shutdown at " + new Date()); - } - - try { - - // on éteint le context applicatif - onClose(false); - - // on ferme le service de traduction uniquement si on quitte - // definitivement l'application - I18n.close(); - - getActionExecutor().terminatesAndWaits(); - - } finally { - - Runtime.getRuntime().halt(0); - - } - - - } - - @Override - protected void onShutdown(Exception ex) { - if (log.isErrorEnabled()) { - log.error("error while closing " + ex.getMessage(), ex); - } - Runtime.getRuntime().halt(1); - } - - @Override - protected void onError(Exception e) { - UIHelper.handlingError(e); - } - - protected ObserveSwingApplicationConfig initConfig() throws Exception { - - ObserveSwingApplicationConfig config = new ObserveSwingApplicationConfig(); - - // init config (load application configuration) - config.initConfig(resourceManager); - - // init config arguments - config.parse(args); - - // install save action on option modification - config.installSaveAction(); - - if (log.isInfoEnabled()) { - String message = config.getConfigurationDescription(); - log.info(message); - } - - return config; - } - - protected void initUserDirectories(ObserveSwingApplicationConfig config) throws IOException { - - // 1 - user data directory - - File dataDirectory = resourceManager.createDirectory(config, DATA_DIRECTORY); - - if (log.isDebugEnabled()) { - log.debug("user data directory : " + dataDirectory); - } - - FileChooserUtil.setCurrentDirectory(dataDirectory); - - resourceManager.createParentDirectory(config, DB_DIRECTORY, INITIAL_DB_DUMP); - - // 2 - tmp directory - - resourceManager.createDirectory(config, TMP_DIRECTORY); - - // suppression du contenu du répertoire temporaire - FileUtils.cleanDirectory(config.getTmpDirectory()); - - // 3 - backup directory - - resourceManager.createDirectory(config, BACKUP_DIRECTORY); - - // 4 - resources directory - - File resourcesDirectory = resourceManager.createDirectory(config, RESOURCES_DIRECTORY); - - if (log.isDebugEnabled()) { - log.debug("user resource data directory : " + resourcesDirectory); - } - - // 5 - application ui - - File file = Resource.ui.getFile(resourcesDirectory); - - if (!file.exists()) { - - String message = t("observe.runner.copy.default.ui.file", file); - - resourceManager.copyResource(Resource.ui, file, message); - } - - // 6 - resources log configuration file - - file = Resource.LOG_CONFIGURATION_FILE.getFile(resourcesDirectory); - - if (!file.exists()) { - - String message = t("observe.runner.copy.default.logConfigurationFile.file", file); - - resourceManager.copyResource(Resource.LOG_CONFIGURATION_FILE, file, message); - - } - - // 7 - resources report - - File reportDirectory = resourceManager.createDirectory(config, REPORT_DIRECTORY); - - file = Resource.report.getFile(reportDirectory); - - if (!file.exists()) { - - String message = t("observe.runner.copy.default.report.file", file); - - resourceManager.copyResource(Resource.report, file, message); - - } - - // 8 - validation report directory - - resourceManager.createDirectory(config, VALIDATION_REPORT_DIRECTORY); - - // 9 - resources shapeFiles - - File mapdirectory = resourceManager.createDirectory(config, MAP_DIRECTORY); - - String message = t("observe.runner.copy.default.map.file", mapdirectory); - - resourceManager.unzipToDirectory(Resource.mapLayers, config, RESOURCES_DIRECTORY, message); - - } - - protected void detectLocalDataBase(ObserveSwingApplicationConfig config) { - boolean hasLocalStorage = new File(config.getLocalDBDirectory(), ObserveSwingApplicationConfig.DB_NAME).exists(); - config.setLocalStorageExist(hasLocalStorage); - if (!hasLocalStorage) { - if (log.isInfoEnabled()) { - log.info(t("observe.init.no.local.db.detected", config.getLocalDBDirectory())); - } - } - - boolean hasInitialDb = config.getInitialDbDump().exists(); - config.setInitialDumpExist(hasInitialDb); - - if (!hasInitialDb) { - if (log.isInfoEnabled()) { - log.info(t("observe.init.no.initial.dump.detected", config.getInitialDbDump())); - } - } - } - - protected void initI18n(ObserveSwingApplicationConfig config) { - - I18n.close(); - - File i18nDirectory = config.getI18nDirectory(); - - UserI18nInitializer i18nInitializer = new UserI18nInitializer(i18nDirectory, new DefaultI18nInitializer("observe-i18n")) { - - @Override - protected void createUserI18nLayout(File directory) throws Exception { - super.createUserI18nLayout(directory); - - // add also the i18n csv bundle - - URL resource = ObserveResourceManager.getResource("/META-INF/observe-i18n.csv"); - resourceManager.copyResource(resource, new File(directory, "observe-i18n.csv"), "Copy i18n csv bundle"); - } - }; - - long t00 = System.nanoTime(); - - Locale locale = config.getLocale(); - - I18n.init(i18nInitializer, locale); - - if (log.isDebugEnabled()) { - log.debug("i18n language : " + locale); - log.debug("i18n loading time : " + StringUtil.convertTime(t00, System.nanoTime())); - } - } - - protected void initUIConfiguration(ObserveSwingApplicationConfig config) { - - // prepare ui look&feel and load ui properties - try { - UIHelper.initNimbusLoookAndFeel(); - } catch (Exception e) { - // could not find nimbus look-and-feel - if (log.isWarnEnabled()) { - log.warn(t("observe.warning.nimbus.landf")); - } - } catch (Throwable e) { - if (log.isWarnEnabled()) { - log.warn(t("observe.warning.no.ui")); - } - // pas d'environnement d'ui - config.setCanUseUI(false); - } - - if (config.isCanUseUI()) { - - // chargement de la configuration des uis - loadUIConfig(config); - - } - } - - public void loadUIConfig(ObserveSwingApplicationConfig config) { - - // chargement de la configuration des uis - File dir = config.getResourcesDirectory(); - File file = Resource.ui.getFile(dir); - - - if (!file.exists()) { - - String message = t("observe.runner.copy.default.ui.file", file); - - try { - resourceManager.copyResource(Resource.ui, file, message); - } catch (IOException e) { - throw new ObserveSwingTechnicalException("could not copy ui configuration: " + file, e); - } - } - - if (log.isInfoEnabled()) { - log.info(t("observe.runner.loading.ui.configuration", file)); - } - try { - Properties p = resourceManager.getResource(file); - UIHelper.loadUIConfig(p); - } catch (IOException e) { - - throw new ObserveSwingTechnicalException("could not load ui configuration: " + file, e); - - } - - } - - protected ObserveMainUI startUI(ObserveSwingApplicationContext context, ObserveSwingApplicationConfig config) { - - ObserveMainUIHandler uiHandler = context.getContextValue(ObserveMainUIHandler.class); - - ObserveMainUI ui = uiHandler.initUI(context, config); - - UIHelper.setMainUIVisible(ui); - return ui; - } - - /** - * Method pour vérifier que le moteur de scripting est bien présent. - * - * Voir http://forge.codelutin.com/issues/829 - * - * @since 2.5 - */ - protected void checkScriptEngineFound() { - - ScriptEngineManager factory = new ScriptEngineManager(); - - ScriptEngine scriptEngine = factory.getEngineByExtension("js"); - - if (scriptEngine == null) { - - // script engine pas trouvé. - String message = "Could not found script engine, use a Oracle jvm"; - if (Locale.FRANCE.getCountry().equals(Locale.getDefault().getCountry())) { - message = "Moteur de scripting non trouvé, Utiliser une jvm fournie par Oracle."; - } - onError(new ScriptException(message)); - } - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ObserveSwingApplicationContext.java b/observe-application-swing/src/main/java/fr/ird/observe/ObserveSwingApplicationContext.java deleted file mode 100644 index 7583d5b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ObserveSwingApplicationContext.java +++ /dev/null @@ -1,715 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe; - -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.db.constants.DbMode; -import fr.ird.observe.db.event.ObserveSwingDataSourceEvent; -import fr.ird.observe.db.event.ObserveSwingDataSourceListenerAdapter; -import fr.ird.observe.services.ObserveDataSourceConfigurationMainFactory; -import fr.ird.observe.services.ObserveServiceMainFactory; -import fr.ird.observe.services.ObserveServicesProvider; -import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaH2; -import fr.ird.observe.services.configuration.ObserveDataSourceInformation; -import fr.ird.observe.services.dto.constants.ReferentialLocale; -import fr.ird.observe.services.dto.reference.ReferenceBinderEngine; -import fr.ird.observe.services.dto.reference.ReferenceBinderEngineSupplier; -import fr.ird.observe.services.service.BabModelVersionException; -import fr.ird.observe.services.service.DatabaseConnexionNotAuthorizedException; -import fr.ird.observe.services.service.DatabaseNotFoundException; -import fr.ird.observe.services.service.actions.validate.ValidateServiceUtils; -import fr.ird.observe.services.service.actions.validate.ValidatorDto; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.ObserveUIMode; -import fr.ird.observe.ui.actions.ChangeStorageAction; -import fr.ird.observe.ui.actions.shared.AbstractUIAction; -import fr.ird.observe.ui.actions.shared.CancelCreateUIAction; -import fr.ird.observe.ui.actions.shared.CloseAndCreateUIAction; -import fr.ird.observe.ui.actions.shared.CloseOpenUIAction; -import fr.ird.observe.ui.actions.shared.DeleteDataUIAction; -import fr.ird.observe.ui.actions.shared.DeleteReferenceUIAction; -import fr.ird.observe.ui.actions.shared.GoDownUIAction; -import fr.ird.observe.ui.actions.shared.GoUpUIAction; -import fr.ird.observe.ui.actions.shared.MoveActivityLonglinesUIAction; -import fr.ird.observe.ui.actions.shared.MoveActivitySeinesUIAction; -import fr.ird.observe.ui.actions.shared.MoveRoutesUIAction; -import fr.ird.observe.ui.actions.shared.MoveTripLonglinesUIAction; -import fr.ird.observe.ui.actions.shared.MoveTripSeinesUIAction; -import fr.ird.observe.ui.actions.shared.ReOpenUIAction; -import fr.ird.observe.ui.actions.shared.ResetEditUIAction; -import fr.ird.observe.ui.actions.shared.SaveEditUIAction; -import fr.ird.observe.ui.actions.shared.SelectNodeUIAction; -import fr.ird.observe.ui.actions.shared.SelectOpenNodeUIAction; -import fr.ird.observe.ui.content.ContentUIManager; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.validation.ValidationContext; -import jaxx.runtime.context.DefaultApplicationContext; -import jaxx.runtime.context.JAXXContextEntryDef; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.h2.tools.Server; - -import javax.swing.ActionMap; -import javax.swing.JOptionPane; -import java.io.Closeable; -import java.io.File; -import java.util.Arrays; -import java.util.Collection; -import java.util.EnumSet; -import java.util.List; -import java.util.Objects; -import java.util.Set; -import java.util.UUID; - -import static fr.ird.observe.ObserveSwingApplicationContext.Entries.ACTIONS; -import static fr.ird.observe.ObserveSwingApplicationContext.Entries.ACTION_MAP; -import static fr.ird.observe.ObserveSwingApplicationContext.Entries.BINDER_SERVICE; -import static fr.ird.observe.ObserveSwingApplicationContext.Entries.CONFIG; -import static fr.ird.observe.ObserveSwingApplicationContext.Entries.CONTENT_UI_MANAGER; -import static fr.ird.observe.ObserveSwingApplicationContext.Entries.DATA_CONTEXT; -import static fr.ird.observe.ObserveSwingApplicationContext.Entries.DATA_SOURCES_MANAGER; -import static fr.ird.observe.ObserveSwingApplicationContext.Entries.DATA_SOURCE_CONFIGURATION_FACTORY; -import static fr.ird.observe.ObserveSwingApplicationContext.Entries.DECORATOR_SERVICE; -import static fr.ird.observe.ObserveSwingApplicationContext.Entries.H2_SERVER; -import static fr.ird.observe.ObserveSwingApplicationContext.Entries.H2_SERVER_MODE; -import static fr.ird.observe.ObserveSwingApplicationContext.Entries.H2_WEBSERVER; -import static fr.ird.observe.ObserveSwingApplicationContext.Entries.MAIN_UI; -import static fr.ird.observe.ObserveSwingApplicationContext.Entries.NODE_TO_RESELECT; -import static fr.ird.observe.ObserveSwingApplicationContext.Entries.OPEN_DATA_MANAGER; -import static fr.ird.observe.ObserveSwingApplicationContext.Entries.TEXT_GENERATOR; -import static fr.ird.observe.ObserveSwingApplicationContext.Entries.VALIDATION_CONTEXT; -import static fr.ird.observe.ObserveSwingApplicationContext.Entries.VALIDATORS; -import static fr.ird.observe.ui.UIHelper.askUser; -import static fr.ird.observe.ui.UIHelper.displayInfo; -import static fr.ird.observe.ui.UIHelper.handlingError; -import static fr.ird.observe.ui.UIHelper.newContextEntryDef; -import static fr.ird.observe.ui.UIHelper.newListContextEntryDef; -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Le contexte de l'application. - * - * On définit ici toutes les entrées du contexte. - * - * Note : cette classe possède une instance partagée accéssible via la méthode - * {@link #get()}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class ObserveSwingApplicationContext extends DefaultApplicationContext implements Closeable { - - /** Logger */ - private static final Log log = LogFactory.getLog(ObserveSwingApplicationContext.class); - - enum Entries { - - CONFIG("Config", ObserveSwingApplicationConfig.class), - DECORATOR_SERVICE("Decorator service", DecoratorService.class), - TEXT_GENERATOR("Text generator", ObserveTextGenerator.class), - SERVICE_MAIN_FACTORY("Service main factory", ObserveServiceMainFactory.class), - DATA_SOURCE_CONFIGURATION_FACTORY("Data source configuration main factory", ObserveDataSourceConfigurationMainFactory.class), - OPEN_DATA_MANAGER("Open data manager", ObserveOpenDataManager.class), - BINDER_SERVICE("Binder service", ObserveSwingBinderService.class), - DATA_CONTEXT("Data context", DataContext.class), - CONTENT_UI_MANAGER("Content UI manager", ContentUIManager.class), - DATA_SOURCES_MANAGER("Data sources manager", ObserveSwingApplicationDataSourcesManager.class), - VALIDATION_CONTEXT("Validation context", ValidationContext.class), - MAIN_UI("Main UI", ObserveMainUI.class), - ACTIONS("Command line Actions", ObserveCLAction.class), - ACTION_MAP("UI Actions", ActionMap.class), - H2_SERVER_MODE("H2 Server mode", Boolean.class), - H2_SERVER("H2 Server", Server.class), - H2_WEBSERVER("H2 Web server", Server.class), - VALIDATORS("Validators"), - NODE_TO_RESELECT("Node to reselect"); - - private final String objectName; - private final JAXXContextEntryDef entryDef; - - <O> Entries(String objectName, Class<O> entryType) { - this.objectName = objectName; - this.entryDef = newContextEntryDef(objectName, entryType); - } - - <O> Entries(String objectName) { - this.objectName = objectName; - this.entryDef = newListContextEntryDef(objectName); - } - - public <O> O get() { - return (O) entryDef.getContextValue(ObserveSwingApplicationContext.get()); - } - - private <O> void set(O instance) { - entryDef.setContextValue(ObserveSwingApplicationContext.get(), instance); - if (log.isInfoEnabled()) { - log.info("Add to application context " + objectName + ": " + (instance instanceof Collection ? ((Collection)instance).size()+" element(s)": instance)); - } - } - - private <O> void remove() { - O instance = get(); - entryDef.removeContextValue(ObserveSwingApplicationContext.get()); - if (log.isInfoEnabled()) { - log.info("Remove from application context " + objectName + ": " + (instance instanceof Collection ? ((Collection)instance).size()+" element(s)": instance)); - } - } - } - - private static ObserveSwingApplicationContext INSTANCE; - - /** Un objet pour bloquer le context */ - private final Object lock; - - private final ReferenceBinderEngine referenceBinderEngine; - - /** Un drapeau pour savoir quand l'application est en cours de fermeture. */ - private boolean closed; - - /** - * Un drapeau pour activer sur les connections le support JMX. - * - * @since 2.2 - */ - private boolean useJMX; - - /** - * Récupération du contexte applicatif. - * - * @return l'instance partagé du contexte. - * @throws IllegalStateException si le contexte n'a pas été initialisé - */ - public static ObserveSwingApplicationContext get() throws IllegalStateException { - Objects.requireNonNull(INSTANCE, "no application context initialized."); - return INSTANCE; - } - - /** @return {@code true} si le context a été initialisé */ - public static boolean isInit() { - return INSTANCE != null; - } - - public ObserveSwingApplicationContext(ObserveSwingApplicationConfig config) { - - Preconditions.checkState(INSTANCE == null, "application context already registred."); - - INSTANCE = this; - - CONFIG.set(config); - BINDER_SERVICE.set(new ObserveSwingBinderService()); - ACTIONS.set(new ObserveCLAction()); - CONTENT_UI_MANAGER.set(new ContentUIManager()); - DATA_SOURCES_MANAGER.set(new ObserveSwingApplicationDataSourcesManager()); - DATA_SOURCE_CONFIGURATION_FACTORY.set(new ObserveDataSourceConfigurationMainFactory()); - DECORATOR_SERVICE.set(new DecoratorService(ReferentialLocale.valueOf(config.getDbLocale()))); - TEXT_GENERATOR.set(new ObserveTextGenerator(config)); - DATA_CONTEXT.set(new DataContext()); - OPEN_DATA_MANAGER.set(new ObserveOpenDataManager(getDataContext())); - VALIDATION_CONTEXT.set(new ValidationContext(getDataContext())); - VALIDATORS.set(Lists.newArrayList(ValidateServiceUtils.getValidators())); - referenceBinderEngine = new ReferenceBinderEngineSupplier().get(); - lock = new Object(); - } - - //------------------------------------------- - // - Read - //------------------------------------------- - - public boolean isUseJMX() { - return useJMX; - } - - /** - * @return {@code true} si le context applicatif a été fermé (et est donc - * passé dans la méthode {@link #close()}, {@code false} autrement. - */ - public boolean isClosed() { - return closed; - } - - public ObserveSwingApplicationConfig getConfig() { - return CONFIG.get(); - } - - public ContentUIManager getContentUIManager() { - return CONTENT_UI_MANAGER.get(); - } - - public ObserveSwingApplicationDataSourcesManager getDataSourcesManager() { - return DATA_SOURCES_MANAGER.get(); - } - - public ReferenceBinderEngine getReferenceBinderEngine() { - return referenceBinderEngine; - } - - public DecoratorService getDecoratorService() { - return DECORATOR_SERVICE.get(); - } - - public ObserveTextGenerator getTextGenerator() { - return TEXT_GENERATOR.get(); - } - - public ObserveOpenDataManager getOpenDataManager() { - return OPEN_DATA_MANAGER.get(); - } - - public ObserveDataSourceConfigurationMainFactory getObserveDataSourceConfigurationMainFactory() { - return DATA_SOURCE_CONFIGURATION_FACTORY.get(); - } - - public ObserveServicesProvider getMainDataSourceServicesProvider() { - return getDataSourcesManager().getMainDataSource(); - } - - public DataContext getDataContext() { - return DATA_CONTEXT.get(); - } - - public ValidationContext getValidationContext() { - return VALIDATION_CONTEXT.get(); - } - - public final ImmutableSet<ValidatorDto> getValidators() { - return ImmutableSet.copyOf((List) VALIDATORS.get()); - } - - public ObserveMainUI getMainUI() { - return MAIN_UI.get(); - } - - public List<String> getNodesToReselect() { - return NODE_TO_RESELECT.get(); - } - - public ActionMap getActionMap() { - return ACTION_MAP.get(); - } - - public Server getH2Server() { - return H2_SERVER.get(); - } - - public Server getH2WebServer() { - return H2_WEBSERVER.get(); - } - - //------------------------------------------- - // - Write - //------------------------------------------- - - public void setUseJMX(boolean useJMX) { - this.useJMX = useJMX; - } - - public void setNodesToReselect(String[] paths) { - if (paths == null) { - NODE_TO_RESELECT.remove(); - - } else { - NODE_TO_RESELECT.set(Arrays.asList(paths)); - } - } - - public void setH2Server(Server server) { - H2_SERVER.set(server); - } - - public void setH2WebServer(Server server) { - H2_WEBSERVER.set(server); - } - - public void setMainUI(ObserveMainUI ui) { - MAIN_UI.set(ui); - } - - public void removeMainUI() { - MAIN_UI.remove(); - } - - public void removeH2ServerMode() { - H2_SERVER_MODE.remove(); - } - - - public void registerShareActions() { - - ObserveMainUI ui = getMainUI(); - ActionMap actionMap = ui.getRootPane().getActionMap(); - - ACTION_MAP.set(actionMap); - - registerMainAction(actionMap, new SelectOpenNodeUIAction(ui)); - registerMainAction(actionMap, new SelectNodeUIAction(ui)); - registerMainAction(actionMap, new GoUpUIAction(ui)); - registerMainAction(actionMap, new GoDownUIAction(ui)); - registerMainAction(actionMap, new ReOpenUIAction(ui)); - registerMainAction(actionMap, new CloseOpenUIAction(ui)); - registerMainAction(actionMap, new CloseAndCreateUIAction(ui)); - registerMainAction(actionMap, new CancelCreateUIAction(ui)); - registerMainAction(actionMap, new ResetEditUIAction(ui)); - registerMainAction(actionMap, new SaveEditUIAction(ui)); - registerMainAction(actionMap, new DeleteDataUIAction(ui)); - registerMainAction(actionMap, new DeleteReferenceUIAction(ui)); - registerMainAction(actionMap, new MoveTripLonglinesUIAction(ui)); - registerMainAction(actionMap, new MoveTripSeinesUIAction(ui)); - registerMainAction(actionMap, new MoveRoutesUIAction(ui)); - registerMainAction(actionMap, new MoveActivitySeinesUIAction(ui)); - registerMainAction(actionMap, new MoveActivityLonglinesUIAction(ui)); - - } - - //------------------------------------------- - // - Locks - //------------------------------------------- - - public void lock() throws InterruptedException { - synchronized (lock) { - lock.wait(); - } - } - - public void releaseLock() { - synchronized (lock) { - lock.notifyAll(); - } - } - - //------------------------------------------- - // - Storages - //------------------------------------------- - - public ObserveSwingDataSource createTemporaryH2Storage(String label) { - ObserveDataSourceConfigurationMainFactory configurationMainFactory = getObserveDataSourceConfigurationMainFactory(); - - File tmpDirectory = getConfig().getTmpDirectory(); - - File dbDirectory = new File(tmpDirectory, ObserveSwingApplicationConfig.DB_NAME + UUID.randomUUID().toString()); - - ObserveDataSourceConfigurationTopiaH2 config = configurationMainFactory.createObserveDataSourceConfigurationTopiaH2( - label, - dbDirectory, - ObserveSwingApplicationConfig.DB_NAME, - getConfig().getH2Login(), - getConfig().getH2Password(), - false, - false, - getConfig().getModelVersion() - ); - - ObserveSwingDataSource result = getDataSourcesManager().newDataSource(config); - - return result; - } - - public void initStorage(ObserveSwingApplicationConfig config, ObserveMainUI mainUI, boolean askToCreate) { - - if (config.isLocalStorageExist()) { - - // une base locale existe, on l'ouvre - - boolean success = false; - // chargement de la base locale - - // création de la source de données sur la base locale - ObserveSwingDataSource dataSource = getDataSourcesManager().newLocalDatasource(getConfig()); - - try { - - ObserveDataSourceInformation dataSourceInformation = dataSource.checkCanConnect(); - - dataSource.migrateData(dataSourceInformation, getConfig().getModelVersion()); - - // la source sera utilisée dans les ui - prepareMainStorage(dataSource, true); -// getDataSourcesManager().setMainDataSource(dataSource); - - if (log.isInfoEnabled()) { - log.info(t("observe.init.local.db.detected", dataSource.getLabel())); - } - - // la base locale existe, on l'ouvre - dataSource.open(); - success = true; - } catch (DatabaseConnexionNotAuthorizedException | DatabaseNotFoundException | BabModelVersionException e) { - JOptionPane.showMessageDialog( - null, - e.getMessage(), - t("observe.title.error.dialog"), - JOptionPane.ERROR_MESSAGE - ); - } - - if (success) { - // on peut retourner sur cette base - mainUI.setMode(ObserveUIMode.DB); - } - - } else { - - // on peut retourner sur cette base - mainUI.setMode(ObserveUIMode.NO_DB); - - if (askToCreate) { - - // demande à l'utilisateur s'il veut créer la base locale - - int reponse = askUser( - t("observe.title.no.local.db.found"), - t("observe.message.no.local.db.found", - config.getLocalDBDirectory()), - JOptionPane.QUESTION_MESSAGE, - new Object[]{ - t("observe.choice.useRemoteStorage"), - t("observe.choice.createLocalStorage"), - t("observe.choice.doNothing") - }, - 1 - ); - if (log.isDebugEnabled()) { - log.debug("response : " + reponse); - } - - Set<DbMode> dbModes = EnumSet.noneOf(DbMode.class); - String title = null; - if (reponse != JOptionPane.CLOSED_OPTION && reponse < 2) { - - if (reponse == 1) { - // creation de la base locale - dbModes.add(DbMode.CREATE_LOCAL); - title = n("observe.title.create.local.db"); - } else { - // connexion à une base distante - dbModes.add(DbMode.USE_REMOTE); - dbModes.add(DbMode.USE_SERVER); - title = n("observe.title.load.remote.db"); - } - } - if (!dbModes.isEmpty()) { - new ChangeStorageAction(getMainUI(), dbModes, title).run(); - } - - } - } - if (log.isInfoEnabled()) { - log.info(t("observe.init.storage.done")); - } - } - - - /** - * Prepare le storage principal qui servira dans les ui. - * - * @param dataSource la source de données a preparer - */ - public void prepareMainStorage(ObserveSwingDataSource dataSource, boolean setAsMainDataSource) { - - if (setAsMainDataSource) { - - getDataSourcesManager().setMainDataSource(dataSource); - - } - - dataSource.addObserveSwingDataSourceListener(new ObserveSwingDataSourceListenerAdapter() { - - @Override - public void onOpening(ObserveSwingDataSourceEvent event) { - ObserveSwingDataSource s = event.getSource(); - displayInfo(t("observe.message.db.loading", s.getLabel())); - } - - @Override - public void onOpened(ObserveSwingDataSourceEvent event) { - - // le service est disponible, on enregistre les listeners - ObserveSwingDataSource source = event.getSource(); - - try { - openOnUI(source); - } catch (Exception e) { - - // la base n'a pas pu être chargée proprement - // ceci peut être due a une base dans une version pas - // assez recente, on doit donc refermer cette base - handlingError("Could not obtain open datas from " + source.getLabel(), e); - - // fermeture de la source - source.close(); - } - - } - - @Override - public void onClosing(ObserveSwingDataSourceEvent event) { - - super.onClosing(event); - - ObserveMainUI mainUI = getMainUI(); - DataContext dataContext = getDataContext(); - dataContext.setEnabled(false); - - // suppresion des opens dans le context de données - getConfig().setTreeOpenNodeIds(dataContext.getOpenIds()); - dataContext.populateOpens(); - - mainUI.getTreeHelper().cleanNavigationUI(mainUI); - - // on met a jour l'état dans la config - getConfig().setMainStorageOpened(false); - - } - - - @Override - public void onClosed(ObserveSwingDataSourceEvent event) { - // le service est indisponible, il faut supprimer toutes les - // references vers le service - ObserveSwingDataSource source = event.getSource(); - - // on ferme la marée, la route ou l'activité ouvertes - getOpenDataManager().close(); - - ObserveMainUI mainUI = getMainUI(); - - // nettoyage de l'ui ( suppression navigation et autres ) - if (mainUI != null) { - - if (log.isDebugEnabled()) { - log.debug("dispose ui from storage " + source.getLabel() + ": " + mainUI.getName()); - } - - mainUI.setMode(ObserveUIMode.NO_DB); - - displayInfo(t("observe.message.db.closed", source.getLabel())); - - } - - source.removeObserveSwingDataSourceListener(this); - - } - - protected void openOnUI(ObserveSwingDataSource source) { - // on rend le service disponible dans le service de validation - //getValidationContext().setMainDataSource(source); - - // toutes les données sont chargées, on peut declarer le service - // comme ouvert dans la configuration - ObserveSwingApplicationConfig config = getConfig(); - config.setMainStorageOpened(true); - config.setMainStorageOpenedLocal(source.isLocal()); - - if (source.isLocal()) { - config.setLocalStorageExist(true); - } - - // remplissage de l'ui - ObserveMainUI mainUI = getMainUI(); - - if (mainUI != null) { - if (log.isDebugEnabled()) { - log.debug("loading ui for storage " + source.getLabel() + ": " + mainUI.getName()); - } - - DataContext dataContext = mainUI.getDataContext(); - dataContext.setEnabled(true); - - ObserveTreeHelper treeHelper = mainUI.getTreeHelper(); - - treeHelper.cleanNavigationUI(mainUI); - - String[] openIds = config.getTreeOpenNodeIds(); - - if (source.canReadData()) { - getOpenDataManager().sanitizeOpenIds(openIds); - } - - dataContext.populateOpens(openIds); - treeHelper.loadNavigationUI(source); - - mainUI.setMode(ObserveUIMode.DB); - - mainUI.getStatus().setStatus(t("observe.message.db.loaded", source.getLabel())); - - } - } - }); - } - - @Override - public void close() { - if (log.isInfoEnabled()) { - log.info("Closing swing application context " + this); - } - - // fermeture de touts les context de donnée ouvert - getDataSourcesManager().close(); - - ObserveServiceMainFactory serviceMainFactory = ObserveServiceMainFactory.get(); - if (log.isInfoEnabled()) { - log.info("Closing main service factory: " + serviceMainFactory); - } - serviceMainFactory.close(); - - // fermeture du context principal - clear(); - - INSTANCE = null; - - closed = true; - - } - - @Override - protected void finalize() throws Throwable { - if (!closed) { - close(); - } - super.finalize(); - } - - private void registerMainAction(ActionMap actionMap, AbstractUIAction action) { - String actionId = action.getActionId(); - if (log.isInfoEnabled()) { - log.info("Register UI action " + actionId); - } - actionMap.put(actionId, action); - } - -// private ObjectName createMBean(DataSource source) throws MalformedObjectNameException { -// Hashtable<String, String> tb = new Hashtable<String, String>(); -// tb.put("type", "statistics"); -// String name = source.getLabel(); -// tb.put("sessionFactory", name.replaceAll(":", "_")); -// // MBean object name -// ObjectName on = new ObjectName("hibernate", tb); -// return on; -// } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ObserveSwingApplicationDataSourcesManager.java b/observe-application-swing/src/main/java/fr/ird/observe/ObserveSwingApplicationDataSourcesManager.java deleted file mode 100644 index 047de8e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ObserveSwingApplicationDataSourcesManager.java +++ /dev/null @@ -1,108 +0,0 @@ -package fr.ird.observe; - -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.db.event.ObserveSwingDataSourceEvent; -import fr.ird.observe.db.event.ObserveSwingDataSourceListenerAdapter; -import fr.ird.observe.services.configuration.ObserveDataSourceConfiguration; -import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaH2; - -import java.io.Closeable; -import java.util.LinkedList; -import java.util.List; - -import static jaxx.runtime.swing.editor.bean.BeanUIUtil.PopupHandler.log; -import static org.nuiton.i18n.I18n.t; - -/** - * Permet de gérer les différentes data sources utilisées dans l'application. - * - * Created on 09/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class ObserveSwingApplicationDataSourcesManager implements Closeable { - - private final List<ObserveSwingDataSource> dataSources = new LinkedList<>(); - - private ObserveSwingDataSource dataSource; - - /** - * Construit une source de données sur la base locale de l'application. - * - * <b>Note:</b> La base locale doit exister, sinon on soulève une - * exeception - * - * @param config la configuration à utiliser - * @return la service de persistance initialisé (mais non ouvert) - */ - public ObserveSwingDataSource newLocalDatasource(ObserveSwingApplicationConfig config) { - - ObserveDataSourceConfigurationTopiaH2 dataSourceConfigurationH2 = config.getDataSourceConfigurationH2(t("observe.storage.label.local")); - - Preconditions.checkState(dataSourceConfigurationH2.getDatabaseFile().exists(), "local base must exist, when using this method (" + - dataSourceConfigurationH2.getDirectory() + ')'); - return newDataSource(dataSourceConfigurationH2); - } - - public ObserveSwingDataSource getMainDataSource() { - return dataSource; - } - - public void setMainDataSource(ObserveSwingDataSource dataSource) { - this.dataSource = dataSource; - } - - public ObserveSwingDataSource newDataSource(ObserveDataSourceConfiguration configuration) { - ObserveSwingDataSource dataSource = new ObserveSwingDataSource(configuration); - - dataSource.addObserveSwingDataSourceListener(new ObserveSwingDataSourceListenerAdapter() { - - @Override - public void onOpened(ObserveSwingDataSourceEvent event) { - super.onOpened(event); - ObserveSwingDataSource dataSource = event.getSource(); - dataSources.add(dataSource); - - if (log.isInfoEnabled()) { - log.info("Data source opened : " + dataSource.getConfiguration() + " (" + dataSources.size() + " datas sources open)"); - } - } - - @Override - public void onClosed(ObserveSwingDataSourceEvent event) { - super.onClosed(event); - ObserveSwingDataSource dataSource = event.getSource(); - dataSources.remove(dataSource); - if (log.isInfoEnabled()) { - log.info("Data source closed : " + dataSource.getConfiguration() + " (" + dataSources.size() + " datas sources open)"); - } - } - }); - - return dataSource; - } - - @Override - public void close() { - - // fermeture de touts les context de donnée ouvert - for (ObserveSwingDataSource dataSource : Lists.newArrayList(dataSources)) { - if (log.isInfoEnabled()) { - log.info("Closing dataSource : " + dataSource.getConnection()); - } - try { - dataSource.close(); - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error("Could not close data source: " + dataSource, e); - } - } - } - setMainDataSource(null); - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ObserveSwingBinderService.java b/observe-application-swing/src/main/java/fr/ird/observe/ObserveSwingBinderService.java deleted file mode 100644 index ceb6b58..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ObserveSwingBinderService.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe; - -import fr.ird.observe.services.dto.AbstractObserveDto; -import org.nuiton.util.beans.BinderModelBuilder; - -/** - * Service d'utilisation des binders - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ObserveSwingBinderService { - - public <E extends AbstractObserveDto> BinderModelBuilder<E, E> newBinderBuilder(Class<E> type, String... properties) { - BinderModelBuilder<E, E> builder = BinderModelBuilder.newEmptyBuilder(type); - builder.addSimpleProperties(properties); - return builder; - } - - public <E extends AbstractObserveDto> void simpleCopy(E source, E target, boolean tech) { - //FIXME -// Class<E> entityClass = (Class<E>) TopiaEntityHelper.getContractClass(ObserveDAOHelper.getContracts(), target.getClass()); -// TopiaEntityBinder<E> binder = getSimpleTopiaBinder(entityClass); -// if (binder == null) { -// throw new NullPointerException("could not find a simple topia binder of type : " + target.getClass()); -// } -// binder.load(source, target, tech); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ObserveSwingTechnicalException.java b/observe-application-swing/src/main/java/fr/ird/observe/ObserveSwingTechnicalException.java deleted file mode 100644 index ca73a1e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ObserveSwingTechnicalException.java +++ /dev/null @@ -1,50 +0,0 @@ -package fr.ird.observe; - -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -/** - * Created on 8/30/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class ObserveSwingTechnicalException extends RuntimeException { - - private static final long serialVersionUID = 1L; - - public ObserveSwingTechnicalException() { - } - - public ObserveSwingTechnicalException(String message) { - super(message); - } - - public ObserveSwingTechnicalException(String message, Throwable cause) { - super(message, cause); - } - - public ObserveSwingTechnicalException(Throwable cause) { - super(cause); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ObserveTextGenerator.java b/observe-application-swing/src/main/java/fr/ird/observe/ObserveTextGenerator.java deleted file mode 100644 index da5a109..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ObserveTextGenerator.java +++ /dev/null @@ -1,133 +0,0 @@ -package fr.ird.observe; - -/*- - * #%L - * ObServe :: Application Swing - * %% - * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.configuration.ObserveDataSourceConfiguration; -import fr.ird.observe.services.configuration.ObserveDataSourceInformation; -import fr.ird.observe.ui.storage.StorageUIModel; -import freemarker.cache.ClassTemplateLoader; -import freemarker.template.Configuration; -import freemarker.template.Template; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.jaxx.application.ApplicationTechnicalException; - -import java.io.StringWriter; -import java.io.Writer; -import java.util.Locale; - -import static org.nuiton.i18n.I18n.t; - -/** - * @author Sylvain Bavencoff - bavencoff@codelutin.com - */ -public class ObserveTextGenerator { - - private static final Log log = LogFactory.getLog(ObserveTextGenerator.class); - - protected static final String DATA_SOURCE_CONFIGURATION_TEMPLATE = "dataSourceConfiguration.ftl"; - - protected static final String CONNEXION_TEST_RESULT_TEMPLATE = "connexionTestResult.ftl"; - - protected static final String DATA_SOURCE_SELECT_MODE_RESUME_TEMPLATE = "dataSourceSelectModeResume.ftl"; - - protected static final String DATA_SOURCE_CONNECTION_REPORT_TEMPLATE = "dataSourceConnectionReport.ftl"; - - protected static final String DATA_SOURCE_INFORMATION_TEMPLATE = "dataSourceInformation.ftl"; - - protected static final String DATA_SOURCE_POLICY_TEMPLATE = "dataSourcePolicy.ftl"; - - - protected final Configuration freemarkerConfiguration; - - protected final ObserveSwingApplicationConfig observeConfiguration; - - public ObserveTextGenerator(ObserveSwingApplicationConfig observeConfiguration) { - this.observeConfiguration = observeConfiguration; - - freemarkerConfiguration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); - - // needed to overwrite "Defaults to default system encoding." - // fix encoding issue on some systems - freemarkerConfiguration.setEncoding(Locale.getDefault(), "UTF-8"); - - // specific template loader to get template from jars (classpath) - ClassTemplateLoader templateLoader = new ClassTemplateLoader(ObserveTextGenerator.class, "/ftl"); - freemarkerConfiguration.setTemplateLoader(templateLoader); - -// freemarkerConfiguration.setObjectWrapper(new BeansWrapper(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS)); - } - - public String getConfigurationDetail(ObserveDataSourceConfiguration dataSourceConfiguration) { - return generateHtml(DATA_SOURCE_CONFIGURATION_TEMPLATE, dataSourceConfiguration); - } - - public String getConnexionTestResultMessage(StorageUIModel model) { - return generateHtml(CONNEXION_TEST_RESULT_TEMPLATE, model); - } - - public String getLoadDataSourceResume(StorageUIModel model) { - return generateHtml(DATA_SOURCE_SELECT_MODE_RESUME_TEMPLATE, model); - } - - public String getDataSourceConnectionReport(StorageUIModel model) { - return generateHtml(DATA_SOURCE_CONNECTION_REPORT_TEMPLATE, model); - } - - public String getDataSourceInfo(ObserveSwingDataSource source) { - return generateHtml(DATA_SOURCE_INFORMATION_TEMPLATE, source); - } - - public String getDataSourcePolicy(ObserveDataSourceInformation model) { - return generateHtml(DATA_SOURCE_POLICY_TEMPLATE, model); - } - - protected String generateHtml(String templateName, Object model) { - return generateHtml(observeConfiguration.getLocale(), templateName, model); - } - - protected String generateHtml(Locale locale, String templateName, Object model) { - - try { - - // Get freemarker template - Template mapTemplate = freemarkerConfiguration.getTemplate(templateName, locale); - - Writer out = new StringWriter(); - mapTemplate.process(model, out); - - out.flush(); - - return out.toString(); - - - } catch (Exception ex) { - if (log.isErrorEnabled()) { - log.error("error while generating html", ex); - } - throw new ApplicationTechnicalException(t("observe.generateHtml.error", templateName), ex); - } - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveActionExecutor.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveActionExecutor.java new file mode 100644 index 0000000..217c659 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveActionExecutor.java @@ -0,0 +1,318 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing; + +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.admin.AdminActionWorker; +import fr.ird.observe.application.swing.ui.admin.AdminUIModel; +import jaxx.runtime.swing.application.ActionExecutor; +import jaxx.runtime.swing.application.ActionWorker; +import jaxx.runtime.swing.wizard.ext.WizardState; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.Date; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.ThreadPoolExecutor; +import java.util.concurrent.TimeUnit; + +/** + * Action executor. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ObserveActionExecutor extends ActionExecutor { + + /** Logger */ + private static final Log log = + LogFactory.getLog(ObserveActionExecutor.class); + + public ObserveActionExecutor() { + } + + @Override + public void onActionStart(ActionWorker<?, ?> source) { + if (log.isDebugEnabled()) { + log.debug("Action [" + source.getActionLabel() + "] was started at " + new Date(source.getStartTime())); + } + if (source instanceof ObserveCLAction.CommandLineActionWorker) { + if (log.isInfoEnabled()) { + log.info("Action [" + source.getActionLabel() + "] démarrée à " + new Date(source.getStartTime())); + } + + return; + } + if (ObserveSwingApplicationContext.get().isClosed()) { + + // l'application est déjà fermée, on ne fait rien + return; + } + if (source instanceof AdminActionWorker) { + AdminActionWorker admin = (AdminActionWorker) source; + AdminUIModel model = admin.getHandler().getModel(); + model.setBusy(true); + model.setStepState(WizardState.RUNNING); +// return; + } + ObserveMainUI ui = ObserveSwingApplicationContext.get().getMainUI(); + if (ui != null) { + ui.setBusy(true); + } + } + + @Override + public void onActionFail(ActionWorker<?, ?> source) { + Exception error = source.getError(); + if (log.isInfoEnabled()) { + if (log.isErrorEnabled()) { + log.error("Action [" + source.getActionLabel() + + "] failed with error " + error.getCause(), error); + } + } + if (ObserveSwingApplicationContext.get().isClosed()) { + + // l'application est déjà fermée, on ne fait rien + return; + } + if (source instanceof AdminActionWorker) { + AdminActionWorker admin = (AdminActionWorker) source; + AdminUIModel model = admin.getHandler().getModel(); + model.getStepModel(model.getOperation()).setError(error); + model.setStepState(WizardState.FAILED); + return; + } + ObserveMainUI ui = ObserveSwingApplicationContext.get().getMainUI(); + if (ui != null) { + ui.getStatus().setStatus("Action [" + source.getActionLabel() + "] arrêté à cause d'un erreur " + error.getMessage()); + } + } + + @Override + public void onActionCancel(ActionWorker<?, ?> source) { + if (log.isDebugEnabled()) { + log.debug("Action [" + source.getActionLabel() + "] was canceled"); + } + if (ObserveSwingApplicationContext.get().isClosed()) { + + // l'application est déjà fermée, on ne fait rien + return; + } + if (source instanceof AdminActionWorker) { + AdminActionWorker admin = (AdminActionWorker) source; + admin.getHandler().getModel().setStepState(WizardState.CANCELED); + return; + } + ObserveMainUI ui = ObserveSwingApplicationContext.get().getMainUI(); + if (ui != null) { + ui.getStatus().setStatus("Action [" + source.getActionLabel() + "] annulée"); + } + } + + @Override + public void onActionEnd(ActionWorker<?, ?> source) { + if (log.isDebugEnabled()) { + log.debug("Action [" + source.getActionLabel() + " ] was done in " + source.getTime()); + } + if (ObserveSwingApplicationContext.get().isClosed()) { + + // l'application est déjà fermée, on ne fait rien + return; + } + if (source instanceof AdminActionWorker) { + AdminActionWorker admin = (AdminActionWorker) source; + WizardState state; + try { + state = admin.get(); + admin.getHandler().getModel().setStepState(state); + } catch (Exception e) { + if (log.isErrorEnabled()) { + log.error("Could not retrive data from worker " + admin, e); + } + } + return; + } + ObserveMainUI ui = ObserveSwingApplicationContext.get().getMainUI(); + if (ui != null) { + ui.getStatus().setStatus("Action [" + source.getActionLabel() + "] terminée."); + } + } + + @Override + public void onAfterAction(ActionWorker<?, ?> source) { + long count = getNbActions(); + if (log.isDebugEnabled()) { + log.debug("Action [" + source.getActionLabel() + " ] is consumed (still " + count + " tasks to treat)."); + } + if (ObserveSwingApplicationContext.get().isClosed()) { + + // l'application est déjà fermée, on ne fait rien + return; + } + if (source instanceof ObserveCLAction.CommandLineActionWorker) { + + if (log.isInfoEnabled()) { + log.info("Action [" + source.getActionLabel() + "] terminée à " + new Date(source.getStartTime())); + } + + ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); + if (log.isDebugEnabled()) { + log.debug("Unlock main context " + context); + } + context.releaseLock(); + return; + } + if (source instanceof AdminActionWorker) { + AdminActionWorker admin = (AdminActionWorker) source; + admin.getHandler().getModel().setBusy(false); + //admin.getHandler().getUi().removePropertyChangeListener(admin.getHandler().getUi()); +// return; + } + ObserveMainUI ui = ObserveSwingApplicationContext.get().getMainUI(); + if (count < 1 && ui != null) { + ui.setBusy(false); + } + } + + /** + * Add an new worker to perform. + * + * @param worker the worker to run + * @return the worker that will launch the action + */ + public ActionWorker<?, ?> addAction(ActionWorker<?, ?> worker) { + addAction(worker.getActionLabel(), worker); + return worker; + } + + /** + * Add an new action to perform. + * + * @param actionLabel the name of the action to perform + * @param action the action to perform + * @return the worker that will launch the action + */ + public ActionWorker<?, ?> addAction(String actionLabel, Runnable action) { + + ActionWorker<?, ?> worker; + if (action instanceof ActionWorker) { + + worker = (ActionWorker<?, ?>) action; + } else { + + worker = new ActionWorker(actionLabel, action); + } + worker.addPropertyChangeListener(workerListener); + tasks.add(worker); + if (log.isDebugEnabled()) { + log.debug("Launch worker [" + actionLabel + "] now..."); + } + getWorkersExecutorService().execute(worker); + if (log.isDebugEnabled()) { + log.debug("Launch worker [" + actionLabel + "] is on..."); + } + return worker; + } + + private static ExecutorService executorService; + + /** + * On surcharge celui offer par SwingWorker car le corepool est à 1 et cela + * ne permet pas d'exécuter plusieurs actions en même temps... + * returns workersExecutorService. + * + * returns the service stored in the appContext or creates it if + * necessary. + * + * @return ExecutorService for the {@code SwingWorkers} + */ + private static ExecutorService getWorkersExecutorService() { +// AppContext appContext = AppContext.getAppContext(); +// ExecutorService executorService = +// (ExecutorService) appContext.get(ActionWorker.class); + if (executorService == null) { + //this creates daemon threads. + ThreadFactory threadFactory = + new ThreadFactory() { + final ThreadFactory defaultFactory = + Executors.defaultThreadFactory(); + + public Thread newThread(Runnable r) { + Thread thread = + defaultFactory.newThread(r); + thread.setName("ActionWorker-" + + thread.getName()); + thread.setDaemon(true); + return thread; + } + }; + + executorService = + new ThreadPoolExecutor(5, 10, + 10L, TimeUnit.MINUTES, + new LinkedBlockingQueue<>(), + threadFactory); + +// appContext.put(ActionWorker.class, executorService); + + // Don't use ShutdownHook here as it's not enough. We should track + // AppContext disposal instead of JVM shutdown, see 6799345 for details +// final ExecutorService es = executorService; + Runtime.getRuntime().addShutdownHook(new Thread() { + @Override + public void run() { + if (executorService != null) { + executorService.shutdownNow(); + } + } + }); +// appContext.addPropertyChangeListener(AppContext.DISPOSED_PROPERTY_NAME, +// new PropertyChangeListener() { +// @Override +// public void propertyChange(PropertyChangeEvent pce) { +// boolean disposed = (Boolean) pce.getNewValue(); +// if (disposed) { +// WeakReference<ExecutorService> executorServiceRef = +// new WeakReference<ExecutorService>(es); +// final ExecutorService executorService = +// executorServiceRef.get(); +// if (executorService != null) { +// AccessController.doPrivileged( +// new PrivilegedAction<Void>() { +// public Void run() { +// executorService.shutdown(); +// return null; +// } +// } +// ); +// } +// } +// } +// } +// ); + } + return executorService; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveAdminCLI.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveAdminCLI.java new file mode 100644 index 0000000..12f866e --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveAdminCLI.java @@ -0,0 +1,58 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.Arrays; +import java.util.Date; + +/** + * Pour lancer le client swing {@code ObServe} en mode administrateur. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ObserveAdminCLI extends ObserveRunner { + + /** Logger */ + private static final Log log = LogFactory.getLog(ObserveAdminCLI.class); + + @Override + public String getRunnerName() { + return "observe"; + } + + public ObserveAdminCLI(String... args) { + super(args); + } + + public static void main(String... args) { + + log.info("ObServe admin client launch at " + + new Date() + " args: " + Arrays.toString(args)); + + new ObserveAdminCLI(args).launch(); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveCLAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveCLAction.java new file mode 100644 index 0000000..156adae --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveCLAction.java @@ -0,0 +1,399 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing; + +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfigOption; +import fr.ird.observe.application.swing.ui.ObserveMainUIHandler; +import fr.ird.observe.application.swing.ui.admin.AdminStep; +import fr.ird.observe.application.swing.ui.admin.AdminUILauncher; +import fr.ird.observe.application.swing.ui.storage.ObstunaAdminAction; +import fr.ird.observe.application.swing.ui.storage.RemoteUILauncher; +import jaxx.runtime.swing.application.ActionWorker; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.config.ConfigActionDef; + +import java.io.Console; +import java.io.IOException; +import java.util.Arrays; +import java.util.EnumSet; + +import static org.nuiton.i18n.I18n.t; + +/** + * Les actions appellables via {@link ObserveRunner}. + * + * Consulter la classe {@link ActionDefinition} pour connaitre les actions + * possibles. + * + * @author Tony Chemit - chemit@codelutin.com + * @see ObserveSwingApplicationConfig + * @see ObserveRunner + * @since 1.0 + */ +public class ObserveCLAction { + + /** Logger */ + private static final Log log = LogFactory.getLog(ObserveCLAction.class); + + /** + * Les actions appellables en ligne de commande. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ + public enum ActionDefinition implements ConfigActionDef { + /** + * Afficher l'aide dans la console. + * + * @since 1.0 + */ + HELP(false, t("observe.action.commandline.help"), + ObserveCLAction.class.getName() + "#help", "-h", "--help"), + /** + * Afficher l'aide embarqué de l'application (dans une interface + * graphique). + * + * @since 1.0 + */ + HELP_UI(false, t("observe.action.commandline.help.ui"), + ObserveCLAction.class.getName() + "#helpUI", "--help-ui"), + /** + * Pour désactiver le lancement de l'application graphique. + * + * @since 1.0 + */ + NO_MAIN_UI(false, t("observe.action.commandline.disable.main.ui"), + ObserveCLAction.class.getName() + "#disableMainUI", "-n", + "--no-main"), + /** + * Pour lancer l'interface graphique du configuration de l'application. + * + * @since 1.0 + */ + CONFIGURE_UI(false, t("observe.action.commandline.configure.ui"), + ObserveCLAction.class.getName() + "#configure", + "--configure"), + /** + * Pour lancer une opération d'administration via un assistant + * graphique. + * + * @since 1.4 + */ + ADMIN_UI(true, t("observe.action.commandline.launch.admin.ui"), + ObserveCLAction.class.getName() + "#launchAdminUI", "-a", + "--admin"), + /** + * Pour lancer une opération d'administration via un assistant + * graphique. + * + * @since 1.4 + */ + OBSTUNA_ADMIN_UI(true, t("observe.action.commandline.launch.obstuna.admin.ui"), + ObserveCLAction.class.getName() + "#launchObstunaAdminUI", + "--obstuna-admin"), + + /** + * Pour lancer la base locale en mode serveur. + * + * @since 2.1 + */ + H2_SERVER_MODE(true, t("observe.action.commandline.launch.h2.server.mode"), + ObserveCLAction.class.getName() + "#launchH2ServerMode", + "--h2-server"), + /** + * Pour activer le support JMX pour les source de données. + * + * @since 1.4 + */ + USE_JMX(true, t("observe.action.commandline.use.jmx"), + ObserveCLAction.class.getName() + "#useJMX", + "--jmx"), + + CREATE_ID(true, + t("observe.action.commandline.create.id"), + ObserveCLAction.class.getName() + "#createId", + "--create-id"); + + + public final String description; + + public final String action; + + public final String[] aliases; + + public final boolean admin; + + ActionDefinition(boolean admin, String description, String action, String... aliases) { + this.description = description; + this.action = action; + this.aliases = aliases; + this.admin = admin; + } + + public String getDescription() { + return description; + } + + public String getAction() { + return action; + } + + public String[] getAliases() { + return aliases; + } + + public boolean isAdmin() { + return admin; + } + } + + /** La configuration de l'application. */ + protected ObserveSwingApplicationConfig config; + + public ObserveCLAction() { + } + + /** Désactiver la possiblite de lancer l'ui principale. */ + public void disableMainUI() { + if (log.isDebugEnabled()) { + log.debug(this); + } + getConfig().setDisplayMainUI(false); + } + + @SuppressWarnings("unused") + public void help() { + disableMainUI(); + + StringBuilder out = new StringBuilder(); + + out.append(t("observe.message.help.usage", getConfig().getVersion())); + out.append('\n'); + out.append("Options (set with --option <key> <value>:"); + out.append('\n'); + for (ObserveSwingApplicationConfigOption o : ObserveSwingApplicationConfigOption.values()) { + + out.append("\t"); + out.append(o.getKey()); + out.append("("); + out.append(o.getDefaultValue()); + out.append(") :"); + out.append(t(o.getDescription())); + out.append('\n'); + } + + out.append("Actions:"); + out.append('\n'); + for (ActionDefinition a : ActionDefinition.values()) { + out.append("\t"); + out.append(Arrays.toString(a.aliases)); + out.append("("); + out.append(a.action); + out.append("):"); + out.append(t(a.description)); + out.append('\n'); + } + Console cons; + + if ((cons = System.console()) != null) { + cons.printf(out.toString()); + } + } + + public void configure() throws InterruptedException { + disableMainUI(); + ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); + + ObserveMainUIHandler handler = context.getContextValue(ObserveMainUIHandler.class); + + Runnable runnable = createRunnable(handler, "showConfig", context); + + launchAction(t("observe.action.showConfig.title"), runnable); + } + + @SuppressWarnings("unused") + public void launchAdminUI(String operationName) throws InterruptedException { + + disableMainUI(); + + EnumSet<AdminStep> operations = AdminStep.getOperations(); + + AdminStep operation = AdminStep.valueOfIgnoreCase(operationName); + if (operation == null) { + if (log.isErrorEnabled()) { + log.error(operationName + " is not a known admin operation."); + log.error("Use one of these ones : " + operations); + } + return; + } + + if (!operation.isOperation()) { + if (log.isErrorEnabled()) { + log.error(operation + " is not a admin operation(just a step in wizard)."); + log.error("Use one of these ones : " + operations); + } + return; + } + + ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); + + AdminUILauncher launcher = AdminUILauncher.newLauncher(context, operation); + + Runnable runnable = createRunnable(launcher, "start"); + + launchAction(t(operation.getTitle()), runnable); + } + + @SuppressWarnings("unused") + public void launchObstunaAdminUI(String operationName) throws InterruptedException { + + disableMainUI(); + + EnumSet<ObstunaAdminAction> operations = EnumSet.allOf(ObstunaAdminAction.class); + + ObstunaAdminAction operation = ObstunaAdminAction.valueOfIgnoreCase(operationName); + if (operation == null) { + if (log.isErrorEnabled()) { + log.error(operationName + " is not a known obstuna admin operation."); + log.error("Use one of these ones : " + operations); + } + return; + } + + ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); + + // FIXME +// getConfig().setOption(AbstractDataSourceMigration.AUTO_MIGRATE, "false"); + + if (operation == ObstunaAdminAction.UPDATE || + operation == ObstunaAdminAction.CREATE) { + getConfig().setOption(ObserveSwingApplicationConfigOption.OBSTUNA_CAN_MIGRATE, true); + } + + RemoteUILauncher launcher = operation.newLauncher(context, null); + + Runnable runnable = createRunnable(launcher, "start"); + launchAction(t(launcher.getTitle()), runnable); + } + + public void launchH2ServerMode() throws InterruptedException { + + if (!config.isLocalStorageExist()) { + if (log.isErrorEnabled()) { + log.error("Local database does not exist."); + } + } else { + + ObserveSwingApplicationContext.get().setContextValue( + true, + ActionDefinition.H2_SERVER_MODE.name()); + } + } + + public void createId(String className, int nbId) throws IOException { + + disableMainUI(); + +// Class<?> klazz = null; + + //FIXME +// List<ObserveEntityEnum> enums = Lists.newArrayList(Entities.ALL_ENTITIES); +// enums.remove(ObserveEntityEnum.CommentableEntity); +// enums.remove(ObserveEntityEnum.OpenableEntity); +// enums.remove(ObserveEntityEnum.I18nReferenceEntity); +// enums.remove(ObserveEntityEnum.ReferenceEntity); +// +// for (ObserveEntityEnum e : enums) { +// if (className.equals(e.name())) { +// klazz = e.getContract(); +// break; +// } +// } +// +// if (klazz == null) { +// +// Collections.sort(enums, new Comparator<ObserveEntityEnum>() { +// @Override +// public int compare(ObserveEntityEnum observeEntityEnum, ObserveEntityEnum observeEntityEnum2) { +// return observeEntityEnum.name().compareTo(observeEntityEnum2.name()); +// } +// }); +// if (log.isErrorEnabled()) { +// log.error(className + " not found! availables names :\n\t" + Joiner.on("\n\t").join(enums)); +// } +// return; +// } +// +// for (int i = 0; i < nbId; i++) { +// String topiaId = TopiaId.create(klazz); +// System.out.println(topiaId); +// } + } + + protected ObserveSwingApplicationConfig getConfig() { + if (config == null) { + config = ObserveSwingApplicationContext.get().getConfig(); + } + return config; + } + + protected Runnable createRunnable(Object invoker, String method, Object... args) { + ObserveActionExecutor executor = ObserveRunner.getActionExecutor(); + + Runnable runnable = executor.createRunnable(invoker, method, args); + return runnable; + } + + protected void launchAction(String title, Runnable target) throws InterruptedException { + ObserveActionExecutor executor = ObserveRunner.getActionExecutor(); + + CommandLineActionWorker action = new CommandLineActionWorker(title, target); + executor.addAction(action); + + // on attends la fin de l'opération + ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); + if (log.isDebugEnabled()) { + log.debug("Lock main context " + context); + } + context.lock(); + } + + /** + * Un worker pour les opération longues d'administration. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ + public class CommandLineActionWorker extends ActionWorker<Void, String> { + + public CommandLineActionWorker(String actionLabel, Runnable target) { + super(actionLabel); + setTarget(target); + } + + public ObserveCLAction getAction() { + return ObserveCLAction.this; + } + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveOpenDataManager.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveOpenDataManager.java new file mode 100644 index 0000000..4264d4f --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveOpenDataManager.java @@ -0,0 +1,288 @@ +package fr.ird.observe.application.swing; + +/*- + * #%L + * ObServe :: Application Swing + * %% + * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.base.Preconditions; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.services.ObserveServicesProvider; +import fr.ird.observe.services.dto.IdDtos; +import fr.ird.observe.services.dto.referential.ProgramDto; + +import java.io.Closeable; + +/** + * Pour gérer les données ouvertes sur une source de données dans l'application. + * À l'ouverture d'une source de données rien n'est ouvert. + * Les états de cet objet sont liés au cylce de vie d'une source de données dans l'application. + * + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class ObserveOpenDataManager implements Closeable { + + private final DataContext dataContext; + + public ObserveOpenDataManager(DataContext dataContext) { + this.dataContext = dataContext; + } + + // Program + public boolean canOpenProgram() { + return !dataContext.isOpenProgram(); + } + + public void openProgram(String programId) { + Preconditions.checkNotNull(programId, "id cant be null"); + Preconditions.checkState(canOpenProgram(), "a program is already opened"); + dataContext.setOpenProgramId(programId); + } + + public boolean isOpenProgram(String programId) { + Preconditions.checkNotNull(programId, "id cant be null"); + return programId.equals(dataContext.getOpenProgramId()); + } + + public void closeProgram(String programId) { + Preconditions.checkNotNull(programId, "id cant be null"); + Preconditions.checkState(isOpenProgram(programId), "this program is not opened"); + dataContext.setOpenProgramId(null); + } + + + // Trip Seine + public boolean canOpenTripSeine() { + return !dataContext.isOpenTrip(); + } + + public void openTripSeine(String programId, String tripSeineId) { + openProgram(programId); + Preconditions.checkNotNull(tripSeineId, "id cant be null"); + Preconditions.checkState(canOpenTripSeine(), "a trip is already opened"); + dataContext.setOpenTripSeineId(tripSeineId); + } + + public boolean isOpenTripSeine(String tripSeineId) { + Preconditions.checkNotNull(tripSeineId, "id cant be null"); + return tripSeineId.equals(dataContext.getOpenTripSeineId()); + } + + public void closeTripSeine(String tripSeineId) { + Preconditions.checkNotNull(tripSeineId, "id cant be null"); + Preconditions.checkState(isOpenTripSeine(tripSeineId), "this trip is not opened"); + + if (dataContext.isOpenRoute()) { + String openRouteId = dataContext.getOpenRouteId(); + closeRoute(openRouteId); + } + + dataContext.setOpenTripSeineId(null); + dataContext.setOpenProgramId(null); + } + + // Route + public boolean canOpenRoute(String parentTripSeineId) { + Preconditions.checkNotNull(parentTripSeineId, "id cant be null"); + return isOpenTripSeine(parentTripSeineId) && !dataContext.isOpenRoute(); + } + + public void openRoute(String parentTripSeineId, String routeId) { + Preconditions.checkNotNull(parentTripSeineId, "id cant be null"); + Preconditions.checkNotNull(routeId, "id cant be null"); + Preconditions.checkState(canOpenRoute(parentTripSeineId), "the trip is not opened or another route already opened"); + dataContext.setOpenRouteId(routeId); + } + + public boolean isOpenRoute(String routeId) { + Preconditions.checkNotNull(routeId, "id cant be null"); + return routeId.equals(dataContext.getOpenRouteId()); + } + + public void closeRoute(String routeId) { + Preconditions.checkNotNull(routeId, "id cant be null"); + Preconditions.checkState(isOpenRoute(routeId), "this route is not opened"); + + if (dataContext.isOpenActivitySeine()) { + String openActivitySeineId = dataContext.getOpenActivitySeineId(); + closeActivitySeine(openActivitySeineId); + } + + dataContext.setOpenRouteId(null); + } + + // Activity Seine + public boolean canOpenActivitySeine(String parentRouteId) { + Preconditions.checkNotNull(parentRouteId, "id cant be null"); + return isOpenRoute(parentRouteId) && !dataContext.isOpenActivitySeine(); + } + + public void openActivitySeine(String parentRouteId, String activitySeineId) { + Preconditions.checkNotNull(parentRouteId, "id cant be null"); + Preconditions.checkNotNull(activitySeineId, "id cant be null"); + Preconditions.checkState(canOpenActivitySeine(parentRouteId), "the route is not opened or another activity is already opened"); + dataContext.setOpenActivitySeineId(activitySeineId); + } + + public boolean isOpenActivitySeine(String activitySeineId) { + Preconditions.checkNotNull(activitySeineId, "id cant be null"); + return activitySeineId.equals(dataContext.getOpenActivitySeineId()); + } + + public void closeActivitySeine(String activitySeineId) { + Preconditions.checkNotNull(activitySeineId, "id cant be null"); + Preconditions.checkState(isOpenActivitySeine(activitySeineId), "this activity is not opened"); + dataContext.setOpenActivitySeineId(null); + } + + // Trip Longline + public boolean canOpenTripLongline() { + return !dataContext.isOpenTrip(); + } + + public void openTripLongline(String programId, String tripLongLineId) { + openProgram(programId); + Preconditions.checkNotNull(tripLongLineId, "id cant be null"); + Preconditions.checkState(canOpenTripLongline(), "a trip is already opened"); + dataContext.setOpenTripLonglineId(tripLongLineId); + } + + public boolean isOpenTripLongline(String tripLongLineId) { + Preconditions.checkNotNull(tripLongLineId, "id cant be null"); + return tripLongLineId.equals(dataContext.getOpenTripLonglineId()); + } + + public void closeTripLongline(String tripLongLineId) { + Preconditions.checkNotNull(tripLongLineId, "id cant be null"); + Preconditions.checkState(isOpenTripLongline(tripLongLineId), "this trip is not opened"); + + if (dataContext.isOpenActivityLongline()) { + String openActivityLonglineId = dataContext.getOpenActivityLonglineId(); + closeActivityLongline(openActivityLonglineId); + } + + dataContext.setOpenTripLonglineId(null); + dataContext.setOpenProgramId(null); + } + + // Activity Longline + public boolean canOpenActivityLongline(String parentTripLonglineId) { + Preconditions.checkNotNull(parentTripLonglineId, "id cant be null"); + return isOpenTripLongline(parentTripLonglineId) && !dataContext.isOpenActivityLongline(); + } + + public void openActivityLongline(String parentTripLonglineId, String activityLonglineId) { + Preconditions.checkNotNull(parentTripLonglineId, "id cant be null"); + Preconditions.checkNotNull(activityLonglineId, "id cant be null"); + Preconditions.checkState(canOpenActivityLongline(parentTripLonglineId), "the trip is not opened or another activity is already opened"); + dataContext.setOpenActivityLonglineId(activityLonglineId); + } + + public boolean isOpenActivityLongline(String activityLonglineId) { + Preconditions.checkNotNull(activityLonglineId, "id cant be null"); + return activityLonglineId.equals(dataContext.getOpenActivityLonglineId()); + } + + public void closeActivityLongline(String activityLonglineId) { + Preconditions.checkNotNull(activityLonglineId, "id cant be null"); + Preconditions.checkState(isOpenActivityLongline(activityLonglineId), "this activity is not opened"); + dataContext.setOpenActivityLonglineId(null); + } + + public boolean isOpen(String openableId) { + return isOpenTripSeine(openableId) + || isOpenRoute(openableId) + || isOpenActivitySeine(openableId) + || isOpenTripLongline(openableId) + || isOpenActivityLongline(openableId); + } + + public boolean isOpenActivity(String activityId) { + return isOpenActivitySeine(activityId) + || isOpenActivityLongline(activityId); + } + + @Override + public void close() { + dataContext.resetOpen(); + } + + public void sanitizeOpenIds(String[] ids) { + if (ids != null) { + + boolean exists = true; + + ObserveServicesProvider servicesProvider = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider(); + + for (int i = 0, l = ids.length; i < l; i++) { + String id = ids[i]; + + // si l'id précédent existe, on vérifie l'actuel + // sinon, on met à null + if (exists) { + if (IdDtos.isProgramId(id)) { + + exists = servicesProvider.newReferentialService().exists(ProgramDto.class, id); + + } else if (IdDtos.isTripSeineId(id)) { + + exists = servicesProvider.newTripSeineService().exists(id); + + } else if (IdDtos.isRouteId(id)) { + + exists = servicesProvider.newRouteService().exists(id); + + } else if (IdDtos.isActivitySeineId(id)) { + + exists = servicesProvider.newActivitySeineService().exists(id); + + } else if (IdDtos.isSetSeineId(id)) { + + exists = servicesProvider.newSetSeineService().exists(id); + + } else if (IdDtos.isFloatingObjectId(id)) { + + exists = servicesProvider.newFloatingObjectService().exists(id); + + } else if (IdDtos.isTripLonglineId(id)) { + + exists = servicesProvider.newTripLonglineService().exists(id); + + } else if (IdDtos.isActivityLonglineId(id)) { + + exists = servicesProvider.newActivityLonglineService().exists(id); + + } else if (IdDtos.isSetLonglineId(id)) { + + exists = servicesProvider.newSetLonglineService().exists(id); + + } else { + + exists = false; + } + } + + if (!exists) { + ids[i] = null; + } + } + } + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveResourceManager.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveResourceManager.java new file mode 100644 index 0000000..908b2b4 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveResourceManager.java @@ -0,0 +1,325 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing; + +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfigOption; +import org.apache.commons.io.IOUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.util.SortedProperties; +import org.nuiton.util.ZipUtil; + +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URL; +import java.util.Map; +import java.util.Properties; +import java.util.TreeMap; + +import static org.nuiton.i18n.I18n.t; + +/** + * La classe responsable du chargement de toutes les resources qui viennent de + * l'application et qui seont ensuite redispatchés dans le répertoire de + * resource de l'utilisateur. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ObserveResourceManager { + + public static final String OBSERVE_UI_PROPERTIES = "/observe-ui.properties"; + + public static final String OBSERVE_APPLICATION_PROPERTIES = "/observe-application.properties"; + + public static final String OBSERVE_REPORTS_PROPERTIES = "/observe-reports.properties"; + + public static final String OBSERVE_MAP_ARCHIVE = "/map.zip"; + + public static final String OBSERVE_LOG_CONFIGURATION_FILE_PROPERTIES = "/observe-log4j.properties"; + + /** Logger */ + private static final Log log = LogFactory.getLog(ObserveResourceManager.class); + + public enum Resource { + + ui(OBSERVE_UI_PROPERTIES), + application(OBSERVE_APPLICATION_PROPERTIES), + report(OBSERVE_REPORTS_PROPERTIES), + LOG_CONFIGURATION_FILE(OBSERVE_LOG_CONFIGURATION_FILE_PROPERTIES), + mapLayers(OBSERVE_MAP_ARCHIVE); + + private final String location; + + private URL url; + + Resource(String location) { + this.location = location; + } + + public URL getUrl() { + if (url == null) { + url = getResource(location); + } + return url; + } + + public boolean exists(File directory) { + File file = getFile(directory); + return file.exists(); + } + + public File getFile(File directory) { + File file = new File(directory, location.substring(1)); + return file; + } + + } + + protected Map<String, Properties> resources; + + public Map<String, Properties> getResources() { + if (resources == null) { + resources = new TreeMap<>(); + } + return resources; + } + + + public Properties getResource(Resource resource) throws IOException { + + URL url = resource.getUrl(); + Properties result = getResource(url); + return result; + } + + public Properties getResource(File file) throws IOException { + + URL url = file.toURI().toURL(); + + Properties result = load(url); + + return result; + } + + + public Properties getResource(URL url) throws IOException { + + String path = url.toString(); + + Properties result = getResources().get(path); + + if (result == null) { + + result = load(url); + + // on sauvegarde dans le cache + if (log.isDebugEnabled()) { + log.debug("Store configuration [" + path + "]"); + } + getResources().put(path, result); + } + + // toujours faire une copie pour eviter toute altération des + // configuration par défaut. + SortedProperties tmp = new SortedProperties(); + tmp.putAll(result); + return tmp; + } + + protected Properties load(URL url) throws IOException { + Properties result;// chargement une unique fois de la resource + InputStream in = openInternalStream(url); + + try { + result = new Properties(); + result.load(in); + + + } finally { + in.close(); + } + return result; + } + + public void copyResource(Resource resource, + File file, + String message) throws IOException { + + FileOutputStream out = new FileOutputStream(file); + try { + // on fait une copie brute en ne passant pas par un Properties + // qui perd le formatage et les commentaires + + // chargement des ressources + InputStreamReader in = + new InputStreamReader( + new BufferedInputStream( + openInternalStream(resource.getUrl())), + "utf-8"); + + // sauvegarde dans le fichier cible + try { + IOUtils.copy(in, out, "utf-8"); + } finally { + in.close(); + } + + if (log.isInfoEnabled()) { + log.info(message); + } + } finally { + out.close(); + } + } + + public void copyResource(URL resource, + File file, + String message) throws IOException { + + FileOutputStream out = new FileOutputStream(file); + try { + // on fait une copie brute en ne passant pas par un Properties + // qui perd le formatage et les commentaires + + // chargement des ressources + InputStreamReader in = + new InputStreamReader( + new BufferedInputStream( + openInternalStream(resource)), + "utf-8"); + + // sauvegarde dans le fichier cible + try { + IOUtils.copy(in, out, "utf-8"); + in.close(); + } finally { + IOUtils.closeQuietly(in); + } + + if (log.isInfoEnabled()) { + log.info(message); + } + out.close(); + } finally { + IOUtils.closeQuietly(out); + } + } + + /** + * Créer le répertoire si nécessaire à partir le l'option donnée. + * + * @param config la configuration utilisée + * @param option l'option qui représentent le répertoire. + * @return le fichier + * @throws IOException pour tout problème de création de répertoire + */ + protected File createDirectory(ObserveSwingApplicationConfig config, + ObserveSwingApplicationConfigOption option) throws IOException { + File dir = config.getOptionAsFile(option.getKey()); + createDirectory(dir); + return dir; + } + + /** + * Créer tous les répertoires parents nécessaires à partir des options sur + * répertoire ou fichier. + * + * @param config la configuration utilisée + * @param options les options qui représentent des répertoires ou fichiers. + * @throws IOException pour tout problème de création de répertoire + */ + protected void createParentDirectory(ObserveSwingApplicationConfig config, + ObserveSwingApplicationConfigOption... options) throws IOException { + for (ObserveSwingApplicationConfigOption option : options) { + File dir = config.getOptionAsFile(option.getKey()).getParentFile(); + createDirectory(dir); + } + } + + /** + * Créer un répertoire s'il n'existe pas. + * + * @param dir le répertoire à créer + * @throws IOException pour tout problème de création de répertoire + */ + protected void createDirectory(File dir) throws IOException { + + if (!dir.exists()) { + if (log.isInfoEnabled()) { + log.info(t("observe.runner.create.directory", dir)); + } else { + log.info(t("observe.runner.exists.directory", dir)); + } + boolean b = dir.mkdirs(); + if (!b) { + throw new IOException( + t("observe.error.can.not.create.directory", dir)); + } + } + } + + protected static URL getResource(String location) { + URL resource = ObserveResourceManager.class.getResource(location); + try { + // test que la resource existe bien dans le class-path + InputStream in = openInternalStream(resource); + in.close(); + return resource; + } catch (Exception e) { + throw new IllegalStateException("Could not treat internal resource " + location); + } + } + + protected static InputStream openInternalStream(URL resource) { + try { + InputStream in = resource.openStream(); + if (in == null) { + throw new IllegalStateException("Could not find internal resource " + resource); + } + + return in; + } catch (Exception e) { + throw new IllegalStateException("Could not treat internal resource " + resource); + } + } + + public File unzipToDirectory(Resource resource, ObserveSwingApplicationConfig config, ObserveSwingApplicationConfigOption option, String message) throws IOException { + + File dir = config.getOptionAsFile(option.getKey()); + createDirectory(dir); + InputStream inputStream = openInternalStream(resource.getUrl()); + try { + ZipUtil.uncompress(inputStream, dir); + return dir; + } finally { + inputStream.close(); + + } + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveRunner.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveRunner.java new file mode 100644 index 0000000..7f76c42 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveRunner.java @@ -0,0 +1,648 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing; + +import com.google.common.base.Preconditions; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.ObserveMainUIHandler; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.actions.StartServerModeAction; +import fr.ird.observe.application.swing.ui.util.FloatConverter; +import jaxx.runtime.FileChooserUtil; +import jaxx.runtime.swing.application.ApplicationRunner; +import org.apache.commons.beanutils.ConvertUtils; +import org.apache.commons.beanutils.Converter; +import org.apache.commons.beanutils.converters.DateConverter; +import org.apache.commons.io.FileUtils; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.apache.log4j.LogManager; +import org.apache.log4j.PropertyConfigurator; +import org.jdesktop.swingx.plaf.basic.CalendarHeaderHandler; +import org.jdesktop.swingx.plaf.basic.SpinningCalendarHeaderHandler; +import org.nuiton.converter.ConverterUtil; +import org.nuiton.i18n.I18n; +import org.nuiton.i18n.init.DefaultI18nInitializer; +import org.nuiton.i18n.init.UserI18nInitializer; +import org.nuiton.util.StringUtil; + +import javax.script.ScriptEngine; +import javax.script.ScriptEngineManager; +import javax.script.ScriptException; +import javax.swing.UIManager; +import java.io.File; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.util.Arrays; +import java.util.Date; +import java.util.Locale; +import java.util.Map; +import java.util.Properties; + +import static fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfigOption.BACKUP_DIRECTORY; +import static fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfigOption.DATA_DIRECTORY; +import static fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfigOption.DB_DIRECTORY; +import static fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfigOption.INITIAL_DB_DUMP; +import static fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfigOption.MAP_DIRECTORY; +import static fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfigOption.REPORT_DIRECTORY; +import static fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfigOption.RESOURCES_DIRECTORY; +import static fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfigOption.TMP_DIRECTORY; +import static fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfigOption.VALIDATION_REPORT_DIRECTORY; +import static org.nuiton.i18n.I18n.t; + +/** + * Le lanceur de l'application ObServe. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public abstract class ObserveRunner extends ApplicationRunner { + + /** Logger */ + private static Log log = LogFactory.getLog(ObserveRunner.class); + + protected static ObserveResourceManager resourceManager; + + protected static ObserveActionExecutor actionExecutor; + + public static ObserveRunner getRunner() { + return (ObserveRunner) ApplicationRunner.getRunner(); + } + +// public static ObserveResourceManager getResourceManager() { +// if (resourceManager == null) { +// throw new IllegalStateException("No resourceManager initialized"); +// } +// return resourceManager; +// } + + public static ObserveActionExecutor getActionExecutor() { + if (actionExecutor == null) { + actionExecutor = new ObserveActionExecutor(); + } + return actionExecutor; + } + + public abstract String getRunnerName(); + +// public static boolean isAdmin() { +// return true; +// } + + public final boolean init; + + public ObserveRunner(String... args) { + super(args); + init = true; + initOnce(); + } + + public static void runAction(String actionLabel, Runnable action) { + getActionExecutor().addAction(actionLabel, action); + } + + public static void runAction(String actionLabel, + Object invoker, + String methodName, + Object... arguments) { + Runnable action; + try { + action = getActionExecutor().createRunnable( + invoker, + methodName, + arguments + ); + } catch (Exception e) { + throw new RuntimeException( + "could not create action " + actionLabel, e); + } + runAction(actionLabel, action); + } + + @Override + protected void initOnce() { + if (!init) { + return; + } + + // check script engine exist + checkScriptEngineFound(); + + // on veut avoir les traductions dès le début + // on charge dans un premier temps les traductions fournies + // par l'application + I18n.init(new DefaultI18nInitializer("observe-i18n"), null); + + // to enable javassist on webstart, must remove any securityManager, + // see if this can be dangerous (should not be since jnlp is signed ?) + // moreover it speeds up the loading :) +// System.setSecurityManager(null); + + resourceManager = new ObserveResourceManager(); + + // initialisation des converteurs + + Converter converter = ConverterUtil.getConverter(Date.class); + if (converter != null) { + ConvertUtils.deregister(Date.class); + } + DateConverter dateConverter = new DateConverter(); + dateConverter.setUseLocaleFormat(true); + ConvertUtils.register(dateConverter, Date.class); + + converter = ConverterUtil.getConverter(Float.class); + if (converter != null) { + ConvertUtils.deregister(Float.class); + } + ConvertUtils.register(new FloatConverter(), Float.class); + + // initialisation du thread d'action + getActionExecutor(); + + UIManager.put(CalendarHeaderHandler.uiControllerID, SpinningCalendarHeaderHandler.class.getName()); + UIManager.put(SpinningCalendarHeaderHandler.ARROWS_SURROUND_MONTH, true); + UIManager.put(SpinningCalendarHeaderHandler.FOCUSABLE_SPINNER_TEXT, true); + } + + @Override + protected void onInit() throws Exception { + + if (log.isInfoEnabled()) { + log.info(t("observe.runner.init", new Date(), + Arrays.toString(args))); + } + + long t0 = System.nanoTime(); + + // 1 - preparation de la configuration + + ObserveSwingApplicationConfig config = initConfig(); + + if (log.isInfoEnabled()) { + log.info(t("observe.runner.config.loaded", config.getVersion())); + } + + // 2 - preparation des répertoires utilisateurs + + initUserDirectories(config); + + // 3 - Chargement de la configuration des logs utilisateur + if (!config.isDevMode()) { + initLog(config); + } + + if (log.isInfoEnabled()) { + log.info(t("observe.runner.user.directories.loaded", config.getDataDirectory())); + } + + // 3 - preparation i18n + + initI18n(config); + + if (log.isInfoEnabled()) { + log.info(t("observe.runner.i18n.loaded", config.getLocale().getDisplayLanguage())); + } + + // 4 - preparation de la configuration des ui + + initUIConfiguration(config); + + // 5 - preparation du context applicatif + + ObserveSwingApplicationContext applicationContext = new ObserveSwingApplicationContext(config); + + // 6 - détection de la base locale + + detectLocalDataBase(config); + + String time = StringUtil.convertTime(t0, System.nanoTime()); + + if (log.isInfoEnabled()) { + log.info(t("observe.runner.context.loaded", time)); + } + } + + protected void initLog(ObserveSwingApplicationConfig config) throws IOException { + + File logFile = config.getLogConfigurationFile(); + Preconditions.checkState(logFile.exists(), "Le fichier de configuration des logs %s n'existe pas.", logFile); + + URL resource; + try { + resource = logFile.toURI().toURL(); + } catch (MalformedURLException mue) { + throw new ObserveSwingTechnicalException("Unable to load log configuration", mue); + } + + if (log.isInfoEnabled()) { + log.info("Chargement du fichier de de log4j depuis " + resource); + } + Properties logConfigurationProperties = resourceManager.load(resource); + Properties finalLogConfigurationProperties = new Properties(); + for (Map.Entry<Object, Object> entry : logConfigurationProperties.entrySet()) { + String key = (String) entry.getKey(); + String value = (String) entry.getValue(); + String newValue = config.replaceRecursiveOptions(value); + finalLogConfigurationProperties.setProperty(key, newValue); + } + LogManager.resetConfiguration(); + PropertyConfigurator.configure(finalLogConfigurationProperties); + + log = LogFactory.getLog(ObserveRunner.class); + if (log.isInfoEnabled()) { + log.info("Initialisation des logs depuis " + logFile); + } + + } + + @Override + protected void onStart() throws Exception { + + if (log.isInfoEnabled()) { + log.info(t("observe.runner.start", new Date(), Arrays.toString(args))); + } + + ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); + + if (log.isDebugEnabled()) { + log.debug("Will use context : " + context); + } + + // 1 - launch commandline actions + + ObserveSwingApplicationConfig config = context.getConfig(); + + if (config.containActions(ObserveSwingApplicationConfig.Step.AfterInit)) { + + config.doAction(ObserveSwingApplicationConfig.Step.AfterInit.ordinal()); + + if (log.isInfoEnabled()) { + log.info("Operation terminées..."); + } + } + + if (!config.isDisplayMainUI()) { + if (log.isInfoEnabled()) { + log.info(t("observe.runner.quit.withno.ui")); + } + + unlock(); + return; + } + + // 2 - init ui + + ObserveMainUI ui = startUI(context, config); + + if (log.isInfoEnabled()) { + log.info(t("observe.runner.ui.loaded")); + } + + Boolean h2ServerMode = ObserveSwingApplicationContext.Entries.H2_SERVER_MODE.get(); + + if (BooleanUtils.isTrue(h2ServerMode)) { + + // starts in h2 server mode + + ObserveSwingApplicationContext.get().removeH2ServerMode(); + + new StartServerModeAction(ui).run(); + + // on ne charge rien au démarrage + ui.getStatus().setStatus(t("observe.runner.loaded", config.getVersion())); + + return; + } + if (!config.isLoadLocalStorage()) { + + // on ne charge rien au démarrage + ui.getStatus().setStatus(t("observe.runner.loaded", config.getVersion())); + return; + } + + // 3 - init storage + + runAction(t("observe.runner.load.database"), context, "initStorage", config, ui, true); + + } + + @Override + protected void onClose(boolean reload) throws Exception { + if (ObserveSwingApplicationContext.isInit()) { + + if (log.isDebugEnabled()) { + log.debug("Will close context..."); + } + ObserveSwingApplicationContext.get().close(); + } + } + + @Override + protected void onShutdown() throws Exception { + if (log.isInfoEnabled()) { + log.info("ObServe shutdown at " + new Date()); + } + + try { + + // on éteint le context applicatif + onClose(false); + + // on ferme le service de traduction uniquement si on quitte + // definitivement l'application + I18n.close(); + + getActionExecutor().terminatesAndWaits(); + + } finally { + + Runtime.getRuntime().halt(0); + + } + + + } + + @Override + protected void onShutdown(Exception ex) { + if (log.isErrorEnabled()) { + log.error("error while closing " + ex.getMessage(), ex); + } + Runtime.getRuntime().halt(1); + } + + @Override + protected void onError(Exception e) { + UIHelper.handlingError(e); + } + + protected ObserveSwingApplicationConfig initConfig() throws Exception { + + ObserveSwingApplicationConfig config = new ObserveSwingApplicationConfig(); + + // init config (load application configuration) + config.initConfig(resourceManager); + + // init config arguments + config.parse(args); + + // install save action on option modification + config.installSaveAction(); + + if (log.isInfoEnabled()) { + String message = config.getConfigurationDescription(); + log.info(message); + } + + return config; + } + + protected void initUserDirectories(ObserveSwingApplicationConfig config) throws IOException { + + // 1 - user data directory + + File dataDirectory = resourceManager.createDirectory(config, DATA_DIRECTORY); + + if (log.isDebugEnabled()) { + log.debug("user data directory : " + dataDirectory); + } + + FileChooserUtil.setCurrentDirectory(dataDirectory); + + resourceManager.createParentDirectory(config, DB_DIRECTORY, INITIAL_DB_DUMP); + + // 2 - tmp directory + + resourceManager.createDirectory(config, TMP_DIRECTORY); + + // suppression du contenu du répertoire temporaire + FileUtils.cleanDirectory(config.getTmpDirectory()); + + // 3 - backup directory + + resourceManager.createDirectory(config, BACKUP_DIRECTORY); + + // 4 - resources directory + + File resourcesDirectory = resourceManager.createDirectory(config, RESOURCES_DIRECTORY); + + if (log.isDebugEnabled()) { + log.debug("user resource data directory : " + resourcesDirectory); + } + + // 5 - application ui + + File file = ObserveResourceManager.Resource.ui.getFile(resourcesDirectory); + + if (!file.exists()) { + + String message = t("observe.runner.copy.default.ui.file", file); + + resourceManager.copyResource(ObserveResourceManager.Resource.ui, file, message); + } + + // 6 - resources log configuration file + + file = ObserveResourceManager.Resource.LOG_CONFIGURATION_FILE.getFile(resourcesDirectory); + + if (!file.exists()) { + + String message = t("observe.runner.copy.default.logConfigurationFile.file", file); + + resourceManager.copyResource(ObserveResourceManager.Resource.LOG_CONFIGURATION_FILE, file, message); + + } + + // 7 - resources report + + File reportDirectory = resourceManager.createDirectory(config, REPORT_DIRECTORY); + + file = ObserveResourceManager.Resource.report.getFile(reportDirectory); + + if (!file.exists()) { + + String message = t("observe.runner.copy.default.report.file", file); + + resourceManager.copyResource(ObserveResourceManager.Resource.report, file, message); + + } + + // 8 - validation report directory + + resourceManager.createDirectory(config, VALIDATION_REPORT_DIRECTORY); + + // 9 - resources shapeFiles + + File mapdirectory = resourceManager.createDirectory(config, MAP_DIRECTORY); + + String message = t("observe.runner.copy.default.map.file", mapdirectory); + + resourceManager.unzipToDirectory(ObserveResourceManager.Resource.mapLayers, config, RESOURCES_DIRECTORY, message); + + } + + protected void detectLocalDataBase(ObserveSwingApplicationConfig config) { + boolean hasLocalStorage = new File(config.getLocalDBDirectory(), ObserveSwingApplicationConfig.DB_NAME).exists(); + config.setLocalStorageExist(hasLocalStorage); + if (!hasLocalStorage) { + if (log.isInfoEnabled()) { + log.info(t("observe.init.no.local.db.detected", config.getLocalDBDirectory())); + } + } + + boolean hasInitialDb = config.getInitialDbDump().exists(); + config.setInitialDumpExist(hasInitialDb); + + if (!hasInitialDb) { + if (log.isInfoEnabled()) { + log.info(t("observe.init.no.initial.dump.detected", config.getInitialDbDump())); + } + } + } + + protected void initI18n(ObserveSwingApplicationConfig config) { + + I18n.close(); + + File i18nDirectory = config.getI18nDirectory(); + + UserI18nInitializer i18nInitializer = new UserI18nInitializer(i18nDirectory, new DefaultI18nInitializer("observe-i18n")) { + + @Override + protected void createUserI18nLayout(File directory) throws Exception { + super.createUserI18nLayout(directory); + + // add also the i18n csv bundle + + URL resource = ObserveResourceManager.getResource("/META-INF/observe-i18n.csv"); + resourceManager.copyResource(resource, new File(directory, "observe-i18n.csv"), "Copy i18n csv bundle"); + } + }; + + long t00 = System.nanoTime(); + + Locale locale = config.getLocale(); + + I18n.init(i18nInitializer, locale); + + if (log.isDebugEnabled()) { + log.debug("i18n language : " + locale); + log.debug("i18n loading time : " + StringUtil.convertTime(t00, System.nanoTime())); + } + } + + protected void initUIConfiguration(ObserveSwingApplicationConfig config) { + + // prepare ui look&feel and load ui properties + try { + UIHelper.initNimbusLoookAndFeel(); + } catch (Exception e) { + // could not find nimbus look-and-feel + if (log.isWarnEnabled()) { + log.warn(t("observe.warning.nimbus.landf")); + } + } catch (Throwable e) { + if (log.isWarnEnabled()) { + log.warn(t("observe.warning.no.ui")); + } + // pas d'environnement d'ui + config.setCanUseUI(false); + } + + if (config.isCanUseUI()) { + + // chargement de la configuration des uis + loadUIConfig(config); + + } + } + + public void loadUIConfig(ObserveSwingApplicationConfig config) { + + // chargement de la configuration des uis + File dir = config.getResourcesDirectory(); + File file = ObserveResourceManager.Resource.ui.getFile(dir); + + + if (!file.exists()) { + + String message = t("observe.runner.copy.default.ui.file", file); + + try { + resourceManager.copyResource(ObserveResourceManager.Resource.ui, file, message); + } catch (IOException e) { + throw new ObserveSwingTechnicalException("could not copy ui configuration: " + file, e); + } + } + + if (log.isInfoEnabled()) { + log.info(t("observe.runner.loading.ui.configuration", file)); + } + try { + Properties p = resourceManager.getResource(file); + UIHelper.loadUIConfig(p); + } catch (IOException e) { + + throw new ObserveSwingTechnicalException("could not load ui configuration: " + file, e); + + } + + } + + protected ObserveMainUI startUI(ObserveSwingApplicationContext context, ObserveSwingApplicationConfig config) { + + ObserveMainUIHandler uiHandler = context.getContextValue(ObserveMainUIHandler.class); + + ObserveMainUI ui = uiHandler.initUI(context, config); + + UIHelper.setMainUIVisible(ui); + return ui; + } + + /** + * Method pour vérifier que le moteur de scripting est bien présent. + * + * Voir http://forge.codelutin.com/issues/829 + * + * @since 2.5 + */ + protected void checkScriptEngineFound() { + + ScriptEngineManager factory = new ScriptEngineManager(); + + ScriptEngine scriptEngine = factory.getEngineByExtension("js"); + + if (scriptEngine == null) { + + // script engine pas trouvé. + String message = "Could not found script engine, use a Oracle jvm"; + if (Locale.FRANCE.getCountry().equals(Locale.getDefault().getCountry())) { + message = "Moteur de scripting non trouvé, Utiliser une jvm fournie par Oracle."; + } + onError(new ScriptException(message)); + } + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveSwingApplicationContext.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveSwingApplicationContext.java new file mode 100644 index 0000000..472651f --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveSwingApplicationContext.java @@ -0,0 +1,715 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing; + +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.db.constants.DbMode; +import fr.ird.observe.application.swing.db.event.ObserveSwingDataSourceEvent; +import fr.ird.observe.application.swing.db.event.ObserveSwingDataSourceListenerAdapter; +import fr.ird.observe.services.ObserveDataSourceConfigurationMainFactory; +import fr.ird.observe.services.ObserveServiceMainFactory; +import fr.ird.observe.services.ObserveServicesProvider; +import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaH2; +import fr.ird.observe.services.configuration.ObserveDataSourceInformation; +import fr.ird.observe.services.dto.constants.ReferentialLocale; +import fr.ird.observe.services.dto.reference.ReferenceBinderEngine; +import fr.ird.observe.services.dto.reference.ReferenceBinderEngineSupplier; +import fr.ird.observe.services.service.BabModelVersionException; +import fr.ird.observe.services.service.DatabaseConnexionNotAuthorizedException; +import fr.ird.observe.services.service.DatabaseNotFoundException; +import fr.ird.observe.services.service.actions.validate.ValidateServiceUtils; +import fr.ird.observe.services.service.actions.validate.ValidatorDto; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.ObserveUIMode; +import fr.ird.observe.application.swing.ui.actions.ChangeStorageAction; +import fr.ird.observe.application.swing.ui.actions.shared.AbstractUIAction; +import fr.ird.observe.application.swing.ui.actions.shared.CancelCreateUIAction; +import fr.ird.observe.application.swing.ui.actions.shared.CloseAndCreateUIAction; +import fr.ird.observe.application.swing.ui.actions.shared.CloseOpenUIAction; +import fr.ird.observe.application.swing.ui.actions.shared.DeleteDataUIAction; +import fr.ird.observe.application.swing.ui.actions.shared.DeleteReferenceUIAction; +import fr.ird.observe.application.swing.ui.actions.shared.GoDownUIAction; +import fr.ird.observe.application.swing.ui.actions.shared.GoUpUIAction; +import fr.ird.observe.application.swing.ui.actions.shared.MoveActivityLonglinesUIAction; +import fr.ird.observe.application.swing.ui.actions.shared.MoveActivitySeinesUIAction; +import fr.ird.observe.application.swing.ui.actions.shared.MoveRoutesUIAction; +import fr.ird.observe.application.swing.ui.actions.shared.MoveTripLonglinesUIAction; +import fr.ird.observe.application.swing.ui.actions.shared.MoveTripSeinesUIAction; +import fr.ird.observe.application.swing.ui.actions.shared.ReOpenUIAction; +import fr.ird.observe.application.swing.ui.actions.shared.ResetEditUIAction; +import fr.ird.observe.application.swing.ui.actions.shared.SaveEditUIAction; +import fr.ird.observe.application.swing.ui.actions.shared.SelectNodeUIAction; +import fr.ird.observe.application.swing.ui.actions.shared.SelectOpenNodeUIAction; +import fr.ird.observe.application.swing.ui.content.ContentUIManager; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import fr.ird.observe.application.swing.validation.ValidationContext; +import jaxx.runtime.context.DefaultApplicationContext; +import jaxx.runtime.context.JAXXContextEntryDef; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.h2.tools.Server; + +import javax.swing.ActionMap; +import javax.swing.JOptionPane; +import java.io.Closeable; +import java.io.File; +import java.util.Arrays; +import java.util.Collection; +import java.util.EnumSet; +import java.util.List; +import java.util.Objects; +import java.util.Set; +import java.util.UUID; + +import static fr.ird.observe.application.swing.ObserveSwingApplicationContext.Entries.ACTIONS; +import static fr.ird.observe.application.swing.ObserveSwingApplicationContext.Entries.ACTION_MAP; +import static fr.ird.observe.application.swing.ObserveSwingApplicationContext.Entries.BINDER_SERVICE; +import static fr.ird.observe.application.swing.ObserveSwingApplicationContext.Entries.CONFIG; +import static fr.ird.observe.application.swing.ObserveSwingApplicationContext.Entries.CONTENT_UI_MANAGER; +import static fr.ird.observe.application.swing.ObserveSwingApplicationContext.Entries.DATA_CONTEXT; +import static fr.ird.observe.application.swing.ObserveSwingApplicationContext.Entries.DATA_SOURCES_MANAGER; +import static fr.ird.observe.application.swing.ObserveSwingApplicationContext.Entries.DATA_SOURCE_CONFIGURATION_FACTORY; +import static fr.ird.observe.application.swing.ObserveSwingApplicationContext.Entries.DECORATOR_SERVICE; +import static fr.ird.observe.application.swing.ObserveSwingApplicationContext.Entries.H2_SERVER; +import static fr.ird.observe.application.swing.ObserveSwingApplicationContext.Entries.H2_SERVER_MODE; +import static fr.ird.observe.application.swing.ObserveSwingApplicationContext.Entries.H2_WEBSERVER; +import static fr.ird.observe.application.swing.ObserveSwingApplicationContext.Entries.MAIN_UI; +import static fr.ird.observe.application.swing.ObserveSwingApplicationContext.Entries.NODE_TO_RESELECT; +import static fr.ird.observe.application.swing.ObserveSwingApplicationContext.Entries.OPEN_DATA_MANAGER; +import static fr.ird.observe.application.swing.ObserveSwingApplicationContext.Entries.TEXT_GENERATOR; +import static fr.ird.observe.application.swing.ObserveSwingApplicationContext.Entries.VALIDATION_CONTEXT; +import static fr.ird.observe.application.swing.ObserveSwingApplicationContext.Entries.VALIDATORS; +import static fr.ird.observe.application.swing.ui.UIHelper.askUser; +import static fr.ird.observe.application.swing.ui.UIHelper.displayInfo; +import static fr.ird.observe.application.swing.ui.UIHelper.handlingError; +import static fr.ird.observe.application.swing.ui.UIHelper.newContextEntryDef; +import static fr.ird.observe.application.swing.ui.UIHelper.newListContextEntryDef; +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Le contexte de l'application. + * + * On définit ici toutes les entrées du contexte. + * + * Note : cette classe possède une instance partagée accéssible via la méthode + * {@link #get()}. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class ObserveSwingApplicationContext extends DefaultApplicationContext implements Closeable { + + /** Logger */ + private static final Log log = LogFactory.getLog(ObserveSwingApplicationContext.class); + + enum Entries { + + CONFIG("Config", ObserveSwingApplicationConfig.class), + DECORATOR_SERVICE("Decorator service", DecoratorService.class), + TEXT_GENERATOR("Text generator", ObserveTextGenerator.class), + SERVICE_MAIN_FACTORY("Service main factory", ObserveServiceMainFactory.class), + DATA_SOURCE_CONFIGURATION_FACTORY("Data source configuration main factory", ObserveDataSourceConfigurationMainFactory.class), + OPEN_DATA_MANAGER("Open data manager", ObserveOpenDataManager.class), + BINDER_SERVICE("Binder service", ObserveSwingBinderService.class), + DATA_CONTEXT("Data context", DataContext.class), + CONTENT_UI_MANAGER("Content UI manager", ContentUIManager.class), + DATA_SOURCES_MANAGER("Data sources manager", ObserveSwingApplicationDataSourcesManager.class), + VALIDATION_CONTEXT("Validation context", ValidationContext.class), + MAIN_UI("Main UI", ObserveMainUI.class), + ACTIONS("Command line Actions", ObserveCLAction.class), + ACTION_MAP("UI Actions", ActionMap.class), + H2_SERVER_MODE("H2 Server mode", Boolean.class), + H2_SERVER("H2 Server", Server.class), + H2_WEBSERVER("H2 Web server", Server.class), + VALIDATORS("Validators"), + NODE_TO_RESELECT("Node to reselect"); + + private final String objectName; + private final JAXXContextEntryDef entryDef; + + <O> Entries(String objectName, Class<O> entryType) { + this.objectName = objectName; + this.entryDef = newContextEntryDef(objectName, entryType); + } + + <O> Entries(String objectName) { + this.objectName = objectName; + this.entryDef = newListContextEntryDef(objectName); + } + + public <O> O get() { + return (O) entryDef.getContextValue(ObserveSwingApplicationContext.get()); + } + + private <O> void set(O instance) { + entryDef.setContextValue(ObserveSwingApplicationContext.get(), instance); + if (log.isInfoEnabled()) { + log.info("Add to application context " + objectName + ": " + (instance instanceof Collection ? ((Collection)instance).size()+" element(s)": instance)); + } + } + + private <O> void remove() { + O instance = get(); + entryDef.removeContextValue(ObserveSwingApplicationContext.get()); + if (log.isInfoEnabled()) { + log.info("Remove from application context " + objectName + ": " + (instance instanceof Collection ? ((Collection)instance).size()+" element(s)": instance)); + } + } + } + + private static ObserveSwingApplicationContext INSTANCE; + + /** Un objet pour bloquer le context */ + private final Object lock; + + private final ReferenceBinderEngine referenceBinderEngine; + + /** Un drapeau pour savoir quand l'application est en cours de fermeture. */ + private boolean closed; + + /** + * Un drapeau pour activer sur les connections le support JMX. + * + * @since 2.2 + */ + private boolean useJMX; + + /** + * Récupération du contexte applicatif. + * + * @return l'instance partagé du contexte. + * @throws IllegalStateException si le contexte n'a pas été initialisé + */ + public static ObserveSwingApplicationContext get() throws IllegalStateException { + Objects.requireNonNull(INSTANCE, "no application context initialized."); + return INSTANCE; + } + + /** @return {@code true} si le context a été initialisé */ + public static boolean isInit() { + return INSTANCE != null; + } + + public ObserveSwingApplicationContext(ObserveSwingApplicationConfig config) { + + Preconditions.checkState(INSTANCE == null, "application context already registred."); + + INSTANCE = this; + + CONFIG.set(config); + BINDER_SERVICE.set(new ObserveSwingBinderService()); + ACTIONS.set(new ObserveCLAction()); + CONTENT_UI_MANAGER.set(new ContentUIManager()); + DATA_SOURCES_MANAGER.set(new ObserveSwingApplicationDataSourcesManager()); + DATA_SOURCE_CONFIGURATION_FACTORY.set(new ObserveDataSourceConfigurationMainFactory()); + DECORATOR_SERVICE.set(new DecoratorService(ReferentialLocale.valueOf(config.getDbLocale()))); + TEXT_GENERATOR.set(new ObserveTextGenerator(config)); + DATA_CONTEXT.set(new DataContext()); + OPEN_DATA_MANAGER.set(new ObserveOpenDataManager(getDataContext())); + VALIDATION_CONTEXT.set(new ValidationContext(getDataContext())); + VALIDATORS.set(Lists.newArrayList(ValidateServiceUtils.getValidators())); + referenceBinderEngine = new ReferenceBinderEngineSupplier().get(); + lock = new Object(); + } + + //------------------------------------------- + // - Read + //------------------------------------------- + + public boolean isUseJMX() { + return useJMX; + } + + /** + * @return {@code true} si le context applicatif a été fermé (et est donc + * passé dans la méthode {@link #close()}, {@code false} autrement. + */ + public boolean isClosed() { + return closed; + } + + public ObserveSwingApplicationConfig getConfig() { + return CONFIG.get(); + } + + public ContentUIManager getContentUIManager() { + return CONTENT_UI_MANAGER.get(); + } + + public ObserveSwingApplicationDataSourcesManager getDataSourcesManager() { + return DATA_SOURCES_MANAGER.get(); + } + + public ReferenceBinderEngine getReferenceBinderEngine() { + return referenceBinderEngine; + } + + public DecoratorService getDecoratorService() { + return DECORATOR_SERVICE.get(); + } + + public ObserveTextGenerator getTextGenerator() { + return TEXT_GENERATOR.get(); + } + + public ObserveOpenDataManager getOpenDataManager() { + return OPEN_DATA_MANAGER.get(); + } + + public ObserveDataSourceConfigurationMainFactory getObserveDataSourceConfigurationMainFactory() { + return DATA_SOURCE_CONFIGURATION_FACTORY.get(); + } + + public ObserveServicesProvider getMainDataSourceServicesProvider() { + return getDataSourcesManager().getMainDataSource(); + } + + public DataContext getDataContext() { + return DATA_CONTEXT.get(); + } + + public ValidationContext getValidationContext() { + return VALIDATION_CONTEXT.get(); + } + + public final ImmutableSet<ValidatorDto> getValidators() { + return ImmutableSet.copyOf((List) VALIDATORS.get()); + } + + public ObserveMainUI getMainUI() { + return MAIN_UI.get(); + } + + public List<String> getNodesToReselect() { + return NODE_TO_RESELECT.get(); + } + + public ActionMap getActionMap() { + return ACTION_MAP.get(); + } + + public Server getH2Server() { + return H2_SERVER.get(); + } + + public Server getH2WebServer() { + return H2_WEBSERVER.get(); + } + + //------------------------------------------- + // - Write + //------------------------------------------- + + public void setUseJMX(boolean useJMX) { + this.useJMX = useJMX; + } + + public void setNodesToReselect(String[] paths) { + if (paths == null) { + NODE_TO_RESELECT.remove(); + + } else { + NODE_TO_RESELECT.set(Arrays.asList(paths)); + } + } + + public void setH2Server(Server server) { + H2_SERVER.set(server); + } + + public void setH2WebServer(Server server) { + H2_WEBSERVER.set(server); + } + + public void setMainUI(ObserveMainUI ui) { + MAIN_UI.set(ui); + } + + public void removeMainUI() { + MAIN_UI.remove(); + } + + public void removeH2ServerMode() { + H2_SERVER_MODE.remove(); + } + + + public void registerShareActions() { + + ObserveMainUI ui = getMainUI(); + ActionMap actionMap = ui.getRootPane().getActionMap(); + + ACTION_MAP.set(actionMap); + + registerMainAction(actionMap, new SelectOpenNodeUIAction(ui)); + registerMainAction(actionMap, new SelectNodeUIAction(ui)); + registerMainAction(actionMap, new GoUpUIAction(ui)); + registerMainAction(actionMap, new GoDownUIAction(ui)); + registerMainAction(actionMap, new ReOpenUIAction(ui)); + registerMainAction(actionMap, new CloseOpenUIAction(ui)); + registerMainAction(actionMap, new CloseAndCreateUIAction(ui)); + registerMainAction(actionMap, new CancelCreateUIAction(ui)); + registerMainAction(actionMap, new ResetEditUIAction(ui)); + registerMainAction(actionMap, new SaveEditUIAction(ui)); + registerMainAction(actionMap, new DeleteDataUIAction(ui)); + registerMainAction(actionMap, new DeleteReferenceUIAction(ui)); + registerMainAction(actionMap, new MoveTripLonglinesUIAction(ui)); + registerMainAction(actionMap, new MoveTripSeinesUIAction(ui)); + registerMainAction(actionMap, new MoveRoutesUIAction(ui)); + registerMainAction(actionMap, new MoveActivitySeinesUIAction(ui)); + registerMainAction(actionMap, new MoveActivityLonglinesUIAction(ui)); + + } + + //------------------------------------------- + // - Locks + //------------------------------------------- + + public void lock() throws InterruptedException { + synchronized (lock) { + lock.wait(); + } + } + + public void releaseLock() { + synchronized (lock) { + lock.notifyAll(); + } + } + + //------------------------------------------- + // - Storages + //------------------------------------------- + + public ObserveSwingDataSource createTemporaryH2Storage(String label) { + ObserveDataSourceConfigurationMainFactory configurationMainFactory = getObserveDataSourceConfigurationMainFactory(); + + File tmpDirectory = getConfig().getTmpDirectory(); + + File dbDirectory = new File(tmpDirectory, ObserveSwingApplicationConfig.DB_NAME + UUID.randomUUID().toString()); + + ObserveDataSourceConfigurationTopiaH2 config = configurationMainFactory.createObserveDataSourceConfigurationTopiaH2( + label, + dbDirectory, + ObserveSwingApplicationConfig.DB_NAME, + getConfig().getH2Login(), + getConfig().getH2Password(), + false, + false, + getConfig().getModelVersion() + ); + + ObserveSwingDataSource result = getDataSourcesManager().newDataSource(config); + + return result; + } + + public void initStorage(ObserveSwingApplicationConfig config, ObserveMainUI mainUI, boolean askToCreate) { + + if (config.isLocalStorageExist()) { + + // une base locale existe, on l'ouvre + + boolean success = false; + // chargement de la base locale + + // création de la source de données sur la base locale + ObserveSwingDataSource dataSource = getDataSourcesManager().newLocalDatasource(getConfig()); + + try { + + ObserveDataSourceInformation dataSourceInformation = dataSource.checkCanConnect(); + + dataSource.migrateData(dataSourceInformation, getConfig().getModelVersion()); + + // la source sera utilisée dans les ui + prepareMainStorage(dataSource, true); +// getDataSourcesManager().setMainDataSource(dataSource); + + if (log.isInfoEnabled()) { + log.info(t("observe.init.local.db.detected", dataSource.getLabel())); + } + + // la base locale existe, on l'ouvre + dataSource.open(); + success = true; + } catch (DatabaseConnexionNotAuthorizedException | DatabaseNotFoundException | BabModelVersionException e) { + JOptionPane.showMessageDialog( + null, + e.getMessage(), + t("observe.title.error.dialog"), + JOptionPane.ERROR_MESSAGE + ); + } + + if (success) { + // on peut retourner sur cette base + mainUI.setMode(ObserveUIMode.DB); + } + + } else { + + // on peut retourner sur cette base + mainUI.setMode(ObserveUIMode.NO_DB); + + if (askToCreate) { + + // demande à l'utilisateur s'il veut créer la base locale + + int reponse = askUser( + t("observe.title.no.local.db.found"), + t("observe.message.no.local.db.found", + config.getLocalDBDirectory()), + JOptionPane.QUESTION_MESSAGE, + new Object[]{ + t("observe.choice.useRemoteStorage"), + t("observe.choice.createLocalStorage"), + t("observe.choice.doNothing") + }, + 1 + ); + if (log.isDebugEnabled()) { + log.debug("response : " + reponse); + } + + Set<DbMode> dbModes = EnumSet.noneOf(DbMode.class); + String title = null; + if (reponse != JOptionPane.CLOSED_OPTION && reponse < 2) { + + if (reponse == 1) { + // creation de la base locale + dbModes.add(DbMode.CREATE_LOCAL); + title = n("observe.title.create.local.db"); + } else { + // connexion à une base distante + dbModes.add(DbMode.USE_REMOTE); + dbModes.add(DbMode.USE_SERVER); + title = n("observe.title.load.remote.db"); + } + } + if (!dbModes.isEmpty()) { + new ChangeStorageAction(getMainUI(), dbModes, title).run(); + } + + } + } + if (log.isInfoEnabled()) { + log.info(t("observe.init.storage.done")); + } + } + + + /** + * Prepare le storage principal qui servira dans les ui. + * + * @param dataSource la source de données a preparer + */ + public void prepareMainStorage(ObserveSwingDataSource dataSource, boolean setAsMainDataSource) { + + if (setAsMainDataSource) { + + getDataSourcesManager().setMainDataSource(dataSource); + + } + + dataSource.addObserveSwingDataSourceListener(new ObserveSwingDataSourceListenerAdapter() { + + @Override + public void onOpening(ObserveSwingDataSourceEvent event) { + ObserveSwingDataSource s = event.getSource(); + displayInfo(t("observe.message.db.loading", s.getLabel())); + } + + @Override + public void onOpened(ObserveSwingDataSourceEvent event) { + + // le service est disponible, on enregistre les listeners + ObserveSwingDataSource source = event.getSource(); + + try { + openOnUI(source); + } catch (Exception e) { + + // la base n'a pas pu être chargée proprement + // ceci peut être due a une base dans une version pas + // assez recente, on doit donc refermer cette base + handlingError("Could not obtain open datas from " + source.getLabel(), e); + + // fermeture de la source + source.close(); + } + + } + + @Override + public void onClosing(ObserveSwingDataSourceEvent event) { + + super.onClosing(event); + + ObserveMainUI mainUI = getMainUI(); + DataContext dataContext = getDataContext(); + dataContext.setEnabled(false); + + // suppresion des opens dans le context de données + getConfig().setTreeOpenNodeIds(dataContext.getOpenIds()); + dataContext.populateOpens(); + + mainUI.getTreeHelper().cleanNavigationUI(mainUI); + + // on met a jour l'état dans la config + getConfig().setMainStorageOpened(false); + + } + + + @Override + public void onClosed(ObserveSwingDataSourceEvent event) { + // le service est indisponible, il faut supprimer toutes les + // references vers le service + ObserveSwingDataSource source = event.getSource(); + + // on ferme la marée, la route ou l'activité ouvertes + getOpenDataManager().close(); + + ObserveMainUI mainUI = getMainUI(); + + // nettoyage de l'ui ( suppression navigation et autres ) + if (mainUI != null) { + + if (log.isDebugEnabled()) { + log.debug("dispose ui from storage " + source.getLabel() + ": " + mainUI.getName()); + } + + mainUI.setMode(ObserveUIMode.NO_DB); + + displayInfo(t("observe.message.db.closed", source.getLabel())); + + } + + source.removeObserveSwingDataSourceListener(this); + + } + + protected void openOnUI(ObserveSwingDataSource source) { + // on rend le service disponible dans le service de validation + //getValidationContext().setMainDataSource(source); + + // toutes les données sont chargées, on peut declarer le service + // comme ouvert dans la configuration + ObserveSwingApplicationConfig config = getConfig(); + config.setMainStorageOpened(true); + config.setMainStorageOpenedLocal(source.isLocal()); + + if (source.isLocal()) { + config.setLocalStorageExist(true); + } + + // remplissage de l'ui + ObserveMainUI mainUI = getMainUI(); + + if (mainUI != null) { + if (log.isDebugEnabled()) { + log.debug("loading ui for storage " + source.getLabel() + ": " + mainUI.getName()); + } + + DataContext dataContext = mainUI.getDataContext(); + dataContext.setEnabled(true); + + ObserveTreeHelper treeHelper = mainUI.getTreeHelper(); + + treeHelper.cleanNavigationUI(mainUI); + + String[] openIds = config.getTreeOpenNodeIds(); + + if (source.canReadData()) { + getOpenDataManager().sanitizeOpenIds(openIds); + } + + dataContext.populateOpens(openIds); + treeHelper.loadNavigationUI(source); + + mainUI.setMode(ObserveUIMode.DB); + + mainUI.getStatus().setStatus(t("observe.message.db.loaded", source.getLabel())); + + } + } + }); + } + + @Override + public void close() { + if (log.isInfoEnabled()) { + log.info("Closing swing application context " + this); + } + + // fermeture de touts les context de donnée ouvert + getDataSourcesManager().close(); + + ObserveServiceMainFactory serviceMainFactory = ObserveServiceMainFactory.get(); + if (log.isInfoEnabled()) { + log.info("Closing main service factory: " + serviceMainFactory); + } + serviceMainFactory.close(); + + // fermeture du context principal + clear(); + + INSTANCE = null; + + closed = true; + + } + + @Override + protected void finalize() throws Throwable { + if (!closed) { + close(); + } + super.finalize(); + } + + private void registerMainAction(ActionMap actionMap, AbstractUIAction action) { + String actionId = action.getActionId(); + if (log.isInfoEnabled()) { + log.info("Register UI action " + actionId); + } + actionMap.put(actionId, action); + } + +// private ObjectName createMBean(DataSource source) throws MalformedObjectNameException { +// Hashtable<String, String> tb = new Hashtable<String, String>(); +// tb.put("type", "statistics"); +// String name = source.getLabel(); +// tb.put("sessionFactory", name.replaceAll(":", "_")); +// // MBean object name +// ObjectName on = new ObjectName("hibernate", tb); +// return on; +// } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveSwingApplicationDataSourcesManager.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveSwingApplicationDataSourcesManager.java new file mode 100644 index 0000000..0a6bcef --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveSwingApplicationDataSourcesManager.java @@ -0,0 +1,108 @@ +package fr.ird.observe.application.swing; + +import com.google.common.base.Preconditions; +import com.google.common.collect.Lists; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.db.event.ObserveSwingDataSourceEvent; +import fr.ird.observe.application.swing.db.event.ObserveSwingDataSourceListenerAdapter; +import fr.ird.observe.services.configuration.ObserveDataSourceConfiguration; +import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaH2; + +import java.io.Closeable; +import java.util.LinkedList; +import java.util.List; + +import static jaxx.runtime.swing.editor.bean.BeanUIUtil.PopupHandler.log; +import static org.nuiton.i18n.I18n.t; + +/** + * Permet de gérer les différentes data sources utilisées dans l'application. + * + * Created on 09/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class ObserveSwingApplicationDataSourcesManager implements Closeable { + + private final List<ObserveSwingDataSource> dataSources = new LinkedList<>(); + + private ObserveSwingDataSource dataSource; + + /** + * Construit une source de données sur la base locale de l'application. + * + * <b>Note:</b> La base locale doit exister, sinon on soulève une + * exeception + * + * @param config la configuration à utiliser + * @return la service de persistance initialisé (mais non ouvert) + */ + public ObserveSwingDataSource newLocalDatasource(ObserveSwingApplicationConfig config) { + + ObserveDataSourceConfigurationTopiaH2 dataSourceConfigurationH2 = config.getDataSourceConfigurationH2(t("observe.storage.label.local")); + + Preconditions.checkState(dataSourceConfigurationH2.getDatabaseFile().exists(), "local base must exist, when using this method (" + + dataSourceConfigurationH2.getDirectory() + ')'); + return newDataSource(dataSourceConfigurationH2); + } + + public ObserveSwingDataSource getMainDataSource() { + return dataSource; + } + + public void setMainDataSource(ObserveSwingDataSource dataSource) { + this.dataSource = dataSource; + } + + public ObserveSwingDataSource newDataSource(ObserveDataSourceConfiguration configuration) { + ObserveSwingDataSource dataSource = new ObserveSwingDataSource(configuration); + + dataSource.addObserveSwingDataSourceListener(new ObserveSwingDataSourceListenerAdapter() { + + @Override + public void onOpened(ObserveSwingDataSourceEvent event) { + super.onOpened(event); + ObserveSwingDataSource dataSource = event.getSource(); + dataSources.add(dataSource); + + if (log.isInfoEnabled()) { + log.info("Data source opened : " + dataSource.getConfiguration() + " (" + dataSources.size() + " datas sources open)"); + } + } + + @Override + public void onClosed(ObserveSwingDataSourceEvent event) { + super.onClosed(event); + ObserveSwingDataSource dataSource = event.getSource(); + dataSources.remove(dataSource); + if (log.isInfoEnabled()) { + log.info("Data source closed : " + dataSource.getConfiguration() + " (" + dataSources.size() + " datas sources open)"); + } + } + }); + + return dataSource; + } + + @Override + public void close() { + + // fermeture de touts les context de donnée ouvert + for (ObserveSwingDataSource dataSource : Lists.newArrayList(dataSources)) { + if (log.isInfoEnabled()) { + log.info("Closing dataSource : " + dataSource.getConnection()); + } + try { + dataSource.close(); + } catch (Exception e) { + if (log.isErrorEnabled()) { + log.error("Could not close data source: " + dataSource, e); + } + } + } + setMainDataSource(null); + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveSwingBinderService.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveSwingBinderService.java new file mode 100644 index 0000000..3428127 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveSwingBinderService.java @@ -0,0 +1,50 @@ +/* + * #%L + * ObServe :: Business + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing; + +import fr.ird.observe.services.dto.AbstractObserveDto; +import org.nuiton.util.beans.BinderModelBuilder; + +/** + * Service d'utilisation des binders + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ObserveSwingBinderService { + + public <E extends AbstractObserveDto> BinderModelBuilder<E, E> newBinderBuilder(Class<E> type, String... properties) { + BinderModelBuilder<E, E> builder = BinderModelBuilder.newEmptyBuilder(type); + builder.addSimpleProperties(properties); + return builder; + } + + public <E extends AbstractObserveDto> void simpleCopy(E source, E target, boolean tech) { + //FIXME +// Class<E> entityClass = (Class<E>) TopiaEntityHelper.getContractClass(ObserveDAOHelper.getContracts(), target.getClass()); +// TopiaEntityBinder<E> binder = getSimpleTopiaBinder(entityClass); +// if (binder == null) { +// throw new NullPointerException("could not find a simple topia binder of type : " + target.getClass()); +// } +// binder.load(source, target, tech); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveSwingTechnicalException.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveSwingTechnicalException.java new file mode 100644 index 0000000..c242623 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveSwingTechnicalException.java @@ -0,0 +1,50 @@ +package fr.ird.observe.application.swing; + +/* + * #%L + * ObServe :: Business + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +/** + * Created on 8/30/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.7 + */ +public class ObserveSwingTechnicalException extends RuntimeException { + + private static final long serialVersionUID = 1L; + + public ObserveSwingTechnicalException() { + } + + public ObserveSwingTechnicalException(String message) { + super(message); + } + + public ObserveSwingTechnicalException(String message, Throwable cause) { + super(message, cause); + } + + public ObserveSwingTechnicalException(Throwable cause) { + super(cause); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveTextGenerator.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveTextGenerator.java new file mode 100644 index 0000000..32388ce --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ObserveTextGenerator.java @@ -0,0 +1,133 @@ +package fr.ird.observe.application.swing; + +/*- + * #%L + * ObServe :: Application Swing + * %% + * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.configuration.ObserveDataSourceConfiguration; +import fr.ird.observe.services.configuration.ObserveDataSourceInformation; +import fr.ird.observe.application.swing.ui.storage.StorageUIModel; +import freemarker.cache.ClassTemplateLoader; +import freemarker.template.Configuration; +import freemarker.template.Template; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.jaxx.application.ApplicationTechnicalException; + +import java.io.StringWriter; +import java.io.Writer; +import java.util.Locale; + +import static org.nuiton.i18n.I18n.t; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class ObserveTextGenerator { + + private static final Log log = LogFactory.getLog(ObserveTextGenerator.class); + + protected static final String DATA_SOURCE_CONFIGURATION_TEMPLATE = "dataSourceConfiguration.ftl"; + + protected static final String CONNEXION_TEST_RESULT_TEMPLATE = "connexionTestResult.ftl"; + + protected static final String DATA_SOURCE_SELECT_MODE_RESUME_TEMPLATE = "dataSourceSelectModeResume.ftl"; + + protected static final String DATA_SOURCE_CONNECTION_REPORT_TEMPLATE = "dataSourceConnectionReport.ftl"; + + protected static final String DATA_SOURCE_INFORMATION_TEMPLATE = "dataSourceInformation.ftl"; + + protected static final String DATA_SOURCE_POLICY_TEMPLATE = "dataSourcePolicy.ftl"; + + + protected final Configuration freemarkerConfiguration; + + protected final ObserveSwingApplicationConfig observeConfiguration; + + public ObserveTextGenerator(ObserveSwingApplicationConfig observeConfiguration) { + this.observeConfiguration = observeConfiguration; + + freemarkerConfiguration = new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS); + + // needed to overwrite "Defaults to default system encoding." + // fix encoding issue on some systems + freemarkerConfiguration.setEncoding(Locale.getDefault(), "UTF-8"); + + // specific template loader to get template from jars (classpath) + ClassTemplateLoader templateLoader = new ClassTemplateLoader(ObserveTextGenerator.class, "/ftl"); + freemarkerConfiguration.setTemplateLoader(templateLoader); + +// freemarkerConfiguration.setObjectWrapper(new BeansWrapper(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS)); + } + + public String getConfigurationDetail(ObserveDataSourceConfiguration dataSourceConfiguration) { + return generateHtml(DATA_SOURCE_CONFIGURATION_TEMPLATE, dataSourceConfiguration); + } + + public String getConnexionTestResultMessage(StorageUIModel model) { + return generateHtml(CONNEXION_TEST_RESULT_TEMPLATE, model); + } + + public String getLoadDataSourceResume(StorageUIModel model) { + return generateHtml(DATA_SOURCE_SELECT_MODE_RESUME_TEMPLATE, model); + } + + public String getDataSourceConnectionReport(StorageUIModel model) { + return generateHtml(DATA_SOURCE_CONNECTION_REPORT_TEMPLATE, model); + } + + public String getDataSourceInfo(ObserveSwingDataSource source) { + return generateHtml(DATA_SOURCE_INFORMATION_TEMPLATE, source); + } + + public String getDataSourcePolicy(ObserveDataSourceInformation model) { + return generateHtml(DATA_SOURCE_POLICY_TEMPLATE, model); + } + + protected String generateHtml(String templateName, Object model) { + return generateHtml(observeConfiguration.getLocale(), templateName, model); + } + + protected String generateHtml(Locale locale, String templateName, Object model) { + + try { + + // Get freemarker template + Template mapTemplate = freemarkerConfiguration.getTemplate(templateName, locale); + + Writer out = new StringWriter(); + mapTemplate.process(model, out); + + out.flush(); + + return out.toString(); + + + } catch (Exception ex) { + if (log.isErrorEnabled()) { + log.error("error while generating html", ex); + } + throw new ApplicationTechnicalException(t("observe.generateHtml.error", templateName), ex); + } + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/configuration/ObserveSwingApplicationConfig.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/configuration/ObserveSwingApplicationConfig.java new file mode 100644 index 0000000..4c3d7d8 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/configuration/ObserveSwingApplicationConfig.java @@ -0,0 +1,1168 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.configuration; + +import com.google.common.base.Charsets; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import fr.ird.observe.application.swing.ObserveCLAction; +import fr.ird.observe.application.swing.ObserveResourceManager; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.constants.CreationMode; +import fr.ird.observe.application.swing.db.constants.DbMode; +import fr.ird.observe.services.ObserveDataSourceConfigurationMainFactory; +import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationRest; +import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaH2; +import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaPG; +import fr.ird.observe.application.swing.ui.UIHelper; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.config.ApplicationConfig; +import org.nuiton.config.ApplicationConfigHelper; +import org.nuiton.config.ApplicationConfigProvider; +import org.nuiton.version.Version; +import org.nuiton.version.Versions; + +import javax.swing.JOptionPane; +import java.awt.Color; +import java.beans.PropertyChangeListener; +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.util.ArrayList; +import java.util.Calendar; +import java.util.Date; +import java.util.List; +import java.util.Locale; +import java.util.Properties; +import java.util.Set; + +import static fr.ird.observe.application.swing.ObserveResourceManager.Resource; +import static org.nuiton.i18n.I18n.t; + +/** + * La configuration de l'application. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class ObserveSwingApplicationConfig extends ApplicationConfig { + + + /** + * le fichier de configuration de l'application avec les informations sur le + * projet (version, license,...) et la configuration des ui (icons, ...) + */ + public static final String APPLICATION_PROPERTIES = "/observe.properties"; + + /** le lastName du repertoire ou sont les donnees de l'application */ + public static final String USER_DIRECTORY_FILENAME = ".observe"; + + /** le pattern du fichier de sauvegarde d'une base locale */ + public static final String BACKUP_DB_PATTERN = "obstuna-local-%1$tF--%1$tk-%1$tM-%1$tS.sql.gz"; + + /** le pattern du fichier de sauvegarde d'une base access importée */ + public static final String ACCESS_DB_PATTERN = "import-access-%1$tF--%1$tk-%1$tM-%1$tS.sql.gz"; + + /** le pattern du fichier de rapport après validation */ + public static final String REPORT_PATTERN = "report-%1$tF--%1$tk-%1$tM-%1$tS.sql.gz"; + + public static final String DB_NAME = "obstuna"; + + /** + * La version de l'application. + */ + public static final String APPLICATION_VERSION = "application.version"; + + public static final String VERSION = "version"; + + public static final String PROPERTY_DEFAULT_DB_MODE = "defaultDbMode"; + + public static final String PROPERTY_DEFAULT_CREATION_MODE = "defaultCreationMode"; + + public static final String PROPERTY_SPECIES_LIST_SEINE_TARGET_CATCH_ID = "speciesListSeineTargetCatchId"; + + public static final String PROPERTY_SPECIES_LIST_SEINE_SCHOOL_ESTIMATE_ID = "speciesListSeineSchoolEstimateId"; + + public static final String PROPERTY_SPECIES_LIST_SEINE_OBJECT_SCHOOL_ESTIMATE_ID = "speciesListSeineObjectSchoolEstimateId"; + + public static final String PROPERTY_SPECIES_LIST_SEINE_NON_TARGET_CATCH_ID = "speciesListSeineNonTargetCatchId"; + + public static final String PROPERTY_SPECIES_LIST_SEINE_OBJECT_OBSERVED_SPECIES_ID = "speciesListSeineObjectObservedSpeciesId"; + + public static final String PROPERTY_SPECIES_LIST_LONGLINE_CATCH_ID = "speciesListLonglineCatchId"; + + public static final String PROPERTY_SPECIES_LIST_LONGLINE_ENCOUNTER_ID = "speciesListLonglineEncounterId"; + + public static final String PROPERTY_SPECIES_LIST_LONGLINE_DEPREDATOR_ID = "speciesListLonglineDepredatorId"; + + public static final String PROPERTY_VERSION = "version"; + + public static final String PROPERTY_DB_VERSION = "dbVersion"; + + public static final String PROPERTY_AUTO_POPUP_NUMBER_EDITOR = "autoPopupNumberEditor"; + + public static final String PROPERTY_SHOW_NUMBER_EDITOR_BUTTON = "showNumberEditorButton"; + + public static final String PROPERTY_SHOW_DATE_TIME_EDITOR_SLIDER= "showTimeEditorSlider"; + + public static final String PROPERTY_LOCAL_STORAGE_EXIST = "localStorageExist"; + + public static final String PROPERTY_INITIAL_DUMP_EXIST = "initialDumpExist"; + + public static final String PROPERTY_MAIN_STORAGE_OPENED = "mainStorageOpened"; + + public static final String PROPERTY_STORE_REMOTE_STORAGE = "storeRemoteStorage"; + + public static final String PROPERTY_DEFAULT_GPS_MAX_DELAY = "defaultGpsMaxDelay"; + + public static final String PROPERTY_DEFAULT_GPS_MAX_SPEED = "defaultGpsMaxSpeed"; + + public static final String PROPERTY_CHANGE_SYNCHRO_SRC = "changeSynchroSrc"; + + public static final String PROPERTY_NON_TARGET_OBSERVATION = "nonTargetObservation"; + + public static final String PROPERTY_TARGET_DISCARDS_OBSERVATION = "targetDiscardsObservation"; + + public static final String PROPERTY_SAMPLES_OBSERVATION = "samplesObservation"; + + public static final String PROPERTY_OBJECTS_OBSERVATION = "objectsObservation"; + + public static final String PROPERTY_DETAILLED_ACTIVITIES_OBSERVATION = "detailledActivitiesObservation"; + + public static final String PROPERTY_MAMMALS_OBSERVATION = "mammalsObservation"; + + public static final String PROPERTY_BIRDS_OBSERVATION = "birdsObservation"; + + public static final String PROPERTY_BAIT_OBSERVATION = "baitObservation"; + + public static final String PROPERTY_RESOURCES_DIRECTORY = "resourcesDirectory"; + + public static final String PROPERTY_LOCALE = "locale"; + + public static final String PROPERTY_DB_LOCALE = "dbLocale"; + + public static final String PROPERTY_CAN_MIGRATE_OBSTUNA = "canMigrateObstuna"; + + public static final String PROPERTY_CAN_MIGRATE_H2 = "canMigrateH2"; + + public static final String PROPERTY_MAIN_STORAGE_OPENED_LOCAL = "mainStorageOpenedLocal"; + + public static final String PROPERTY_COPYRIGHT_TEXT = "copyrightText"; + + public static final String PROPERTY_FULL_SCREEN = "fullScreen"; + + public static final String PROPERTY_LOCAL_DBDIRECTORY = "localDBDirectory"; + + public static final String PROPERTY_I18N_DIRECTORY = "i18nDirectory"; + + public static final String PROPERTY_INITIAL_DB_DUMP = "initialDbDump"; + + public static final String PROPERTY_BACKUP_DIRECTORY = "backupDirectory"; + + public static final String PROPERTY_REPORT_DIRECTORY = "reportDirectory"; + + public static final String PROPERTY_MAP_DIRECTORY = "mapDirectory"; + + public static final String PROPERTY_TMP_DIRECTORY = "tmpDirectory"; + + public static final String PROPERTY_DISPLAY_MAIN_UI = "displayMainUI"; + + public static final String PROPERTY_CAN_USE_UI = "canUseUI"; + + public static final String PROPERTY_ADJUSTING = "adjusting"; + + public static final String PROPERTY_H2_LOGIN = "h2Login"; + + public static final String PROPERTY_H2_PASSWORD = "h2Password"; + + public static final String PROPERTY_OBSTUNA_URL = "obstunaUrl"; + + public static final String PROPERTY_OBSTUNA_LOGIN = "obstunaLogin"; + + public static final String PROPERTY_OBSTUNA_PASSWORD = "obstunaPassword"; + + public static final String PROPERTY_OBSTUNA_USE_SSL = "obstunaUseSsl"; + + public static final String PROPERTY_LOAD_LOCAL_STORAGE = "loadLocalStorage"; + + public static final String PROPERTY_SHOW_MIGRATION_PROGRESSION = "showMigrationProgression"; + + public static final String PROPERTY_SHOW_MIGRATION_SQL = "showMigrationSql"; + + public static final String PROPERTY_VALIDATION_REPORT_DIRECTORY = "validationReportDirectory"; + + public static final String PROPERTY_SHOW_SQL = "showSql"; + + public static final String PROPERTY_H2_SERVER_PORT = "h2ServerPort"; + + public static final String PROPERTY_DEV_MODE = "devMode"; + + public static final String PROPERTY_TREE_OPEN_NODES = "treeOpenNodes"; + + /** Logger */ + private static final Log log = LogFactory.getLog(ObserveSwingApplicationConfig.class); + + protected static final String DEFAULT_OBSERVE_SWING_CONFIGURATION_FILENAME = "observeSwing.conf"; + + /** + * un drepeau pour savoir s'il faut lancer l'interface graphique. Cette + * valeur peut être programmées lors des actions. + */ + protected boolean displayMainUI = true; + + /** drapeau pour savoir si une base locale existe */ + protected boolean localStorageExist; + + /** + * drapeau pour savoir si le dump initial a ete chargee depuis la base + * centrale + */ + protected boolean initialDumpExist; + + /** drapeau pour savoir si une source de données est ouverte */ + protected boolean mainStorageOpened; + + /** + * drapeau pour savoir si la source ouverte est locale (attention, lorsqu'il + * n'y a pas de storage d'ouvert, la valeur est null). + */ + protected Boolean mainStorageOpenedLocal; + + /** + * drapeau pour savoir si on peut utiliser des ui dans l'environnement. + * + * Par defaut, on suppose qu'on peut utiliser l'environnement graphique et + * si on désactive explicitement ou si pas d'environnement graphique + * trouvé. + */ + protected boolean canUseUI = true; + + /** La version de l'application */ + private Version version; + + /** Texte du copyright (calculé dynamiquement). */ + protected String copyrightText; + + /** + * Liste des options qu'on ne peut pas sauvegarder (les mots de passes, + * les options d'admin pour les simples utilisateurs,...). + * + * @since 1.5 + */ + protected String[] unsavables; + + //FIXME + private final ImmutableSet<String> longlinVesselTypeIds = ImmutableSet.copyOf( + Sets.newHashSet("fr.ird.observe.entities.referentiel.VesselType#1239832675735#0.044156847891821505", + "fr.ird.observe.entities.referentiel.VesselType#1239832675736#0.8708229847859869", + "fr.ird.observe.entities.referentiel.VesselType#1239832686137#0.1")); + + private final ImmutableSet<String> seineVesselTypeIds = ImmutableSet.copyOf( + Sets.newHashSet("fr.ird.observe.entities.referentiel.VesselType#1239832675735#0.044156847891821505", + "fr.ird.observe.entities.referentiel.VesselType#1239832675735#0.307197212385357", + "fr.ird.observe.entities.referentiel.VesselType#1239832675735#0.7380146830307519", + "fr.ird.observe.entities.referentiel.VesselType#1239832675735#0.9086075071905084", + "fr.ird.observe.entities.referentiel.VesselType#1239832675737#0.43324169605639407")); + + public ObserveSwingApplicationConfig() { + this(DEFAULT_OBSERVE_SWING_CONFIGURATION_FILENAME); + } + + public ObserveSwingApplicationConfig(String confFileName) { + setEncoding(Charsets.UTF_8.name()); + setConfigFileName(confFileName); + ApplicationConfigProvider applicationConfigProvider = ApplicationConfigHelper.getProvider(getClass().getClassLoader(), ObserveSwingApplicationConfigProvider.OBSERVE_SWING_CONFIGURATION_PROVIDER_NAME); + loadDefaultOptions(applicationConfigProvider.getOptions()); + } + + public boolean containActions(Step action) { + List<Action> list = actions.get(action.ordinal()); + return !(list == null || list.isEmpty()); + } + + public void initConfig(ObserveResourceManager manager) throws IOException { + + Version version = null; + + Properties p = manager.getResource(Resource.application); + + for (Object k : p.keySet()) { + String key = String.valueOf(k); + Object value = p.get(k); + if (log.isDebugEnabled()) { + log.debug("install property [" + k + "] : " + value); + } + String strValue = String.valueOf(value); + if (APPLICATION_VERSION.equals(key)) { + version = Versions.valueOf(strValue); + if (version.isSnapshot()) { + version = Versions.removeSnapshot(version); + } + + } else { + setDefaultOption(key, strValue); + } + } + + if (version == null) { + throw new IllegalStateException("No application.version found in application configuration."); + } + + setVersion(version); + setDefaultOption(VERSION, version.getVersion()); + setDefaultOption(APPLICATION_VERSION, version.getVersion()); + + // creation des actions disponibles + for (ObserveCLAction.ActionDefinition a : ObserveCLAction.ActionDefinition.values()) { + + for (String alias : a.aliases) { + addActionAlias(alias, a.action); + } + } + + } + + @Override + protected void migrateUserConfigurationFile(File oldHomeConfig, + File homeConfig) throws IOException { + super.migrateUserConfigurationFile(oldHomeConfig, homeConfig); + // on previent l'utilisateur que son fichier de configuration a été + // deplacé + JOptionPane.showInternalMessageDialog(null, + t("observe.title.config.migrate"), + t("observe.runner.config.migrate.file", + oldHomeConfig.getName(), + oldHomeConfig, + homeConfig + ), + JOptionPane.WARNING_MESSAGE); + } + + public void installSaveAction() { + // ajout de l'action de sauvegarde automatique sur certaines propriétés + + List<String> result = new ArrayList<>(); + + for (ObserveSwingApplicationConfigOption option : ObserveSwingApplicationConfigOption.values()) { + String key = option.getPropertyKey(); + if (key != null) { + // add a listener + if (log.isDebugEnabled()) { + log.debug("register action listener for property " + key); + } + result.add(key); + } + } + + installSaveUserAction(result.toArray(new String[result.size()])); + } + + public String getCopyrightText() { + if (copyrightText == null) { + Date date = new Date(); + Calendar calendar = Calendar.getInstance(); + calendar.setTime(date); + int year = calendar.get(Calendar.YEAR); + copyrightText = "Version " + getVersion() + " IRD @ 2008-" + year; + } + return copyrightText; + } + + public boolean isDevMode() { + boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.DEV_MODE.key); + return result; + } + + public Version getVersion() { + return version; + } + + public Version getModelVersion() { + Version result = getOption(Version.class, ObserveSwingApplicationConfigOption.MODEL_VERSION.key); + return result; + } + + public boolean isAutoPopupNumberEditor() { + boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.AUTO_POPUP_NUMBER_EDITOR.key); + return result; + } + + public boolean isShowNumberEditorButton() { + boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.SHOW_NUMBER_EDITOR_BUTTON.key); + return result; + } + + public boolean isShowTimeEditorSlider() { + boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.SHOW_DATE_TIME_EDITOR_SLIDER.key); + return result; + } + + public boolean isFullScreen() { + boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.FULL_SCREEN.key); + return result; + } + + public File getDataDirectory() { + File file = getOptionAsFile(ObserveSwingApplicationConfigOption.DATA_DIRECTORY.key); + return file; + } + + public File getValidationReportDirectory() { + File file = getOptionAsFile(ObserveSwingApplicationConfigOption.VALIDATION_REPORT_DIRECTORY.key); + return file; + } + + public File getLocalDBDirectory() { + File result = getOptionAsFile(ObserveSwingApplicationConfigOption.DB_DIRECTORY.key); + return result; + } + + public File getResourcesDirectory() { + File result = getOptionAsFile(ObserveSwingApplicationConfigOption.RESOURCES_DIRECTORY.key); + return result; + } + + public File getI18nDirectory() { + File result = getOptionAsFile(ObserveSwingApplicationConfigOption.I18N_DIRECTORY.key); + return result; + } + + public void setResourcesDirectory(File newValue) { + setOption(ObserveSwingApplicationConfigOption.RESOURCES_DIRECTORY, newValue); + } + + public File getInitialDbDump() { + File result = getOptionAsFile(ObserveSwingApplicationConfigOption.INITIAL_DB_DUMP.key); + return result; + } + + public File getBackupDirectory() { + File result = getOptionAsFile(ObserveSwingApplicationConfigOption.BACKUP_DIRECTORY.key); + return result; + } + + public File getReportDirectory() { + File result = getOptionAsFile(ObserveSwingApplicationConfigOption.REPORT_DIRECTORY.key); + return result; + } + + public File getTmpDirectory() { + File result = getOptionAsFile(ObserveSwingApplicationConfigOption.TMP_DIRECTORY.key); + return result; + } + + public File getLogConfigurationFile() { + File result = getOptionAsFile(ObserveSwingApplicationConfigOption.LOG_CONFIGURATION_FILE.key); + return result; + } + + public String getH2Login() { + String result = getOption(ObserveSwingApplicationConfigOption.H2_LOGIN.key); + return result; + } + + public char[] getH2Password() { + String result = getOption(ObserveSwingApplicationConfigOption.H2_PASSWORD.key); + char[] r = result.toCharArray(); + return r; + } + + public int getH2ServerPort() { + Integer port = getOptionAsInt(ObserveSwingApplicationConfigOption.H2_SERVER_PORT.key); + return port; + } + + public String getObstunaUrl() { + String result = getOption(ObserveSwingApplicationConfigOption.OBSTUNA_URL.key); + return result; + } + + public void setObstunaUrl(String jdbcUrl) { + setOption(ObserveSwingApplicationConfigOption.OBSTUNA_URL.key, jdbcUrl); + } + + public String getObstunaLogin() { + String result = getOption(ObserveSwingApplicationConfigOption.OBSTUNA_LOGIN.key); + return result; + } + + public void setObstunaLogin(String login) { + setOption(ObserveSwingApplicationConfigOption.OBSTUNA_LOGIN.key, login); + } + + public char[] getObstunaPassword() { + String result = getOption(ObserveSwingApplicationConfigOption.OBSTUNA_PASSWORD.key); + char[] r = result.toCharArray(); + return r; + } + + public void setObstunaPassword(char[] password) { + setOption(ObserveSwingApplicationConfigOption.OBSTUNA_PASSWORD.key, new String(password)); + } + + public boolean isObstunaUseSsl() { + boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.OBSTUNA_USE_SSL_CERT.key); + return result; + } + + public void setObstunaUseSsl(boolean useSsl) { + setOption(ObserveSwingApplicationConfigOption.OBSTUNA_USE_SSL_CERT, useSsl); + } + + public URL getServerUrl() { + URL result = (URL) getOption(ObserveSwingApplicationConfigOption.SERVER_URL); + return result; + } + + public void setServerUrl(URL serverUrl) { + setOption(ObserveSwingApplicationConfigOption.SERVER_URL, serverUrl); + } + + public String getServerLogin() { + String result = getOption(ObserveSwingApplicationConfigOption.SERVER_LOGIN.key); + return result; + } + + public void setServerLogin(String serverLoginl) { + setOption(ObserveSwingApplicationConfigOption.SERVER_LOGIN.key, serverLoginl); + } + + public char[] getServerPassword() { + String result = getOption(ObserveSwingApplicationConfigOption.SERVER_PASSWORD.key); + char[] r = result.toCharArray(); + return r; + } + + public void setServerPassword(char[] password) { + setOption(ObserveSwingApplicationConfigOption.SERVER_PASSWORD.key, new String(password)); + } + + public String getServerDataBaseName() { + String result = getOption(ObserveSwingApplicationConfigOption.SERVER_DATABASE_NAME.key); + return result; + } + + public void setServerDataBaseName(String dataBaseName) { + setOption(ObserveSwingApplicationConfigOption.SERVER_DATABASE_NAME.key, dataBaseName); + } + + public DbMode getDefaultDbMode() { + DbMode result = getOption(DbMode.class, ObserveSwingApplicationConfigOption.DEFAULT_DB_MODE.key); + return result; + } + + public CreationMode getDefaultCreationMode() { + CreationMode result = + getOption(CreationMode.class, ObserveSwingApplicationConfigOption.DEFAULT_CREATION_MODE.key); + return result; + } + + public boolean isShowMigrationSql() { + boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.SHOW_MIGRATION_SQL.key); + return result; + } + + public boolean isShowMigrationProgression() { + boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.SHOW_MIGRATION_PROGRESSION.key); + return result; + } + + public boolean isShowSql() { + boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.SHOW_SQL.key); + return result; + } + + public int getDefaultGpsMaxDelay() { + Integer i = getOptionAsInt(ObserveSwingApplicationConfigOption.DEFAULT_GPS_MAX_DELAY.key); + return i; + } + + public float getDefaultGpsMaxSpeed() { + double i = getOptionAsDouble(ObserveSwingApplicationConfigOption.DEFAULT_GPS_MAX_SPEED.key); + return (float) i; + } + + public boolean isChangeSynchroSrc() { + boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.CHANGE_SYNCHRO_SRC.key); + return result; + } + + public boolean isStoreRemoteStorage() { + boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.STORE_REMOTE_STORAGE.key); + return result; + } + + public boolean isCanMigrateObstuna() { + boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.OBSTUNA_CAN_MIGRATE.key); + return result; + } + + public boolean isCanMigrateH2() { + boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.H2_CAN_MIGRATE.key); + return result; + } + + public boolean isLoadLocalStorage() { + boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.LOAD_LOCAL_STORAGE.key); + return result; + } + + public Locale getLocale() { + Locale result = getOption(Locale.class, ObserveSwingApplicationConfigOption.LOCALE.key); + return result; + } + + public Locale getDbLocale() { + Locale result = getOption(Locale.class, ObserveSwingApplicationConfigOption.DB_LOCALE.key); + return result; + } + + public int getNonTargetObservation() { + int value = getOptionAsInt(ObserveSwingApplicationConfigOption.NON_TARGET_OBSERVATION.key); + return value; + } + + public int getTargetDiscardsObservation() { + int value = getOptionAsInt(ObserveSwingApplicationConfigOption.TARGET_DISCARDS_OBSERVATION.key); + return value; + } + + public int getSamplesObservation() { + int value = getOptionAsInt(ObserveSwingApplicationConfigOption.SAMPLES_OBSERVATION.key); + return value; + } + + public int getObjectsObservation() { + int value = getOptionAsInt(ObserveSwingApplicationConfigOption.OBJECTS_OBSERVATION.key); + return value; + } + + public int getDetailledActivitiesObservation() { + int value = getOptionAsInt(ObserveSwingApplicationConfigOption.DETAILLED_ACTIVITIES_OBSERVATION.key); + return value; + } + + public int getMammalsObservation() { + int value = getOptionAsInt(ObserveSwingApplicationConfigOption.MAMMALS_OBSERVATION.key); + return value; + } + + public int getBirdsObservation() { + int value = getOptionAsInt(ObserveSwingApplicationConfigOption.BIRDS_OBSERVATION.key); + return value; + } + + public int getBaitObservation() { + int value = getOptionAsInt(ObserveSwingApplicationConfigOption.BAIT_OBSERVATION.key); + return value; + } + + public boolean isDisplayMainUI() { + return displayMainUI; + } + + public boolean isCanUseUI() { + return canUseUI; + } + + public boolean isLocalStorageExist() { + return localStorageExist; + } + + public boolean isInitialDumpExist() { + return initialDumpExist; + } + + public boolean isMainStorageOpened() { + return mainStorageOpened; + } + + public Boolean getMainStorageOpenedLocal() { + return mainStorageOpenedLocal; + } + + public void setLocalStorageExist(boolean newValue) { + localStorageExist = newValue; + // always force propagation + firePropertyChange(PROPERTY_LOCAL_STORAGE_EXIST, newValue); + } + + public void setInitialDumpExist(boolean newValue) { + initialDumpExist = newValue; + // always force propagation + firePropertyChange(PROPERTY_INITIAL_DUMP_EXIST, newValue); + } + + public void setMainStorageOpened(boolean newValue) { + mainStorageOpened = newValue; + if (!newValue) { + // on force la reinitialisation + setMainStorageOpenedLocal(null); + } + // always force propagation + firePropertyChange(PROPERTY_MAIN_STORAGE_OPENED, newValue); + } + + public void setMainStorageOpenedLocal(Boolean newValue) { + mainStorageOpenedLocal = newValue; + // always force propagation + firePropertyChange(PROPERTY_MAIN_STORAGE_OPENED + "Local", newValue); + } + + public void setDisplayMainUI(boolean b) { + displayMainUI = b; + } + + public void setCanUseUI(boolean canUseUI) { + this.canUseUI = canUseUI; + if (!canUseUI) { + // on ne pourra pas lancer l'ui principale + setDisplayMainUI(false); + } + } + + public void setAutoPopupNumberEditor(boolean newValue) { + setOption(ObserveSwingApplicationConfigOption.AUTO_POPUP_NUMBER_EDITOR, newValue); + } + + public void setShowNumberEditorButton(boolean newValue) { + setOption(ObserveSwingApplicationConfigOption.SHOW_NUMBER_EDITOR_BUTTON, newValue); + } + + public void setShowTimeEditorSlider(boolean newValue) { + setOption(ObserveSwingApplicationConfigOption.SHOW_DATE_TIME_EDITOR_SLIDER, newValue); + } + + public void setFullScreen(boolean newValue) { + setOption(ObserveSwingApplicationConfigOption.FULL_SCREEN, newValue); + } + + public void setChangeSynchroSrc(boolean newValue) { + setOption(ObserveSwingApplicationConfigOption.CHANGE_SYNCHRO_SRC, newValue); + } + + public void setStoreRemoteStorage(boolean newValue) { + setOption(ObserveSwingApplicationConfigOption.STORE_REMOTE_STORAGE, newValue); + } + + public void setLoadLocalStorage(boolean newValue) { + setOption(ObserveSwingApplicationConfigOption.LOAD_LOCAL_STORAGE, newValue); + } + + public void setDefaultDbMode(DbMode newValue) { + setOption(ObserveSwingApplicationConfigOption.DEFAULT_DB_MODE, newValue); + } + + public void setDefaultCreationMode(CreationMode newValue) { + setOption(ObserveSwingApplicationConfigOption.DEFAULT_CREATION_MODE, newValue); + } + + public void setDefaultGpsMaxDelay(int newValue) { + setOption(ObserveSwingApplicationConfigOption.DEFAULT_GPS_MAX_DELAY, newValue); + } + + public void setDefaultGpsMaxSpeed(float newValue) { + setOption(ObserveSwingApplicationConfigOption.DEFAULT_GPS_MAX_SPEED, newValue); + } + + public void setLocale(Locale newValue) { + setOption(ObserveSwingApplicationConfigOption.LOCALE, newValue); + } + + public void setDbLocale(Locale newValue) { + setOption(ObserveSwingApplicationConfigOption.DB_LOCALE, newValue); + } + + public void setCanMigrateObstuna(Boolean newValue) { + setOption(ObserveSwingApplicationConfigOption.OBSTUNA_CAN_MIGRATE, newValue); + } + + public void setCanMigrateH2(Boolean newValue) { + setOption(ObserveSwingApplicationConfigOption.H2_CAN_MIGRATE, newValue); + } + + public void setNonTargetObservation(int newValue) { + setOption(ObserveSwingApplicationConfigOption.NON_TARGET_OBSERVATION, newValue); + } + + public void setTargetDiscardsObservation(int newValue) { + setOption(ObserveSwingApplicationConfigOption.TARGET_DISCARDS_OBSERVATION, newValue); + } + + public void setSamplesObservation(int newValue) { + setOption(ObserveSwingApplicationConfigOption.SAMPLES_OBSERVATION, newValue); + } + + public void setObjectsObservation(int newValue) { + setOption(ObserveSwingApplicationConfigOption.OBJECTS_OBSERVATION, newValue); + } + + public void setDetailledActivitiesObservation(int newValue) { + setOption(ObserveSwingApplicationConfigOption.DETAILLED_ACTIVITIES_OBSERVATION, newValue); + } + + public void setMammalsObservation(int newValue) { + setOption(ObserveSwingApplicationConfigOption.MAMMALS_OBSERVATION, newValue); + } + + public void setBirdsObservation(int newValue) { + setOption(ObserveSwingApplicationConfigOption.BIRDS_OBSERVATION, newValue); + } + + public void setBaitObservation(int newValue) { + setOption(ObserveSwingApplicationConfigOption.BAIT_OBSERVATION, newValue); + } + + public void setShowMigrationSql(boolean showMigrationSql) { + setOption(ObserveSwingApplicationConfigOption.SHOW_MIGRATION_SQL, showMigrationSql); + } + + public void setShowMigrationProgression(boolean showMigrationProgression) { + setOption(ObserveSwingApplicationConfigOption.SHOW_MIGRATION_PROGRESSION, showMigrationProgression); + } + + public void setShowSql(boolean showSql) { + setOption(ObserveSwingApplicationConfigOption.SHOW_SQL, showSql); + } + + public String getSpeciesListSeineNonTargetCatchId() { + String value = getOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_NON_TARGET_CATCH_ID.key); + return value; + } + + public String getSpeciesListSeineTargetCatchId() { + String value = getOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_TARGET_CATCH_ID.key); + return value; + } + + public String getSpeciesListSeineSchoolEstimateId() { + String value = getOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_SCHOOL_ESTIMATE_ID.key); + return value; + } + + public String getSpeciesListSeineObjectObservedSpeciesId() { + String value = getOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_OBJECT_OBSERVED_SPECIES_ID.key); + return value; + } + + public String getSpeciesListSeineObjectSchoolEstimateId() { + String value = getOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_OBJECT_SCHOOL_ESTIMATE_ID.key); + return value; + } + + public String getSpeciesListLonglineCatchId() { + String value = getOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_LONGLINE_CATCH_ID.key); + return value; + } + + public String getSpeciesListLonglineEncounterId() { + String value = getOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_LONGLINE_ENCOUNTER_ID.key); + return value; + } + + public String getSpeciesListLonglineDepredatorId() { + String value = getOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_LONGLINE_DEPREDATOR_ID.key); + return value; + } + + public void setSpeciesListSeineNonTargetCatchId(String speciesListSeineNonTargetCatchId) { + setOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_NON_TARGET_CATCH_ID, speciesListSeineNonTargetCatchId); + } + + public void setSpeciesListSeineTargetCatchId(String speciesListSeineTargetCatchId) { + setOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_TARGET_CATCH_ID, speciesListSeineTargetCatchId); + } + + public void setSpeciesListSeineSchoolEstimateId(String speciesListSeineSchoolEstimateId) { + setOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_SCHOOL_ESTIMATE_ID, speciesListSeineSchoolEstimateId); + } + + public void setSpeciesListSeineObjectObservedSpeciesId(String speciesListSeineObjectObservedSpeciesId) { + setOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_OBJECT_OBSERVED_SPECIES_ID, speciesListSeineObjectObservedSpeciesId); + } + + public void setSpeciesListSeineObjectSchoolEstimateId(String speciesListseineObjectSchoolEstimateId) { + setOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_OBJECT_SCHOOL_ESTIMATE_ID, speciesListseineObjectSchoolEstimateId); + } + + public void setSpeciesListLonglineCatchId(String speciesListLonglineCatchId) { + setOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_LONGLINE_CATCH_ID, speciesListLonglineCatchId); + } + + public void setSpeciesListLonglineEncounterId(String speciesListLonglineEncounterId) { + setOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_LONGLINE_ENCOUNTER_ID, speciesListLonglineEncounterId); + } + + public void setSpeciesListLonglineDepredatorId(String speciesListLonglineDepredatorId) { + setOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_LONGLINE_DEPREDATOR_ID, speciesListLonglineDepredatorId); + } + + public Color getMapBackgroundColor() { + Color result = getOptionAsColor(ObserveSwingApplicationConfigOption.MAP_BACKGROUND_COLOR.key); + return result; + } + + public List<File> getMapLayerFiles() { + List<File> layers = Lists.newLinkedList(); + + for (ObserveSwingApplicationConfigOption layerOption : ObserveSwingApplicationConfigOption.MAP_LAYERS) { + File layerFile = getOptionAsFile(layerOption.key); + if (layerFile != null && layerFile.exists()) { + layers.add(layerFile); + } + } + return layers; + } + + public File getMapStyleFile() { + File result = getOptionAsFile(ObserveSwingApplicationConfigOption.MAP_STYLE_FILE.key); + return result; + } + + public String[] getTreeOpenNodeIds() { + String ids = getOption(ObserveSwingApplicationConfigOption.TREE_OPEN_NODES.key); + String[] result = null; + if (ids != null) { + result = ids.split(","); + } + return result; + } + + public void setTreeOpenNodeIds(String[] ids) { + String joinIds = StringUtils.join(ids, ","); + setOption(ObserveSwingApplicationConfigOption.TREE_OPEN_NODES, joinIds); + } + + public String[] getUnsavables() { + if (unsavables == null) { + List<String> tmp = new ArrayList<>(); + tmp.add(ObserveSwingApplicationConfigOption.OBSTUNA_PASSWORD.getKey()); +// tmp.add(OBSTUNA_SSL_CERTIFICAT_PASSWORD.getKey()); + tmp.add(ObserveSwingApplicationConfigOption.H2_PASSWORD.getKey()); + tmp.add(ObserveSwingApplicationConfigOption.OBSTUNA_CAN_MIGRATE.getKey()); + +// if (!ObserveRunner.isAdmin()) { +// // toutes les options dite admin ne sont pas sauvables +// +// for (ObserveSwingApplicationConfigOption option : values()) { +// if (option.isAdmin()) { +// +// // ne pas ajouter les options d'admin pour le simple utilisateur +// tmp.add(option.key); +// } +// } +// } + unsavables = tmp.toArray(new String[tmp.size()]); + } + return unsavables; + } + + public void saveForUser(String... excludeKeys) { + if (log.isInfoEnabled()) { + log.info(t("observe.message.save.configuration", getUserConfigFile())); + } + super.saveForUser(getUnsavables()); + } + + + public void fromStorageConfig(ObserveDataSourceConfigurationTopiaH2 config) { + setShowMigrationProgression(config.isShowMigrationProgression()); + setShowMigrationSql(config.isShowMigrationSql()); + saveForUser(); + } + + public void fromStorageConfig(ObserveDataSourceConfigurationTopiaPG config) { + setObstunaUrl(config.getJdbcUrl()); + setObstunaLogin(config.getUsername()); + setObstunaPassword(config.getPassword()); + setObstunaUseSsl(config.isUseSsl()); +// if (useSsl) { +// setOption(OBSTUNA_SSL_CERTIFICAT_FILE, +// config.getSslCertificatFile().getAbsolutePath()); +// setOption(OBSTUNA_SSL_CERTIFICAT_PASSWORD, +// new String(config.getSslCertificatPassword())); +// } else { +// setOption(OBSTUNA_SSL_CERTIFICAT_FILE.key, ""); +// setOption(OBSTUNA_SSL_CERTIFICAT_PASSWORD, EMPTY_CHAR_ARRAY); +// } + setShowMigrationProgression(config.isShowMigrationProgression()); + setShowMigrationSql(config.isShowMigrationSql()); + //TODO-TC20100311 : on devrait pas regarder si l'utilisateur veut sauver + //TODO-TC20100311 : la configuration ? + saveForUser(); + } + + public void fromStorageConfig(ObserveDataSourceConfigurationRest config) { + setServerUrl(config.getServerUrl()); + setServerLogin(config.getLogin()); + setServerPassword(config.getPassword()); + setServerDataBaseName(config.getOptionalDatabaseName().orElse(null)); + saveForUser(); + } + + + public ObserveDataSourceConfigurationTopiaH2 getDataSourceConfigurationH2(String label) { + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ObserveDataSourceConfigurationMainFactory configurationMainFactory = applicationContext.getObserveDataSourceConfigurationMainFactory(); + + File dbDirectory = new File(getLocalDBDirectory(), DB_NAME); + + ObserveDataSourceConfigurationTopiaH2 result = configurationMainFactory.createObserveDataSourceConfigurationTopiaH2( + label, + dbDirectory, + DB_NAME, + getH2Login(), + getH2Password(), + isShowMigrationProgression(), + isShowMigrationSql(), + getModelVersion() + ); + return result; + } + + public ObserveDataSourceConfigurationTopiaPG getDataSourceConfigurationPG(String label) { + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ObserveDataSourceConfigurationMainFactory configurationMainFactory = applicationContext.getObserveDataSourceConfigurationMainFactory(); + + ObserveDataSourceConfigurationTopiaPG result = configurationMainFactory.createObserveDataSourceConfigurationTopiaPG( + label, + getObstunaUrl(), + getObstunaLogin(), + getObstunaPassword(), + isObstunaUseSsl(), + isShowMigrationProgression(), + isShowMigrationSql(), + getModelVersion() + ); + return result; + } + + public ObserveDataSourceConfigurationRest getDataSourceConfigurationRest(String label) { + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ObserveDataSourceConfigurationMainFactory configurationMainFactory = applicationContext.getObserveDataSourceConfigurationMainFactory(); + + ObserveDataSourceConfigurationRest result = configurationMainFactory.createObserveDataSourceConfigurationRest( + label, + getServerUrl(), + getServerLogin(), + getServerPassword(), + getServerDataBaseName(), + getModelVersion() + ); + return result; + } + + public void removeJaxxPropertyChangeListener() { + List<String> tmp = new ArrayList<>(); + for (ObserveSwingApplicationConfigOption option : ObserveSwingApplicationConfigOption.values()) { + String propertyName = option.getPropertyKey(); + if (propertyName != null) { + tmp.add(propertyName); + } + } + if (log.isDebugEnabled()) { + log.debug("property names to seek for options : " + tmp); + } + String[] propertyNames = tmp.toArray( + new String[tmp.size()]); + + PropertyChangeListener[] toRemove = + UIHelper.findJaxxPropertyChangeListener( + propertyNames, + getPropertyChangeListeners()); + if (toRemove == null || toRemove.length == 0) { + return; + } + if (log.isDebugEnabled()) { + log.debug("before remove : " + getPropertyChangeListeners().length); + log.debug("toRemove : " + toRemove.length); + } + for (PropertyChangeListener listener : toRemove) { + removePropertyChangeListener(listener); + } + if (log.isDebugEnabled()) { + log.debug("after remove : " + getPropertyChangeListeners().length); + } + } + + public void setOption(ObserveSwingApplicationConfigOption option, Object newValue) { + String key = option.getKey(); + Object oldValue = getOption(key); + String value = String.valueOf(newValue); + setOption(key, value); + if (log.isDebugEnabled()) { + log.debug("set option " + key + " value : " + value); + } + String propertyName = option.getPropertyKey(); + if (propertyName != null) { + // l'option est javabeans, declanchement d'un changement + if (log.isTraceEnabled()) { + log.trace("fires config change from option " + key); + } + firePropertyChange(propertyName, oldValue, newValue); + } + } + + void setVersion(Version version) { + this.version = version; + } + + public Set<String> getSeineVesselTypeIds() { + return seineVesselTypeIds; + } + + public Set<String> getLonglineVesselTypeIds() { + return longlinVesselTypeIds; + } + + public String replaceRecursiveOptions(String option) { + return super.replaceRecursiveOptions(option); + } + + public String getConfigurationDescription() { + StringBuilder builder = new StringBuilder(); + builder.append("\n====================================================================================================================="); + builder.append("\n=== Observe Swing configuration ====================================================================================="); + builder.append(String.format("\n=== %1$-40s = %2$s", "Filename", getConfigFileName())); + for (ObserveSwingApplicationConfigOption option : ObserveSwingApplicationConfigOption.orderedByNameValues()) { + builder.append(String.format("\n=== %1$-40s = %2$s", option.getKey(), getOption(option))); + } + builder.append("\n====================================================================================================================="); + return builder.toString(); + } + + ////////////////////////////////////////////////// + // Toutes les étapes d'actions + ////////////////////////////////////////////////// + + public enum Step { + + AfterInit, BeforeExit + } + + protected void firePropertyChange(String propertyName, Object newValue) { + pcs.firePropertyChange(propertyName, null, newValue); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/configuration/ObserveSwingApplicationConfigOption.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/configuration/ObserveSwingApplicationConfigOption.java new file mode 100644 index 0000000..13339ca --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/configuration/ObserveSwingApplicationConfigOption.java @@ -0,0 +1,943 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.configuration; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; +import fr.ird.observe.application.swing.db.constants.CreationMode; +import fr.ird.observe.application.swing.db.constants.DbMode; +import fr.ird.observe.services.ObserveSpeciesListConfiguration; +import org.nuiton.config.ApplicationConfig; +import org.nuiton.config.ConfigOptionDef; +import org.nuiton.version.Version; + +import java.awt.Color; +import java.io.File; +import java.net.URL; +import java.util.Collections; +import java.util.List; +import java.util.Locale; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Les options disponibles dans l'application, modifiables via la ligne de + * commande, ou le fichier utilisateur. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.2 + */ +public enum ObserveSwingApplicationConfigOption implements ConfigOptionDef { + + /** le lastName du fichier de configuration (sans le prefix .) */ + CONFIG_FILE( + ApplicationConfig.CONFIG_FILE_NAME, + n("observe.config.configFileName.description"), + ObserveSwingApplicationConfig.DEFAULT_OBSERVE_SWING_CONFIGURATION_FILENAME, + String.class, + true, + true + ), + + /** flag pour afficher automatiquement la popup du clavier numerique */ + DEV_MODE( + "observe." + ObserveSwingApplicationConfig.PROPERTY_DEV_MODE, + n("observe.config.devMode"), + "true", + Boolean.class, + true, + true + ), + + /** version du modèle de données */ + MODEL_VERSION( + "observe.model.version", + n("observe.model.version"), + null, + Version.class, + true, + true + ), + + // directories + + /** le repertoire ou est stoquee la base locale */ + DATA_DIRECTORY( + "data.directory", + n("observe.config.defaultDataDirectory.description"), + "${user.home}/.observe", + File.class, + false, + false + ), + + /** le repertoire ou est stoquee la base locale */ + DB_DIRECTORY( + "db.directory", + n("observe.config.defaultLocalDbDirectory.description"), + "${data.directory}/db", + File.class, + false, + false + ), + + /** + * le lastName de la base initiale recuperee lors de la premiere connexion + * a Obstuna. + */ + INITIAL_DB_DUMP( + "initial.db.dump", + n("observe.config.defaultInitialDbDump.description"), + "${data.directory}/initial-database.sql.gz", + File.class, + false, + false + ), + + /** le repertoire ou effectuer les sauvegarde */ + BACKUP_DIRECTORY( + "backup.directory", + n("observe.config.defaultBackupDirectory.description"), + "${data.directory}/backup", + File.class, + false, + false + ), + + /** le repertoire ou sont stockees toutes les ressources de l'utilisateur */ + RESOURCES_DIRECTORY( + "resources.directory", + ObserveSwingApplicationConfig.PROPERTY_RESOURCES_DIRECTORY, + n("observe.config.defaultResourcesDirectory.description"), + "${data.directory}/resources-${version}", + File.class, + false, + false + ), + + /** le repertoire ou sont stockees les traduction i18n de l'utilisateur */ + I18N_DIRECTORY( + "i18n.directory", + ObserveSwingApplicationConfig.PROPERTY_I18N_DIRECTORY, + n("observe.config.defaultI18nDirectory.description"), + "${resources.directory}/i18n", + File.class, + false, + false + ), + + /** le repertoire ou sont stockees les reports de l'utilisateur */ + REPORT_DIRECTORY( + "report.directory", + ObserveSwingApplicationConfig.PROPERTY_REPORT_DIRECTORY, + n("observe.config.defaultReportDirectory.description"), + "${resources.directory}/report", + File.class, + false, + false + ), + + /** le repertoire ou sont stockees les cartes de l'utilisateur */ + MAP_DIRECTORY( + "map.directory", + ObserveSwingApplicationConfig.PROPERTY_MAP_DIRECTORY, + n("observe.config.defaultMapDirectory.description"), + "${resources.directory}/map", + File.class, + false, + false + ), + + /** le repertoire ou sont stockees les reports de validation de l'utilisateur */ + VALIDATION_REPORT_DIRECTORY( + "validation.report.directory", + ObserveSwingApplicationConfig.PROPERTY_VALIDATION_REPORT_DIRECTORY, + n("observe.config.defaultValidationReportDirectory.description"), + "${data.directory}/validation-report", + File.class, + false, + false + ), + + /** le repertoire temporaire (utilise pour les base de synchro) */ + TMP_DIRECTORY( + "tmp.directory", + n("observe.config.defaultTmpDirectory.description"), + "${data.directory}/tmp", + File.class, + false, + false + ), + + /** Le chemin du fichier de configuration des logs. */ + LOG_CONFIGURATION_FILE( + "logConfigurationFile", + n("observe.config.logConfigurationFile.description"), + "${resources.directory}/observe-log4j.properties", + String.class, + true, + false), + + // local db config + + /** login sur toutes les bases h2 (non sauvegarde) */ + H2_LOGIN( + "h2.username", + n("observe.config.h2.login.description"), + "sa", + String.class, + true, + true + ), + + /** mot de passe sur toutes les bases h2 (non sauvegarde) */ + H2_PASSWORD( + "h2.password", + n("observe.config.h2.password.description"), + "sa", + String.class, + true, + true + ), + + /** flag pour effectuer la mise a jour des bases locales */ + H2_CAN_MIGRATE( + "h2.canMigrate", + n("observe.config.h2.can.migrate.description"), + "true", + Boolean.class, + false, + false + ), + + + /** port à utiliser pour lancer ObServe en mode serveur */ + H2_SERVER_PORT( + "h2.serverPort", + n("observe.config.h2.serverPort.description"), + "9093", + Integer.class, + false, + false + ), + + // obstuna db config + + /** url de la base obstuna */ + OBSTUNA_URL( + "obstuna.url", + n("observe.config.obstuna.url.description"), + "jdbc:postgresql:///obstuna", + String.class, + false, + false + ), + + /** login de la base obstuna */ + OBSTUNA_LOGIN( + "obstuna.username", + n("observe.config.obstuna.login.description"), + "utilisateur", + String.class, + false, + false + ), + + /** mot de passe de la base obstuna (non sauvegarde) */ + OBSTUNA_PASSWORD( + "obstuna.password", + n("observe.config.obstuna.password.description"), + "", + String.class, + true, + false + ), + + /** flag pour activer l'utilisation ssl pour la connexion a obstuna */ + OBSTUNA_USE_SSL_CERT( + "obstuna.useSsl", + n("observe.config.obstuna.useSsl.description"), + "false", + Boolean.class, + false, + false + ), + + /** flag pour mettre a jour obstuna */ + OBSTUNA_CAN_MIGRATE( + "pg.canMigrate", + n("observe.config.pg.can.migrate.description"), + "false", + Boolean.class, + false, + false + ), + + // Rest server config + + /** url du serveur restflag pour mettre a jour obstuna */ + SERVER_URL( + "server.url", + n("observe.config.server.url.description"), + null, + URL.class, + false, + false + ), + + /** url du serveur restflag pour mettre a jour obstuna */ + SERVER_LOGIN( + "server.login", + n("observe.config.server.login.description"), + "", + String.class, + false, + false + ), + + /** url du serveur restflag pour mettre a jour obstuna */ + SERVER_PASSWORD( + "server.password", + n("observe.config.server.password.description"), + "", + String.class, + false, + false + ), + + /** url du serveur restflag pour mettre a jour obstuna */ + SERVER_DATABASE_NAME( + "server.dataBaseName", + n("observe.config.server.dataBaseName.description"), + null, + String.class, + false, + false + ), + + // change storage options + + /** le mode de connexion par defaut */ + DEFAULT_DB_MODE( + ObserveSwingApplicationConfig.PROPERTY_DEFAULT_DB_MODE, + ObserveSwingApplicationConfig.PROPERTY_DEFAULT_DB_MODE, + n("observe.config.defaultDbMode"), + DbMode.USE_LOCAL.name(), + DbMode.class, + false, + false + ), + + /** le mode de creation par defaut de base locale */ + DEFAULT_CREATION_MODE( + ObserveSwingApplicationConfig.PROPERTY_DEFAULT_CREATION_MODE, + ObserveSwingApplicationConfig.PROPERTY_DEFAULT_CREATION_MODE, + n("observe.config.defaultCreationMode"), + CreationMode.IMPORT_EXTERNAL_DUMP.name(), + CreationMode.class, + false, + false + ), + + /** flag pour sauvegarder le paramétrage de la connexion a obstuna */ + STORE_REMOTE_STORAGE( + "ui." + ObserveSwingApplicationConfig.PROPERTY_STORE_REMOTE_STORAGE, + ObserveSwingApplicationConfig.PROPERTY_STORE_REMOTE_STORAGE, + n("observe.config.ui.storeRemoteStorage"), + "true", + Boolean.class, + false, + false + ), + + /** flag pour charge ou non la base locale au démarrage */ + LOAD_LOCAL_STORAGE( + "ui." + ObserveSwingApplicationConfig.PROPERTY_LOAD_LOCAL_STORAGE, + ObserveSwingApplicationConfig.PROPERTY_LOAD_LOCAL_STORAGE, + n("observe.config.ui.loadLocalStorage"), + "true", + Boolean.class, + false, + false + ), + + /** pour afficher la progression de la migration dans les logs */ + SHOW_MIGRATION_PROGRESSION( + ObserveSwingApplicationConfig.PROPERTY_SHOW_MIGRATION_PROGRESSION, + ObserveSwingApplicationConfig.PROPERTY_SHOW_MIGRATION_PROGRESSION, + n("observe.config.showMigrationProgression"), + "true", + Boolean.class, + false, + false + ), + + /** pour affichier les requetes sql lors de la migration dans les logs */ + SHOW_MIGRATION_SQL( + ObserveSwingApplicationConfig.PROPERTY_SHOW_MIGRATION_SQL, + ObserveSwingApplicationConfig.PROPERTY_SHOW_MIGRATION_SQL, + n("observe.config.showMigrationSql"), + "true", + Boolean.class, + false, + false + ), + /** pour affichier toutes les requetes sql dans les logs */ + SHOW_SQL( + ObserveSwingApplicationConfig.PROPERTY_SHOW_SQL, + ObserveSwingApplicationConfig.PROPERTY_SHOW_SQL, + n("observe.config.showSql"), + "false", + Boolean.class, + false, + false + ), + // gps default values + + /** temps maximum autorise en deux points gps */ + DEFAULT_GPS_MAX_DELAY( + ObserveSwingApplicationConfig.PROPERTY_DEFAULT_GPS_MAX_DELAY, + ObserveSwingApplicationConfig.PROPERTY_DEFAULT_GPS_MAX_DELAY, + n("observe.config.defaultGpsMaxDelay"), + "60", + Integer.class, + false, + false + ), + + /** vitesse maximum (en noeud) entre deux points gps */ + DEFAULT_GPS_MAX_SPEED( + ObserveSwingApplicationConfig.PROPERTY_DEFAULT_GPS_MAX_SPEED, + ObserveSwingApplicationConfig.PROPERTY_DEFAULT_GPS_MAX_SPEED, + n("observe.config.defaultGpsMaxSpeed"), + "25.0f", + Float.class, + false, + false + ), + + // synchro actions options + + /** flag pour autoriser le choix de la base source */ + CHANGE_SYNCHRO_SRC( + "ui." + ObserveSwingApplicationConfig.PROPERTY_CHANGE_SYNCHRO_SRC, + ObserveSwingApplicationConfig.PROPERTY_CHANGE_SYNCHRO_SRC, + n("observe.config.ui.changeSynchroSrc"), + "false", + Boolean.class, + false, + false + ), + + // ui config + + /** flag pour voir le boutton d'affichage de la popup de clavier numerique) */ + SHOW_NUMBER_EDITOR_BUTTON( + "ui." + ObserveSwingApplicationConfig.PROPERTY_SHOW_NUMBER_EDITOR_BUTTON, + ObserveSwingApplicationConfig.PROPERTY_SHOW_NUMBER_EDITOR_BUTTON, + n("observe.config.ui.showNumberEditorButton"), + "true", + Boolean.class, + false, + false + ), + + /** flag pour afficher automatiquement la popup du clavier numerique */ + AUTO_POPUP_NUMBER_EDITOR( + "ui." + ObserveSwingApplicationConfig.PROPERTY_AUTO_POPUP_NUMBER_EDITOR, + ObserveSwingApplicationConfig.PROPERTY_AUTO_POPUP_NUMBER_EDITOR, + n("observe.config.ui.autoPopupNumberEditor"), + "false", + Boolean.class, + false, + false + ), + + /** flag pour voir la réglette d'affichage des heures dans l'éditeur des temps */ + SHOW_DATE_TIME_EDITOR_SLIDER( + "ui." + ObserveSwingApplicationConfig.PROPERTY_SHOW_DATE_TIME_EDITOR_SLIDER, + ObserveSwingApplicationConfig.PROPERTY_SHOW_DATE_TIME_EDITOR_SLIDER, + n("observe.config.ui.showTimeEditorSlider"), + "true", + Boolean.class, + false, + false + ), + + /** flag pour lancer l'application en mode plein ecran */ + FULL_SCREEN( + "ui." + ObserveSwingApplicationConfig.PROPERTY_FULL_SCREEN, + ObserveSwingApplicationConfig.PROPERTY_FULL_SCREEN, + n("observe.config.ui.fullscreen"), + "false", + Boolean.class, + false, + false + ), + + /** locale a utiliser dans l'application */ + LOCALE( + "ui." + ObserveSwingApplicationConfig.PROPERTY_LOCALE, + ObserveSwingApplicationConfig.PROPERTY_LOCALE, + n("observe.config.ui.locale"), + Locale.FRANCE.toString(), + Locale.class, + false, + false + ), + + /** locale du referentiel */ + DB_LOCALE( + "db." + ObserveSwingApplicationConfig.PROPERTY_LOCALE, + ObserveSwingApplicationConfig.PROPERTY_DB_LOCALE, + n("observe.config.db.locale"), + Locale.FRANCE.toString(), + Locale.class, + false, + false + ), + + // program observation max + + /** la valeur maximale de qualification des observations faune associe */ + NON_TARGET_OBSERVATION( + "observation.fauneAssociee", + ObserveSwingApplicationConfig.PROPERTY_NON_TARGET_OBSERVATION, + n("observe.config.observation.fauneAssociee"), + "1", + Integer.class, + false, + false + ), + + /** la valeur maximale de qualification des observations rejet thons */ + TARGET_DISCARDS_OBSERVATION( + "observation.rejetsThons", + ObserveSwingApplicationConfig.PROPERTY_TARGET_DISCARDS_OBSERVATION, + n("observe.config.observation.rejetsThons"), + "1", + Integer.class, + false, + false + ), + + /** la valeur maximale de qualification des observations mensuration */ + SAMPLES_OBSERVATION( + "observation.mensurations", + ObserveSwingApplicationConfig.PROPERTY_SAMPLES_OBSERVATION, + n("observe.config.observation.mensurations"), + "1", + Integer.class, + false, + false + ), + + /** la valeur maximale de qualification des observations objet flottant */ + OBJECTS_OBSERVATION( + "observation.floatingObject", + ObserveSwingApplicationConfig.PROPERTY_OBJECTS_OBSERVATION, + n("observe.config.observation.floatingObject"), + "1", + Integer.class, + false, + false + ), + + /** la valeur maximale de qualification des observations activitys detaillees */ + DETAILLED_ACTIVITIES_OBSERVATION( + "observation.activitysDetaillees", + ObserveSwingApplicationConfig.PROPERTY_DETAILLED_ACTIVITIES_OBSERVATION, + n("observe.config.observation.activitysDetaillees"), + "1", + Integer.class, + false, + false + ), + + /** la valeur maximale de qualification des observations mammiferes */ + MAMMALS_OBSERVATION( + "observation.mammiferes", + ObserveSwingApplicationConfig.PROPERTY_MAMMALS_OBSERVATION, + n("observe.config.observation.mammiferes"), + "1", + Integer.class, + false, + false + ), + + /** la valeur maximale de qualification des observations oiseaux */ + BIRDS_OBSERVATION( + "observation.oiseaux", + ObserveSwingApplicationConfig.PROPERTY_BIRDS_OBSERVATION, + n("observe.config.observation.oiseaux"), + "1", + Integer.class, + false, + false + ), + + /** la valeur maximale de qualification des observations gleure */ + BAIT_OBSERVATION( + "observation.gleure", + ObserveSwingApplicationConfig.PROPERTY_BAIT_OBSERVATION, + n("observe.config.observation.gleure"), + "1", + Integer.class, + false, + false + ), + + /** le type de liste d'espèces pour les captures cibles (seine) */ + SPECIES_LIST_SEINE_TARGET_CATCH_ID( + "speciesList.seine.targetCatch", + ObserveSwingApplicationConfig.PROPERTY_SPECIES_LIST_SEINE_TARGET_CATCH_ID, + n("observe.config.speciesList.seine.targetCatch"), + ObserveSpeciesListConfiguration.DEFAULT_SPECIES_LIST_SEINE_TARGET_CATCH_ID, + String.class, + false, + false + ), + + /** le type de liste d'espèce pour les Estimation banc (seine) */ + SPECIES_LIST_SEINE_SCHOOL_ESTIMATE_ID( + "speciesList.seine.schoolEstimate", + ObserveSwingApplicationConfig.PROPERTY_SPECIES_LIST_SEINE_SCHOOL_ESTIMATE_ID, + n("observe.config.speciesList.seine.schoolEstimate"), + ObserveSpeciesListConfiguration.DEFAULT_SPECIES_LIST_SEINE_SCHOOL_ESTIMATE_ID, + String.class, + false, + false + ), + + /** le type de liste d'espèces pour les Estimation banc objet (seine) */ + SPECIES_LIST_SEINE_OBJECT_SCHOOL_ESTIMATE_ID( + "speciesList.seine.objectSchoolEstimate", + ObserveSwingApplicationConfig.PROPERTY_SPECIES_LIST_SEINE_OBJECT_SCHOOL_ESTIMATE_ID, + n("observe.config.speciesList.seine.objectSchoolEstimate"), + ObserveSpeciesListConfiguration.DEFAULT_SPECIES_LIST_SEINE_OBJECT_SCHOOL_ESTIMATE_ID, + String.class, + false, + false + ), + + /** le type de liste d'espèces pour les captures non cibles (seine) */ + SPECIES_LIST_SEINE_NON_TARGET_CATCH_ID( + "speciesList.seine.nonTargetCatch", + ObserveSwingApplicationConfig.PROPERTY_SPECIES_LIST_SEINE_NON_TARGET_CATCH_ID, + n("observe.config.speciesList.seine.nonTargetCatch"), + ObserveSpeciesListConfiguration.DEFAULT_SPECIES_LIST_SEINE_NON_TARGET_CATCH_ID, + String.class, + false, + false + ), + + /** le type de liste d'espèces pour les Faune observée (seine) */ + SPECIES_LIST_SEINE_OBJECT_OBSERVED_SPECIES_ID( + "speciesList.seine.objectObservedSpecies", + ObserveSwingApplicationConfig.PROPERTY_SPECIES_LIST_SEINE_OBJECT_OBSERVED_SPECIES_ID, + n("observe.config.speciesList.seine.objectObservedSpecies"), + ObserveSpeciesListConfiguration.DEFAULT_SPECIES_LIST_SEINE_OBJECT_OBSERVED_SPECIES_ID, + String.class, + false, + false + ), + + /** le type de liste d'espèces pour les captures (longline) */ + SPECIES_LIST_LONGLINE_CATCH_ID( + "speciesList.longline.catch", + ObserveSwingApplicationConfig.PROPERTY_SPECIES_LIST_LONGLINE_CATCH_ID, + n("observe.config.speciesList.longline.catch"), + ObserveSpeciesListConfiguration.DEFAULT_SPECIES_LIST_LONGLINE_CATCH_ID, + String.class, + false, + false + ), + + /** le type de liste d'espèces pour les rencontres (longline) */ + SPECIES_LIST_LONGLINE_ENCOUNTER_ID( + "speciesList.longline.encounter", + ObserveSwingApplicationConfig.PROPERTY_SPECIES_LIST_LONGLINE_ENCOUNTER_ID, + n("observe.config.speciesList.longline.encounter"), + ObserveSpeciesListConfiguration.DEFAULT_SPECIES_LIST_LONGLINE_ENCOUNTER_ID, + String.class, + false, + false + ), + /** le type de liste d'espèces pour les deprédations (longline) */ + SPECIES_LIST_LONGLINE_DEPREDATOR_ID( + "speciesList.longline.depredator", + ObserveSwingApplicationConfig.PROPERTY_SPECIES_LIST_LONGLINE_DEPREDATOR_ID, + n("observe.config.speciesList.longline.encounter"), + ObserveSpeciesListConfiguration.DEFAULT_SPECIES_LIST_LONGLINE_DEPREDATOR_ID, + String.class, + false, + false + ), + + /** le chemin vers le fond de carte */ + MAP_BACKGROUND_COLOR( + "map.background.color", + n("observe.config.map.background.description"), + new Color(87, 200, 255).toString(), + Color.class, + false, + false + ), + /** shape file 1 */ + MAP_LAYER_1( + "map.layer1.path", + n("observe.config.map.layer1.description"), + "${resources.directory}/map/shapeFiles/continents/GSHHS_l_L1.shp", + File.class, + false, + false + ), + /** shape file 2 */ + MAP_LAYER_2( + "map.layer2.path", + n("observe.config.map.layer2.description"), + "${resources.directory}/map/shapeFiles/continents/GSHHS_l_L6.shp", + File.class, + false, + false + ), + /** shape file 3 */ + MAP_LAYER_3( + "map.layer3.path", + n("observe.config.map.layer3.description"), + "${resources.directory}/map/shapeFiles/lakesAndSeas/GSHHS_l_L2.shp", + File.class, + false, + false + ), + /** shape file 4 */ + MAP_LAYER_4( + "map.layer4.path", + n("observe.config.map.layer4.description"), + "${resources.directory}/map/shapeFiles/borders/WDBII_border_l_L1.shp", + File.class, + false, + false + ), + /** shape file 5 */ + MAP_LAYER_5( + "map.layer5.path", + n("observe.config.map.layer5.description"), + "${resources.directory}/map/shapeFiles/zee/World_EEZ_v8_2014.shp", + File.class, + false, + false + ), + /** shape file 6 */ + MAP_LAYER_6( + "map.layer6.path", + n("observe.config.map.layer6.description"), + null, + File.class, + false, + false + ), + /** shape file 7 */ + MAP_LAYER_7( + "map.layer7.path", + n("observe.config.map.layer7.description"), + null, + File.class, + false, + false + ), + /** shape file 8 */ + MAP_LAYER_8( + "map.layer8.path", + n("observe.config.map.layer8.description"), + null, + File.class, + false, + false + ), + /** shape file 9 */ + MAP_LAYER_9( + "map.layer9.path", + n("observe.config.map.layer9.description"), + null, + File.class, + false, + false + ), + /** shape file 10 */ + MAP_LAYER_10( + "map.layer10.path", + n("observe.config.map.layer10.description"), + null, + File.class, + false, + false + ), + /** style Maps */ + MAP_STYLE_FILE( + "map.style.path", + n("observe.config.map.style.description"), + "${resources.directory}/map/style.xml", + File.class, + false, + false), + + + /** Ids des noeuds ouverts dans l'arbre */ + TREE_OPEN_NODES( + "ui." + ObserveSwingApplicationConfig.PROPERTY_TREE_OPEN_NODES, + ObserveSwingApplicationConfig.PROPERTY_TREE_OPEN_NODES, + n("observe.config.ui.treeOpenNodes"), + null, + String.class, + false, + false + ); + + public static final List<ObserveSwingApplicationConfigOption> MAP_LAYERS = ImmutableList.of(MAP_LAYER_1, MAP_LAYER_2, MAP_LAYER_3, + MAP_LAYER_4, MAP_LAYER_5, MAP_LAYER_6, MAP_LAYER_7, MAP_LAYER_8, MAP_LAYER_9, MAP_LAYER_10); + + /** + * Clef qui represente l'option (c'est celle enregistrée dans le fichier de + * configuration). + */ + protected final String key; + + /** + * Clef de la propriété (javaBeans) de la configuration associé à cette + * option ({@code null} si pas associé à une propriété javaBeans). + */ + protected final String propertyKey; + + /** Clef i18n de description de l'option */ + protected final String description; + + /** Type de l'option */ + protected final Class<?> type; + + /** Valeur par défaut de l'option */ + protected String defaultValue; + + /** Drapeau pour savoir si on ne doit pas sauvegarder cette option */ + protected boolean _transient; + + /** Drapeau pour savoir si l'option est modifiable */ + protected boolean _final; + +// /** +// * Drapeau pour savoir si l'option requiere le mode admin +// * +// * @see ObserveRunner#isAdmin() +// */ +// protected boolean admin; + + ObserveSwingApplicationConfigOption(String key, + String description, + String defaultValue, + Class<?> type, + boolean _transient, + boolean _final) { + this(key, null, description, defaultValue, type, _transient, _final); + } + + ObserveSwingApplicationConfigOption(String key, + String propertyKey, + String description, + String defaultValue, + Class<?> type, + boolean _transient, + boolean _final) { + this.key = key; + this.description = description; + this.defaultValue = defaultValue; + this.type = type; + this._final = _final; + this._transient = _transient; + this.propertyKey = propertyKey; + } + + @Override + public boolean isFinal() { + return _final; + } + + @Override + public boolean isTransient() { + return _transient; + } + +// public boolean isAdmin() { +// return admin; +// } + + @Override + public String getDefaultValue() { + return defaultValue; + } + + @Override + public String getDescription() { + return t(description); + } + + @Override + public String getKey() { + return key; + } + + @Override + public Class<?> getType() { + return type; + } + + @Override + public void setDefaultValue(String defaultValue) { + this.defaultValue = defaultValue; + } + + @Override + public void setTransient(boolean _transient) { + this._transient = _transient; + } + + @Override + public void setFinal(boolean _final) { + this._final = _final; + } + +// public void setAdmin(boolean admin) { +// this.admin = admin; +// } + + public String getPropertyKey() { + return propertyKey; + } + + public static ImmutableList<ObserveSwingApplicationConfigOption> orderedByNameValues() { + + List<ObserveSwingApplicationConfigOption> values = Lists.newArrayList(values()); + Collections.sort(values, (o1, o2) -> o1.getKey().compareTo(o2.getKey())); + return ImmutableList.copyOf(values); + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/configuration/ObserveSwingApplicationConfigProvider.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/configuration/ObserveSwingApplicationConfigProvider.java new file mode 100644 index 0000000..1414548 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/configuration/ObserveSwingApplicationConfigProvider.java @@ -0,0 +1,60 @@ +package fr.ird.observe.application.swing.configuration; + +/*- + * #%L + * ObServe :: Application Swing + * %% + * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveCLAction; +import org.nuiton.config.ApplicationConfigProvider; +import org.nuiton.config.ConfigActionDef; +import org.nuiton.config.ConfigOptionDef; + +import java.util.Locale; + +import static org.nuiton.i18n.I18n.l; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class ObserveSwingApplicationConfigProvider implements ApplicationConfigProvider { + + public static final String OBSERVE_SWING_CONFIGURATION_PROVIDER_NAME = "observeSwing"; + + @Override + public String getName() { + return OBSERVE_SWING_CONFIGURATION_PROVIDER_NAME; + } + + @Override + public String getDescription(Locale locale) { + return l(locale, "observe.config.name"); + } + + @Override + public ConfigOptionDef[] getOptions() { + return ObserveSwingApplicationConfigOption.values(); + } + + @Override + public ConfigActionDef[] getActions() { + return ObserveCLAction.ActionDefinition.values(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/DataContext.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/DataContext.java new file mode 100644 index 0000000..6b6bd3b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/DataContext.java @@ -0,0 +1,778 @@ +package fr.ird.observe.application.swing.db; + +/* + * #%L + * ObServe :: Business + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.IdDtos; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.services.dto.seine.FloatingObjectDto; +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.services.dto.seine.SetSeineDto; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.jdesktop.beans.AbstractSerializableBean; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +public class DataContext extends AbstractSerializableBean { + + public static final String PROPERTY_OPEN_PROGRAM = "openProgram"; + + public static final String PROPERTY_OPEN_TRIP = "openTrip"; + public static final String PROPERTY_OPEN_TRIP_SEINE = "openTripSeine"; + public static final String PROPERTY_OPEN_TRIP_LONGLINE = "openTripLongline"; + + public static final String PROPERTY_OPEN_ROUTE = "openRoute"; + + public static final String PROPERTY_OPEN_ACTIVITY = "openActivity"; + public static final String PROPERTY_OPEN_ACTIVITY_SEINE = "openActivitySeine"; + public static final String PROPERTY_OPEN_ACTIVITY_LONGLINE = "openActivityLongline"; + + public static final String PROPERTY_OPEN_SET = "openSet"; + public static final String PROPERTY_OPEN_SET_SEINE = "openSetSeine"; + public static final String PROPERTY_OPEN_SET_LONGLINE = "openSetLongline"; + + public static final String PROPERTY_OPEN_PROGRAM_ID = "openProgramId"; + + public static final String PROPERTY_OPEN_TRIP_ID = "openTripId"; + public static final String PROPERTY_OPEN_TRIP_SEINE_ID = "openTripSeineId"; + public static final String PROPERTY_OPEN_TRIP_LONGLINE_ID = "openTripLonglineId"; + + public static final String PROPERTY_OPEN_ROUTE_ID = "openRouteId"; + + public static final String PROPERTY_OPEN_ACTIVITY_ID = "openActivityId"; + public static final String PROPERTY_OPEN_ACTIVITY_SEINE_ID = "openActivitySeineId"; + public static final String PROPERTY_OPEN_ACTIVITY_LONGLINE_ID = "openActivityLonglineId"; + + public static final String PROPERTY_OPEN_SET_ID = "openSetId"; + public static final String PROPERTY_OPEN_SET_SEINE_ID = "openSetSeineId"; + public static final String PROPERTY_OPEN_SET_LONGLINE_ID = "openSetLonglineId"; + + public static final String PROPERTY_SELECTED_PROGRAM_ID = "selectedProgramId"; + + public static final String PROPERTY_SELECTED_TRIP_ID = "selectedTripId"; + + public static final String PROPERTY_SELECTED_ROUTE_ID = "selectedRouteId"; + + public static final String PROPERTY_SELECTED_ACTIVITY_ID = "selectedActivityId"; + + public static final String PROPERTY_SELECTED_SET_ID = "selectedSetId"; + + public static final String PROPERTY_SELECTED_FLOATING_OBJECT_ID = "selectedFloatingObjectId"; + + public static final String PROPERTY_ENABLED = "enabled"; + + public static final String PROPERTY_SELECTION_CHANGED = "selectionChanged"; + + protected String openProgramId; + + protected String openTripSeineId; + + protected String openTripLonglineId; + + protected String openRouteId; + + protected String openActivitySeineId; + + protected String openActivityLonglineId; + + protected String openSetSeineId; + + protected String openSetLonglineId; + + protected String selectedProgramId; + + protected String selectedTripId; + + protected String selectedRouteId; + + protected String selectedActivityId; + + protected String selectedSetId; + + protected String selectedFloatingObjectId; + + protected boolean enabled; + + protected boolean selectionChanged; + + protected TripSeineDto validationTripSeine; + + protected RouteDto validationRoute; + + protected ActivitySeineDto validationActivitySeine; + + protected SetSeineDto validationSetSeine; + + protected FloatingObjectDto validationFloatingObject; + + /** Logger */ + private static final Log log = LogFactory.getLog(DataContext.class); + + private static final long serialVersionUID = 1L; + + public String getOpenProgramId() { + return openProgramId; + } + + public void setOpenProgramId(String openProgramId) { + String oldValue = getOpenProgramId(); + boolean oldValue2 = isOpenProgram(); + this.openProgramId = openProgramId; + firePropertyChange(PROPERTY_OPEN_PROGRAM_ID, oldValue, this.openProgramId); + firePropertyChange(PROPERTY_OPEN_PROGRAM, oldValue2, isOpenProgram()); + } + + public String getOpenTripId() { + return openTripSeineId != null ? openTripSeineId : openTripLonglineId; + } + + public String getOpenTripSeineId() { + return openTripSeineId; + } + + public String getOpenTripLonglineId() { + return openTripLonglineId; + } + + public void setOpenTripSeineId(String openTripId) { + String oldValue = getOpenTripId(); + String oldValue2 = getOpenTripSeineId(); + boolean oldValue3 = isOpenTrip(); + boolean oldValue4 = isOpenTripSeine(); + this.openTripSeineId = openTripId; + firePropertyChange(PROPERTY_OPEN_TRIP_ID, oldValue, this.openTripSeineId); + firePropertyChange(PROPERTY_OPEN_TRIP_SEINE_ID, oldValue2, this.openTripSeineId); + firePropertyChange(PROPERTY_OPEN_TRIP, oldValue3, isOpenTrip()); + firePropertyChange(PROPERTY_OPEN_TRIP_SEINE, oldValue4, isOpenTripSeine()); + } + + public void setOpenTripLonglineId(String openTripId) { + String oldValue = getOpenTripId(); + String oldValue2 = getOpenTripLonglineId(); + boolean oldValue3 = isOpenTrip(); + boolean oldValue4 = isOpenTripLongline(); + this.openTripLonglineId = openTripId; + firePropertyChange(PROPERTY_OPEN_TRIP_ID, oldValue, this.openTripLonglineId); + firePropertyChange(PROPERTY_OPEN_TRIP_LONGLINE_ID, oldValue2, this.openTripLonglineId); + firePropertyChange(PROPERTY_OPEN_TRIP, oldValue3, isOpenTrip()); + firePropertyChange(PROPERTY_OPEN_TRIP_LONGLINE, oldValue4, isOpenTripLongline()); + } + + public String getOpenRouteId() { + return openRouteId; + } + + public void setOpenRouteId(String openRouteId) { + String oldValue = getOpenRouteId(); + boolean oldValue2 = isOpenRoute(); + this.openRouteId = openRouteId; + firePropertyChange(PROPERTY_OPEN_ROUTE_ID, oldValue, openRouteId); + firePropertyChange(PROPERTY_OPEN_ROUTE, oldValue2, isOpenRoute()); + } + + public String getOpenActivityId() { + return openActivitySeineId != null ? openActivitySeineId : openActivityLonglineId; + } + + public String getOpenActivityLonglineId() { + return openActivityLonglineId; + } + + public String getOpenActivitySeineId() { + return openActivitySeineId; + } + + public void setOpenActivitySeineId(String openActivityId) { + String oldValue = getOpenActivityId(); + String oldValue2 = getOpenActivitySeineId(); + boolean oldValue3 = isOpenActivity(); + boolean oldValue4 = isOpenActivitySeine(); + this.openActivitySeineId = openActivityId; + firePropertyChange(PROPERTY_OPEN_ACTIVITY_ID, oldValue, this.openActivitySeineId); + firePropertyChange(PROPERTY_OPEN_ACTIVITY_SEINE_ID, oldValue2, this.openActivitySeineId); + firePropertyChange(PROPERTY_OPEN_ACTIVITY, oldValue3, isOpenActivity()); + firePropertyChange(PROPERTY_OPEN_ACTIVITY_SEINE, oldValue4, isOpenActivitySeine()); + } + + public void setOpenActivityLonglineId(String openActivityId) { + String oldValue = getOpenActivityId(); + String oldValue2 = getOpenActivityLonglineId(); + boolean oldValue3 = isOpenActivity(); + boolean oldValue4 = isOpenActivityLongline(); + this.openActivityLonglineId = openActivityId; + firePropertyChange(PROPERTY_OPEN_ACTIVITY_ID, oldValue, this.openActivityLonglineId); + firePropertyChange(PROPERTY_OPEN_ACTIVITY_LONGLINE_ID, oldValue2, this.openActivityLonglineId); + firePropertyChange(PROPERTY_OPEN_ACTIVITY, oldValue3, isOpenActivity()); + firePropertyChange(PROPERTY_OPEN_ACTIVITY_LONGLINE, oldValue4, isOpenActivityLongline()); + } + + public String getOpenSetId() { + return openSetSeineId != null ? openSetSeineId : openSetLonglineId; + } + + public String getOpenSetLonglineId() { + return openSetSeineId; + } + + public String getOpenSetSeineId() { + return openSetLonglineId; + } + + public void setOpenSetSeineId(String openSetId) { + String oldValue = getOpenSetId(); + String oldValue2 = getOpenSetSeineId(); + boolean oldValue3 = isOpenSet(); + boolean oldValue4 = isOpenSetSeine(); + this.openSetSeineId = openSetId; + firePropertyChange(PROPERTY_OPEN_SET_ID, oldValue, this.openSetSeineId); + firePropertyChange(PROPERTY_OPEN_SET_SEINE_ID, oldValue2, this.openSetSeineId); + firePropertyChange(PROPERTY_OPEN_SET, oldValue3, isOpenSet()); + firePropertyChange(PROPERTY_OPEN_SET_SEINE, oldValue4, isOpenSetSeine()); + } + + public void setOpenSetLonglineId(String openSetId) { + String oldValue = getOpenSetId(); + String oldValue2 = getOpenSetLonglineId(); + boolean oldValue3 = isOpenSet(); + boolean oldValue4 = isOpenSetLongline(); + this.openSetLonglineId = openSetId; + firePropertyChange(PROPERTY_OPEN_SET_ID, oldValue, this.openSetLonglineId); + firePropertyChange(PROPERTY_OPEN_SET_LONGLINE_ID, oldValue2, this.openSetLonglineId); + firePropertyChange(PROPERTY_OPEN_SET, oldValue3, isOpenSet()); + firePropertyChange(PROPERTY_OPEN_SET_LONGLINE, oldValue4, isOpenSetLongline()); + } + + public String getSelectedProgramId() { + return selectedProgramId; + } + + public void setSelectedProgramId(String selectedProgramId) { + String oldValue = getSelectedProgramId(); + this.selectedProgramId = selectedProgramId; + firePropertyChange(PROPERTY_SELECTED_PROGRAM_ID, oldValue, this.selectedProgramId); + } + + public String getSelectedTripId() { + return selectedTripId; + } + + public String getSelectedTripLonglineId() { + return isSelectedTripLongline() ? getSelectedTripId() : null; + } + + public String getSelectedTripSeineId() { + return isSelectedTripSeine() ? getSelectedTripId() : null; + } + + public void setSelectedTripId(String selectedTripId) { + String oldValue = getSelectedTripId(); + this.selectedTripId = selectedTripId; + firePropertyChange(PROPERTY_SELECTED_TRIP_ID, oldValue, this.selectedTripId); + } + + public boolean isSelectedTripLongline() { + return selectedTripId != null && IdDtos.isLonglineId(selectedTripId); + } + + public boolean isSelectedTripSeine() { + return selectedTripId != null && IdDtos.isSeineId(selectedTripId); + } + + public String getSelectedRouteId() { + return selectedRouteId; + } + + public void setSelectedRouteId(String selectedRouteId) { + String oldValue = getSelectedRouteId(); + this.selectedRouteId = selectedRouteId; + firePropertyChange(PROPERTY_SELECTED_ROUTE_ID, oldValue, selectedRouteId); + } + + public String getSelectedActivityId() { + return selectedActivityId; + } + + public String getSelectedActivityLonglineId() { + return isSelectedActivityLongline() ? getSelectedActivityId() : null; + } + + public String getSelectedActivitySeineId() { + return isSelectedActivitySeine() ? getSelectedActivityId() : null; + } + + public boolean isSelectedActivityLongline() { + return selectedActivityId != null && IdDtos.isLonglineId(selectedActivityId); + } + + public boolean isSelectedActivitySeine() { + return selectedActivityId != null && IdDtos.isSeineId(selectedActivityId); + } + + public void setSelectedActivityId(String selectedActivityId) { + String oldValue = getSelectedActivityId(); + this.selectedActivityId = selectedActivityId; + firePropertyChange(PROPERTY_SELECTED_ACTIVITY_ID, oldValue, this.selectedActivityId); + } + + public String getSelectedSetId() { + return selectedSetId; + } + + public String getSelectedSetLonglineId() { + return isSelectedActivityLongline() ? getSelectedSetId() : null; + } + + public String getSelectedSetSeineId() { + return isSelectedActivitySeine() ? getSelectedSetId() : null; + } + + public void setSelectedSetId(String selectedSetId) { + String oldValue = getSelectedSetId(); + this.selectedSetId = selectedSetId; + firePropertyChange(PROPERTY_SELECTED_SET_ID, oldValue, this.selectedSetId); + } + + public String getSelectedFloatingObjectId() { + return selectedFloatingObjectId; + } + + public void setSelectedFloatingObjectId(String selectedFloatingObjectId) { + String oldValue = getSelectedFloatingObjectId(); + this.selectedFloatingObjectId = selectedFloatingObjectId; + firePropertyChange(PROPERTY_SELECTED_FLOATING_OBJECT_ID, oldValue, this.selectedFloatingObjectId); + } + + public boolean isEnabled() { + return enabled; + } + + public boolean getEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + boolean oldValue = getEnabled(); + this.enabled = enabled; + firePropertyChange(PROPERTY_ENABLED, oldValue, enabled); + } + + public boolean isSelectionChanged() { + return selectionChanged; + } + + public boolean getSelectionChanged() { + return selectionChanged; + } + + public void setSelectionChanged(boolean selectionChanged) { + boolean oldValue = getSelectionChanged(); + this.selectionChanged = selectionChanged; + firePropertyChange(PROPERTY_SELECTION_CHANGED, oldValue, selectionChanged); + } + + public DataContext() { + } + + static DataContextType[] types; + + static DataContextType[] reverseTypes; + + public DataContextType[] getTypes() { + if (types == null) { + types = DataContextType.values(); + } + return types; + } + + public DataContextType[] getReverseTypes() { + if (reverseTypes == null) { + List<DataContextType> list = Arrays.asList(DataContextType.values()); + Collections.reverse(list); + reverseTypes = list.toArray(new DataContextType[list.size()]); + } + + return reverseTypes; + } + + public String getHigherOpenId() { + for (DataContextType type : getReverseTypes()) { + String result = type.getOpenId(this); + if (result != null) { + return result; + } + } + return null; + } + + public String getHigherSelectedId() { + + for (DataContextType type : getReverseTypes()) { + String result = type.getSelectedId(this); + if (result != null) { + return result; + } + } + return null; + } + + public String[] getSelectedIds() { + + List<String> ids = new ArrayList<>(); + + for (DataContextType type : getTypes()) { + String result = type.getSelectedId(this); + if (result != null) { + ids.add(result); + } + } + return ids.toArray(new String[ids.size()]); + } + + public String[] getOpenIds() { + + List<String> ids = new ArrayList<>(); + + for (DataContextType type : getTypes()) { + String result = type.getOpenId(this); + if (result != null) { + ids.add(result); + } + } + return ids.toArray(new String[ids.size()]); + } + + public String[] getOpenIds(Class<?> type) { + + String[] result = null; + + if (isOpenProgram()) { + + List<String> ids = new ArrayList<>(); + ids.add(getOpenProgramId()); + + if (!ProgramDto.class.equals(type) && isOpenTrip()) { + + String tripId = getOpenTripId(); + ids.add(tripId); + + if (IdDtos.isTripSeineId(tripId)) { + + // on a seine trip + if (!IdDtos.isTripClass(type) && isOpenRoute()) { + + ids.add(getOpenRouteId()); + + if (!RouteDto.class.equals(type) && isOpenActivitySeine()) { + + ids.add(getOpenActivitySeineId()); + + if (!IdDtos.isActivityClass(type) && isOpenSetSeine()) { + ids.add(getOpenSetSeineId()); + } + } + } + + } else { + + // on a longline trip + if (!IdDtos.isTripClass(type) && isOpenActivityLongline()) { + + ids.add(getOpenActivityLonglineId()); + + if (!IdDtos.isActivityClass(type) && isOpenSetLongline()) { + ids.add(getOpenSetLonglineId()); + } + + } + + } + + } + + result = ids.toArray(new String[ids.size()]); + + } + + return result; + } + + public boolean isOpenProgram() { + return openProgramId != null; + } + + public boolean isOpenTrip() { + return isOpenTripLongline() || isOpenTripSeine(); + } + + public boolean isOpenTripLongline() { + return openTripLonglineId != null; + } + + public boolean isOpenTripSeine() { + return openTripSeineId != null; + } + + public boolean isOpenRoute() { + return openRouteId != null; + } + + public boolean isOpenActivity() { + return isOpenActivityLongline() || isOpenActivitySeine(); + } + + public boolean isOpenActivityLongline() { + return openActivityLonglineId != null; + } + + public boolean isOpenActivitySeine() { + return openActivitySeineId != null; + } + + + public boolean isOpenSet() { + return isOpenSetLongline() || isOpenSetSeine(); + } + + public boolean isOpenSetLongline() { + return openSetLonglineId != null; + } + + public boolean isOpenSetSeine() { + return openSetSeineId != null; + } + + public boolean isSelectedOpen(Class<?> type) { + + for (DataContextType entityType : DataContextType.values()) { + if (entityType.acceptType(type)) { + + // bon type trouve + + String openId = entityType.getOpenId(this); + String selectedId = entityType.getSelectedId(this); + if (selectedId == null || openId == null) { + + // pas selectionne ou rien d'ouvert + return false; + } + + return selectedId.equals(openId); + } + } + + // type non trouve + return false; + } + + public void populateSelectedIds(String... selectedId) { + + List<String> oldSelection = Arrays.asList(getSelectedIds()); + + if (log.isDebugEnabled()) { + log.debug("old selection = " + oldSelection); + } + + // on nettoye toujours toutes les anciennes sélections + // avant de positionner les nouvelles + resetSelect(); + + List<String> realSelection = null; + if (selectedId != null && selectedId.length > 0) { + + realSelection = new ArrayList<>(); + for (String s : selectedId) { + if (s == null) { + + // ce cas peut arriver lors de la creation d'un nouvel objet + continue; + } + DataContextType type = DataContextType.acceptId(s); + if (type == null) { + + if (log.isWarnEnabled()) { + log.warn("Could not find type for id : " + s); + } + continue; + } + + type.setSelectedId(this, s); + realSelection.add(s); + if (log.isDebugEnabled()) { + log.debug("add selectedId : " + s); + } + } + } + + if (oldSelection.equals(realSelection)) { + + // rien a change + if (log.isDebugEnabled()) { + log.debug("selection does not changed"); + } + return; + } + + if (log.isInfoEnabled()) { + log.info("new selection = " + realSelection); + } + + // on change toujours l'état de selection + + setSelectionChanged(true); + } + + public void populateOpens(String... openIds) { + if (!getEnabled()) { + + if (log.isWarnEnabled()) { + log.warn(this + " is not enabled"); + } + // service non initialisé + resetOpen(); + return; + } + + List<String> oldSelection = Arrays.asList(getOpenIds()); + List<String> realSelection = new ArrayList<>(); + + if (openIds != null && openIds.length > 0) { + + for (String s : openIds) { + if (s == null) { + + // ce cas peut arriver lors de la creation d'un nouvel objet + continue; + } + DataContextType type = DataContextType.acceptId(s); + if (type == null) { + + if (log.isWarnEnabled()) { + log.warn("Could not find type for id : " + s); + } + continue; + } + + if (!type.canOpen()) { + + // pas de traitement open + continue; + } + + type.setOpenId(this, s); + realSelection.add(s); + if (log.isDebugEnabled()) { + log.debug("add openId : " + s); + } + } + } + + // if only the program is open, remove it + if (realSelection.size() == 1) { + setOpenProgramId(null); + realSelection.clear(); + } + + if (oldSelection.equals(realSelection)) { + + // rien a change + if (log.isDebugEnabled()) { + log.debug("openIds selection does not changed"); + } + return; + } + + if (log.isInfoEnabled()) { + log.info("new openIds selection = " + realSelection); + log.info("old openIds selection = " + oldSelection); + } + + for (String s : oldSelection) { + + if (realSelection.contains(s)) { + // pas bouge rien a faire + continue; + } + + DataContextType type = DataContextType.acceptId(s); + if (type == null) { + + if (log.isWarnEnabled()) { + log.warn("Could not find type for id : " + s); + } + continue; + } + + if (!type.canOpen()) { + + // pas de traitement open + continue; + } + + String newId = type.getOpenId(this); + if (newId != null) { + + if (log.isInfoEnabled()) { + log.info("will remove old obsolete open id : " + s); + } + + // plus d'id pour ce type, on le supprime + type.setOpenId(this, null); + } + } + } + + protected void reset() { + resetOpen(); + resetSelect(); + } + + protected void resetSelect() { + setSelectedProgramId(null); + setSelectedTripId(null); + setSelectedRouteId(null); + setSelectedActivityId(null); + setSelectedFloatingObjectId(null); + setSelectedSetId(null); + selectionChanged = false; + } + + public void resetOpen() { + setOpenProgramId(null); + setOpenTripSeineId(null); + setOpenTripLonglineId(null); + setOpenRouteId(null); + setOpenActivitySeineId(null); + setOpenActivityLonglineId(null); + } + + protected void firePropertyChange(String propertyName, Object newValue) { + firePropertyChange(propertyName, null, newValue); + } + +} //DataContext diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/ObserveSwingDataSource.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/ObserveSwingDataSource.java new file mode 100644 index 0000000..346e2c1 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/ObserveSwingDataSource.java @@ -0,0 +1,723 @@ +package fr.ird.observe.application.swing.db; + +/*- + * #%L + * ObServe :: Application Swing + * %% + * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableList; +import com.google.common.collect.ImmutableMap; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.db.event.ObserveSwingDataSourceEvent; +import fr.ird.observe.application.swing.db.event.ObserveSwingDataSourceListener; +import fr.ird.observe.services.ObserveService; +import fr.ird.observe.services.ObserveServiceInitializer; +import fr.ird.observe.services.ObserveServiceMainFactory; +import fr.ird.observe.services.ObserveServicesProvider; +import fr.ird.observe.services.ObserveSpeciesListConfiguration; +import fr.ird.observe.services.configuration.ObserveDataSourceConfiguration; +import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationAndConnection; +import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationRest; +import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaH2; +import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaPG; +import fr.ird.observe.services.configuration.ObserveDataSourceConnection; +import fr.ird.observe.services.configuration.ObserveDataSourceInformation; +import fr.ird.observe.services.configuration.ObserveDataSourceType; +import fr.ird.observe.services.dto.DataSourceCreateConfigurationDto; +import fr.ird.observe.services.dto.DataSourceCreateWithNoReferentialImportException; +import fr.ird.observe.services.dto.IncompatibleDataSourceCreateConfigurationException; +import fr.ird.observe.services.dto.ObserveDbUserDto; +import fr.ird.observe.services.dto.constants.ReferentialLocale; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.ReferentialReferenceSet; +import fr.ird.observe.services.service.BabModelVersionException; +import fr.ird.observe.services.service.DataSourceService; +import fr.ird.observe.services.service.DatabaseConnexionNotAuthorizedException; +import fr.ird.observe.services.service.DatabaseDestroyNotAuthorizedException; +import fr.ird.observe.services.service.DatabaseNotFoundException; +import fr.ird.observe.services.service.ObserveReferentialCache; +import fr.ird.observe.services.service.PingService; +import fr.ird.observe.services.service.ReferentialService; +import fr.ird.observe.services.service.SqlScriptProducerService; +import fr.ird.observe.services.service.actions.consolidate.ConsolidateDataService; +import fr.ird.observe.services.service.actions.export.ReplicateTripService; +import fr.ird.observe.services.service.actions.report.ReportService; +import fr.ird.observe.services.service.actions.synchro.data.DataSynchronizeService; +import fr.ird.observe.services.service.actions.synchro.referential.diff.ReferentialSynchronizeDiffService; +import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeLocalService; +import fr.ird.observe.services.service.actions.synchro.referential.ng.ReferentialSynchronizeService; +import fr.ird.observe.services.service.actions.validate.ValidateService; +import fr.ird.observe.services.service.longline.ActivityLongLineEncounterService; +import fr.ird.observe.services.service.longline.ActivityLongLineSensorUsedService; +import fr.ird.observe.services.service.longline.ActivityLonglineService; +import fr.ird.observe.services.service.longline.BranchlineService; +import fr.ird.observe.services.service.longline.SetLonglineCatchService; +import fr.ird.observe.services.service.longline.SetLonglineDetailCompositionService; +import fr.ird.observe.services.service.longline.SetLonglineGlobalCompositionService; +import fr.ird.observe.services.service.longline.SetLonglineService; +import fr.ird.observe.services.service.longline.TdrService; +import fr.ird.observe.services.service.longline.TripLonglineGearUseService; +import fr.ird.observe.services.service.longline.TripLonglineService; +import fr.ird.observe.services.service.seine.ActivitySeineObservedSystemService; +import fr.ird.observe.services.service.seine.ActivitySeineService; +import fr.ird.observe.services.service.seine.FloatingObjectService; +import fr.ird.observe.services.service.seine.NonTargetCatchService; +import fr.ird.observe.services.service.seine.NonTargetSampleService; +import fr.ird.observe.services.service.seine.ObjectObservedSpeciesService; +import fr.ird.observe.services.service.seine.ObjectSchoolEstimateService; +import fr.ird.observe.services.service.seine.RouteService; +import fr.ird.observe.services.service.seine.SchoolEstimateService; +import fr.ird.observe.services.service.seine.SetSeineService; +import fr.ird.observe.services.service.seine.TargetCatchService; +import fr.ird.observe.services.service.seine.TargetSampleService; +import fr.ird.observe.services.service.seine.TransmittingBuoyOperationService; +import fr.ird.observe.services.service.seine.TripSeineGearUseService; +import fr.ird.observe.services.service.seine.TripSeineService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.jdesktop.beans.AbstractSerializableBean; +import org.nuiton.version.Version; + +import javax.swing.JOptionPane; +import javax.swing.event.EventListenerList; +import java.io.Closeable; +import java.io.File; +import java.util.Locale; +import java.util.Set; + +import static org.nuiton.i18n.I18n.t; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class ObserveSwingDataSource extends AbstractSerializableBean implements Closeable, ObserveServicesProvider { + + private static final long serialVersionUID = 1L; + + private static final Log log = LogFactory.getLog(ObserveSwingDataSource.class); + + /** le conteneur de listeners */ + protected final EventListenerList listenerList; + + protected final ObserveDataSourceConfiguration configuration; + + protected final ObserveReferentialCache referentialCache; + + protected ObserveDataSourceConnection connection; + + // indique que la connexion a expiré mais que la source n'est pas complétement fermer + private boolean expired; + + public ObserveSwingDataSource(ObserveDataSourceConfiguration configuration) { + this.configuration = configuration; + this.listenerList = new EventListenerList(); + this.referentialCache = new ObserveReferentialCache(); + this.expired = false; + } + + public ObserveDataSourceConfiguration getConfiguration() { + return configuration; + } + + public ObserveDataSourceConnection getConnection() { + return connection; + } + + public String getLabel() { + return configuration.getLabel(); + } + + public boolean isSqlDataSource() { + return ObserveDataSourceType.SQL == configuration.getType(); + } + +// public String getAuthenticationToken() { +// String result = null; +// if (connection != null) { +// result = connection.getAuthenticationToken(); +// } +// return result; +// } + + public boolean canWriteData() { + boolean result = connection != null && connection.canWriteData(); + return result; + } + + public Version getVersion() { + Version result = null; + if (connection != null) { + result = connection.getVersion(); + } + return result; + } + + public boolean canReadReferential() { + boolean result = connection != null && connection.canReadReferential(); + return result; + } + + public boolean canReadData() { + boolean result = connection != null && connection.canReadData(); + return result; + } + + public boolean canWriteReferential() { + boolean result = connection != null && connection.canWriteReferential(); + return result; + } + + public ObserveDataSourceInformation getInformation() { + return new ObserveDataSourceInformation( + canReadReferential(), + canWriteReferential(), + canReadData(), + canWriteData(), + getVersion(), + getVersion(), + ImmutableList.of()); + } + + public void open() throws DatabaseConnexionNotAuthorizedException, DatabaseNotFoundException, BabModelVersionException { + + checkIsNotAlreadyOpen(); + + fireNewMessage(t("observe.storage.message.opening", getLabel())); + fireOpening(); + + + DataSourceService dataSourceService = newDataSourceService(); + + connection = dataSourceService.open(configuration); + + fireNewMessage(t("observe.storage.message.opened", getLabel())); + fireOpened(); + } + + public void create(DataSourceCreateConfigurationDto createDto) + throws IncompatibleDataSourceCreateConfigurationException, DataSourceCreateWithNoReferentialImportException, + DatabaseNotFoundException, DatabaseConnexionNotAuthorizedException, BabModelVersionException { + + checkIsNotAlreadyOpen(); + + fireNewMessage(t("observe.storage.message.creating", getLabel())); + fireOpening(); + + DataSourceService dataSourceService = newDataSourceService(); + + connection = dataSourceService.create(configuration, createDto); + + fireNewMessage(t("observe.storage.message.created", getLabel())); + fireOpened(); + } + + @Override + public void close() { + + checkIsOpen(); + + fireNewMessage(t("observe.storage.message.closing", getLabel())); + fireClosing(); + + referentialCache.close(); + + try { + // si la connection a expirée la source a deja été fermer pas le serveur + if (!expired) { + DataSourceService dataSourceService = newDataSourceService(); + + dataSourceService.close(); + } + } finally { + connection = null; + expired = false; + + fireNewMessage(t("observe.storage.message.closed", getLabel())); + fireClosed(); + } + + } + + public void destroy() throws DatabaseDestroyNotAuthorizedException { + + checkIsOpen(); + + fireNewMessage(t("observe.storage.message.destroying", getLabel())); + fireClosing(); + + referentialCache.close(); + + DataSourceService dataSourceService = newDataSourceService(); + + dataSourceService.destroy(); + + connection = null; + + fireNewMessage(t("observe.storage.message.destroyed", getLabel())); + fireClosed(); + + } + + public Set<ObserveDbUserDto> getUsers() { + + checkIsNotOpen(); + + DataSourceService dataSourceService = newDataSourceService(); + + Set<ObserveDbUserDto> users = dataSourceService.getUsers(getConfiguration()); + + return users; + } + + + public void applySecurity(Set<ObserveDbUserDto> users) { + + checkIsNotOpen(); + + DataSourceService dataSourceService = newDataSourceService(); + + dataSourceService.applySecurity(getConfiguration(), users); + } + + public void migrateData(ObserveDataSourceInformation dataSourceInformation, Version targetVersion) { + + checkIsNotOpen(); + + Version dbVersion = dataSourceInformation.getVersion(); + if (!dataSourceInformation.getMigrations().isEmpty()) { + + if (dbVersion.before(dataSourceInformation.getMinnimumVersion())) { + + JOptionPane.showMessageDialog( + null, + t("observe.storage.migrate.not.possible.before.version.3.0.message", targetVersion, dbVersion), + t("observe.storage.migrate.not.possible.before.version.3.0.title", targetVersion), + JOptionPane.WARNING_MESSAGE); + + } else { + + int answer = JOptionPane.showConfirmDialog( + null, + t("observe.storage.migrate.askUser.message", dbVersion, targetVersion, dataSourceInformation.getMigrations()), + t("observe.storage.migrate.askUser.title", targetVersion), + JOptionPane.YES_NO_OPTION, + JOptionPane.WARNING_MESSAGE); + + if (answer == JOptionPane.YES_OPTION) { + + DataSourceService dataSourceService = newDataSourceService(); + + + if (log.isInfoEnabled()) { + log.info("Migrate data source " + getLabel() + " in " + dbVersion + " to " + targetVersion); + } + + dataSourceService.migrateData(getConfiguration()); + } + } + } + + } + + public ImmutableMap<Class<?>, ReferentialReferenceSet<?>> updateReferentialReferenceSetsCache(String referentialReferenceSetsRequestName) { + + ReferentialService referentialService = newReferentialService(); + return referentialCache.loadReferenceSets(referentialService, referentialReferenceSetsRequestName); + + } + + protected <D extends ReferentialDto> ReferentialReferenceSet<D> getReferentialReferenceSet(Class<D> type) { + + checkIsOpen(); + + ReferentialService referentialService = newReferentialService(); + return referentialCache.getReferentialReferenceSet(referentialService, type); + } + + public <D extends ReferentialDto> Set<ReferentialReference<D>> getReferentialReferences(Class<D> type) { + + ReferentialReferenceSet<D> referentialReferenceSet = getReferentialReferenceSet(type); + return referentialReferenceSet.getReferences(); + + } + + public <D extends ReferentialDto> ReferentialReference<D> getReferentialReference(Class<D> type, String id) { + + ReferentialReferenceSet<D> referentialReferenceSet = getReferentialReferenceSet(type); + return referentialReferenceSet.getReferenceById(id); + + } + + public boolean isOpen() { + return connection != null; + } + + @Override + public SetLonglineService newSetLonglineService() { + return newService(SetLonglineService.class); + } + + public ObserveDataSourceInformation checkCanConnect() throws DatabaseConnexionNotAuthorizedException, DatabaseNotFoundException { + + checkIsNotAlreadyOpen(); + + DataSourceService dataSourceService = newDataSourceService(); + + ObserveDataSourceInformation dataSourceInformation = dataSourceService.checkCanConnect(configuration); + + return dataSourceInformation; + + } + + public boolean isLocal() { + return configuration instanceof ObserveDataSourceConfigurationTopiaH2; + } + + public boolean isRemote() { + return configuration instanceof ObserveDataSourceConfigurationTopiaPG; + } + + public boolean isServer() { + return configuration instanceof ObserveDataSourceConfigurationRest; + } + + public void addObserveSwingDataSourceListener(ObserveSwingDataSourceListener listener) { + listenerList.add(ObserveSwingDataSourceListener.class, listener); + } + + public ObserveSwingDataSourceListener[] getObserveSwingDataSourceListener() { + return listenerList.getListeners(ObserveSwingDataSourceListener.class); + } + +// public boolean containsObserveSwingDataSourceListener(ObserveSwingDataSourceListener listener) { +// ObserveSwingDataSourceListener[] listeners = getObserveSwingDataSourceListener(); +// for (ObserveSwingDataSourceListener l : listeners) { +// if (l.equals(listener)) { +// return true; +// } +// } +// return false; +// } + + public void removeObserveSwingDataSourceListener(ObserveSwingDataSourceListener listener) { + if (log.isInfoEnabled()) { + log.info("removing listener " + listener); + } + listenerList.remove(ObserveSwingDataSourceListener.class, listener); + } + + public void removeObserveSwingDataSourceListeners() { + // remove all listeners + for (ObserveSwingDataSourceListener listener : getObserveSwingDataSourceListener()) { + removeObserveSwingDataSourceListener(listener); + } + } + + public void fireNewMessage(String message) { + fireNewMessage(message, ObserveSwingDataSourceEvent.MessageLevel.INFO); + } + + public void fireNewMessage(String message, ObserveSwingDataSourceEvent.MessageLevel level) { + ObserveSwingDataSourceEvent evt = new ObserveSwingDataSourceEvent(this, message, level); + for (ObserveSwingDataSourceListener listener : getObserveSwingDataSourceListener()) { + listener.onNewMessage(evt); + } + } + + public boolean isExpired() { + return expired; + } + + public void expired() { + this.expired = true; + } + + protected ObserveServiceInitializer getObserveServiceInitializer() { + + ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); + + ObserveSwingApplicationConfig config = context.getConfig(); + + Locale locale = config.getLocale(); + + File tmpDirectory = config.getTmpDirectory(); + + ReferentialLocale referentialLocale = ReferentialLocale.valueOf(locale); + + ObserveDataSourceConfigurationAndConnection configurationAndConnection = new ObserveDataSourceConfigurationAndConnection(configuration, connection); + + ObserveSpeciesListConfiguration speciesListConfiguration = new ObserveSpeciesListConfiguration(); + speciesListConfiguration.setSpeciesListLonglineCatchId(config.getSpeciesListLonglineCatchId()); + speciesListConfiguration.setSpeciesListLonglineDepredatorId(config.getSpeciesListLonglineDepredatorId()); + speciesListConfiguration.setSpeciesListLonglineEncounterId(config.getSpeciesListLonglineEncounterId()); + speciesListConfiguration.setSpeciesListSeineNonTargetCatchId(config.getSpeciesListSeineNonTargetCatchId()); + speciesListConfiguration.setSpeciesListSeineObjectObservedSpeciesId(config.getSpeciesListSeineObjectObservedSpeciesId()); + speciesListConfiguration.setSpeciesListSeineObjectSchoolEstimateId(config.getSpeciesListSeineObjectSchoolEstimateId()); + speciesListConfiguration.setSpeciesListSeineSchoolEstimateId(config.getSpeciesListSeineSchoolEstimateId()); + speciesListConfiguration.setSpeciesListSeineTargetCatchId(config.getSpeciesListSeineTargetCatchId()); + + ObserveServiceInitializer observeServiceInitializer = ObserveServiceInitializer.create( + locale, + referentialLocale, + tmpDirectory, + speciesListConfiguration, + configurationAndConnection); + + return observeServiceInitializer; + } + + protected void fireOpening() { + ObserveSwingDataSourceEvent evt = new ObserveSwingDataSourceEvent(this); + for (ObserveSwingDataSourceListener listener : getObserveSwingDataSourceListener()) { + listener.onOpening(evt); + } + } + + protected void fireOpened() { + ObserveSwingDataSourceEvent evt = new ObserveSwingDataSourceEvent(this); + for (ObserveSwingDataSourceListener listener : getObserveSwingDataSourceListener()) { + listener.onOpened(evt); + } + } + + protected void fireClosing() { + ObserveSwingDataSourceEvent evt = new ObserveSwingDataSourceEvent(this); + for (ObserveSwingDataSourceListener listener : getObserveSwingDataSourceListener()) { + listener.onClosing(evt); + } + } + + protected void fireClosed() { + ObserveSwingDataSourceEvent evt = new ObserveSwingDataSourceEvent(this); + for (ObserveSwingDataSourceListener listener : getObserveSwingDataSourceListener()) { + listener.onClosed(evt); + } + } + + protected void checkIsOpen() { + Preconditions.checkState(isOpen(), "Connection is not open"); + } + + protected void checkIsNotAlreadyOpen() { + Preconditions.checkState(!isOpen(), "Connection is already open"); + } + + protected void checkIsNotOpen() { + Preconditions.checkState(!isOpen(), "Connection is open"); + } + + private <S extends ObserveService> S newService(Class<S> serviceType) { + + ObserveServiceInitializer observeServiceInitializer = getObserveServiceInitializer(); + + ObserveServiceMainFactory serviceFactory = ObserveServiceMainFactory.get(); + + S service = serviceFactory.newService(observeServiceInitializer, serviceType); + return service; + } + + @Override + public SqlScriptProducerService newSqlScriptProducerService() { + return newService(SqlScriptProducerService.class); + } + + @Override + public ValidateService newValidateService() { + return newService(ValidateService.class); + } + + @Override + public ReportService newReportService() { + return newService(ReportService.class); + } + + @Override + public PingService newPingService() { + return newService(PingService.class); + } + + @Override + public ReplicateTripService newReplicateTripService() { + return newService(ReplicateTripService.class); + } + + @Override + public ConsolidateDataService newConsolidateDataService() { + return newService(ConsolidateDataService.class); + } + + @Override + public UnidirectionalReferentialSynchronizeLocalService newUnidirectionalReferentialSynchronizeLocalService() { + return newService(UnidirectionalReferentialSynchronizeLocalService.class); + } + + @Override + public DataSynchronizeService newDataSynchronizeService() { + return newService(DataSynchronizeService.class); + } + + @Override + public ReferentialSynchronizeService newReferentialSynchronizeService() { + return newService(ReferentialSynchronizeService.class); + } + + @Override + public ReferentialSynchronizeDiffService newReferentialSynchronizeDiffService() { + return newService(ReferentialSynchronizeDiffService.class); + } + + @Override + public DataSourceService newDataSourceService() { + return newService(DataSourceService.class); + } + + @Override + public ReferentialService newReferentialService() { + return newService(ReferentialService.class); + } + + @Override + public TripSeineService newTripSeineService() { + return newService(TripSeineService.class); + } + + @Override + public RouteService newRouteService() { + return newService(RouteService.class); + } + + @Override + public FloatingObjectService newFloatingObjectService() { + return newService(FloatingObjectService.class); + } + + @Override + public ActivitySeineService newActivitySeineService() { + return newService(ActivitySeineService.class); + } + + @Override + public SetSeineService newSetSeineService() { + return newService(SetSeineService.class); + } + + @Override + public TripLonglineService newTripLonglineService() { + return newService(TripLonglineService.class); + } + + @Override + public ActivityLonglineService newActivityLonglineService() { + return newService(ActivityLonglineService.class); + } + + @Override + public ActivitySeineObservedSystemService newActivitySeineObservedSystemService() { + return newService(ActivitySeineObservedSystemService.class); + } + + @Override + public SetLonglineGlobalCompositionService newSetLonglineGlobalCompositionService() { + return newService(SetLonglineGlobalCompositionService.class); + } + + @Override + public SetLonglineDetailCompositionService newSetLonglineDetailCompositionService() { + return newService(SetLonglineDetailCompositionService.class); + } + + @Override + public TransmittingBuoyOperationService newTransmittingBuoyOperationService() { + return newService(TransmittingBuoyOperationService.class); + } + + @Override + public BranchlineService newBranchlineService() { + return newService(BranchlineService.class); + } + + @Override + public SetLonglineCatchService newSetLonglineCatchService() { + return newService(SetLonglineCatchService.class); + } + + @Override + public ActivityLongLineEncounterService newActivityLongLineEncounterService() { + return newService(ActivityLongLineEncounterService.class); + } + + @Override + public TripLonglineGearUseService newTripLonglineGearUseService() { + return newService(TripLonglineGearUseService.class); + } + + @Override + public ActivityLongLineSensorUsedService newActivityLongLineSensorUsedService() { + return newService(ActivityLongLineSensorUsedService.class); + } + + @Override + public TdrService newTdrService() { + return newService(TdrService.class); + } + + @Override + public TripSeineGearUseService newTripSeineGearUseService() { + return newService(TripSeineGearUseService.class); + } + + @Override + public NonTargetCatchService newNonTargetCatchService() { + return newService(NonTargetCatchService.class); + } + + @Override + public NonTargetSampleService newNonTargetSampleService() { + return newService(NonTargetSampleService.class); + } + + @Override + public ObjectObservedSpeciesService newObjectObservedSpeciesService() { + return newService(ObjectObservedSpeciesService.class); + } + + @Override + public ObjectSchoolEstimateService newObjectSchoolEstimateService() { + return newService(ObjectSchoolEstimateService.class); + } + + @Override + public SchoolEstimateService newSchoolEstimateService() { + return newService(SchoolEstimateService.class); + } + + @Override + public TargetCatchService newTargetCatchService() { + return newService(TargetCatchService.class); + } + + @Override + public TargetSampleService newTargetSampleService() { + return newService(TargetSampleService.class); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/constants/ConnexionStatus.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/constants/ConnexionStatus.java new file mode 100644 index 0000000..603da1d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/constants/ConnexionStatus.java @@ -0,0 +1,66 @@ +/* + * #%L + * ObServe :: Business + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.db.constants; + +import static org.nuiton.i18n.I18n.n; + +/** + * Pour caractériser l'état d'une connexion à un service de persistance. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public enum ConnexionStatus { + + /** lorsque la connexion n'as pas encore ete testee */ + UNTESTED( + n("observe.storage.connexionStatut.untested"), + n("observe.storage.connexionStatut.untested.description") + ), + /** lorsque le test de connexion a abouti */ + SUCCESS( + n("observe.storage.connexionStatut.success"), + n("observe.storage.connexionStatut.success.description") + ), + /** lorsque le test de connexion a echoue */ + FAILED( + n("observe.storage.connexionStatut.failed"), + n("observe.storage.connexionStatut.failed.description") + ); + + private final String label; + + private final String description; + + ConnexionStatus(String label, String description) { + this.label = label; + this.description = description; + } + + public String getLabel() { + return label; + } + + public String getDescription() { + return description; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/constants/CreationMode.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/constants/CreationMode.java new file mode 100644 index 0000000..e9c8c4a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/constants/CreationMode.java @@ -0,0 +1,108 @@ +/* + * #%L + * ObServe :: Business + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.db.constants; + +import fr.ird.observe.services.dto.DataSourceCreateConfigurationDto; + +import static org.nuiton.i18n.I18n.n; + +/** + * Pour caractériser comment créer une base locale. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public enum CreationMode { + + /** creer une nouvelle base locale vide */ + EMPTY( + n("observe.storage.creationMode.empty"), + n("observe.storage.creationMode.empty.description") + ), + /** creer une nouvelle base a partir du dump embarque */ + IMPORT_INTERNAL_DUMP( + n("observe.storage.creationMode.internalDump"), + n("observe.storage.creationMode.internalDump.description") + ), + /** creer une nouvelle base a partir d'un dump sur fs */ + IMPORT_EXTERNAL_DUMP( + n("observe.storage.creationMode.externalDump"), + n("observe.storage.creationMode.externalDump.description") + ), + /** + * creer une nouvelle base vide et importer le referentiel via une base + * locale. + */ + IMPORT_LOCAL_STORAGE( + n("observe.storage.creationMode.importLocalStorage"), + n("observe.storage.creationMode.importLocalStorage.description") + ), + /** + * creer une nouvelle base vide et importer le referentiel via une base + * distante. + */ + IMPORT_REMOTE_STORAGE( + n("observe.storage.creationMode.importRemoteStorage"), + n("observe.storage.creationMode.importRemoteStorage.description") + ), + /** + * creer une nouvelle base vide et importer le referentiel via une base + * distante. + */ + IMPORT_SERVER_STORAGE( + n("observe.storage.creationMode.importServerStorage"), + n("observe.storage.creationMode.importServerStorage.description") + ); + + private final String label; + + private final String description; + + CreationMode(String label, String description) { + this.label = label; + this.description = description; + } + + public String getLabel() { + return label; + } + + public String getDescription() { + return description; + } + + public static CreationMode valueOf(DataSourceCreateConfigurationDto createConfigurationDto) { + CreationMode result = EMPTY; + + if (createConfigurationDto != null) { + if (createConfigurationDto.isImportData()) { + result = IMPORT_INTERNAL_DUMP; + } else if (createConfigurationDto.isImportDatabase()) { + result = IMPORT_REMOTE_STORAGE; + } else if (createConfigurationDto.isImportReferential()) { + result = IMPORT_EXTERNAL_DUMP; + } + } + + return result; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/constants/DataContextType.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/constants/DataContextType.java new file mode 100644 index 0000000..06c4857 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/constants/DataContextType.java @@ -0,0 +1,331 @@ +/* + * #%L + * ObServe :: Business + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.db.constants; + +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.services.dto.longline.ActivityLonglineDto; +import fr.ird.observe.services.dto.longline.SetLonglineDto; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.services.dto.seine.FloatingObjectDto; +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.services.dto.seine.SetSeineDto; +import fr.ird.observe.services.dto.seine.TripSeineDto; + +/** + * Les types de données connues par le {@link DataContext}. + * + * Chaque constant permet de récupérer des données du context de données. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public enum DataContextType { + + Program(ProgramDto.class, DataContext.PROPERTY_OPEN_PROGRAM) { + @Override + public boolean isOpen(DataContext context) { + return context.isOpenProgram(); + } + + @Override + public String getOpenId(DataContext context) { + return context.getOpenProgramId(); + } + + @Override + public void setOpenId(DataContext dataContext, String id) { + dataContext.setOpenProgramId(id); + } + + @Override + public String getSelectedId(DataContext context) { + return context.getSelectedProgramId(); + } + + @Override + public void setSelectedId(DataContext context, String id) { + context.setSelectedProgramId(id); + } + }, + + TripSeine(TripSeineDto.class, DataContext.PROPERTY_OPEN_TRIP) { + @Override + public boolean isOpen(DataContext context) { + return context.isOpenTripSeine(); + } + + @Override + public String getOpenId(DataContext context) { + return context.getOpenTripSeineId(); + } + + @Override + public void setOpenId(DataContext dataContext, String id) { + dataContext.setOpenTripSeineId(id); + } + + @Override + public String getSelectedId(DataContext context) { + return context.getSelectedTripSeineId(); + } + + @Override + public void setSelectedId(DataContext context, String id) { + context.setSelectedTripId(id); + } + }, + + TripLongline(TripLonglineDto.class, DataContext.PROPERTY_OPEN_TRIP) { + @Override + public boolean isOpen(DataContext context) { + return context.isOpenTripLongline(); + } + + @Override + public String getOpenId(DataContext context) { + return context.getOpenTripLonglineId(); + } + + @Override + public void setOpenId(DataContext dataContext, String id) { + dataContext.setOpenTripLonglineId(id); + } + + @Override + public String getSelectedId(DataContext context) { + return context.getSelectedTripLonglineId(); + } + + @Override + public void setSelectedId(DataContext context, String id) { + context.setSelectedTripId(id); + } + }, + + Route(RouteDto.class, DataContext.PROPERTY_OPEN_ROUTE) { + @Override + public boolean isOpen(DataContext context) { + return context.isOpenRoute(); + } + + @Override + public String getOpenId(DataContext context) { + return context.getOpenRouteId(); + } + + @Override + public void setOpenId(DataContext dataContext, String id) { + dataContext.setOpenRouteId(id); + } + + @Override + public String getSelectedId(DataContext context) { + return context.getSelectedRouteId(); + } + + @Override + public void setSelectedId(DataContext context, String id) { + context.setSelectedRouteId(id); + } + }, + + ActivitySeine(ActivitySeineDto.class, DataContext.PROPERTY_OPEN_ACTIVITY) { + @Override + public boolean isOpen(DataContext context) { + return context.isOpenActivityLongline(); + } + + @Override + public String getOpenId(DataContext context) { + return context.getOpenActivitySeineId(); + } + + @Override + public void setOpenId(DataContext dataContext, String id) { + dataContext.setOpenActivitySeineId(id); + } + + @Override + public String getSelectedId(DataContext context) { + return context.getSelectedActivitySeineId(); + } + + @Override + public void setSelectedId(DataContext context, String id) { + context.setSelectedActivityId(id); + } + }, + + ActivityLongline(ActivityLonglineDto.class, DataContext.PROPERTY_OPEN_ACTIVITY) { + @Override + public boolean isOpen(DataContext context) { + return context.isOpenActivityLongline(); + } + + @Override + public String getOpenId(DataContext context) { + return context.getOpenActivityLonglineId(); + } + + @Override + public void setOpenId(DataContext dataContext, String id) { + dataContext.setOpenActivityLonglineId(id); + } + + @Override + public String getSelectedId(DataContext context) { + return context.getSelectedActivityLonglineId(); + } + + @Override + public void setSelectedId(DataContext context, String id) { + context.setSelectedActivityId(id); + } + }, + + SetSeine(SetSeineDto.class, DataContext.PROPERTY_OPEN_SET) { + @Override + public boolean isOpen(DataContext context) { + return context.isOpenSetSeine(); + } + + @Override + public String getOpenId(DataContext context) { + return context.getOpenSetSeineId(); + } + + @Override + public void setOpenId(DataContext dataContext, String id) { + dataContext.setOpenSetSeineId(id); + } + + @Override + public String getSelectedId(DataContext context) { + return context.getSelectedSetSeineId(); + } + + @Override + public void setSelectedId(DataContext context, String id) { + context.setSelectedSetId(id); + } + }, + + SetLongline(SetLonglineDto.class, DataContext.PROPERTY_OPEN_SET) { + @Override + public boolean isOpen(DataContext context) { + return context.isOpenSetLongline(); + } + + @Override + public String getOpenId(DataContext context) { + return context.getOpenSetLonglineId(); + } + + @Override + public void setOpenId(DataContext dataContext, String id) { + dataContext.setOpenSetLonglineId(id); + } + + @Override + public String getSelectedId(DataContext context) { + return context.getSelectedSetLonglineId(); + } + + @Override + public void setSelectedId(DataContext context, String id) { + context.setSelectedSetId(id); + } + }, + + FloatingObject(FloatingObjectDto.class, null) { + @Override + public String getSelectedId(DataContext context) { + return context.getSelectedFloatingObjectId(); + } + + @Override + public void setSelectedId(DataContext context, String id) { + context.setSelectedFloatingObjectId(id); + } + }; + + private final Class<?> type; + + private final String openProperty; + + DataContextType(Class<?> type, String openProperty) { + this.type = type; + this.openProperty = openProperty; + } + + public boolean acceptType(Class<?> type) { + return type.equals(getType()); + } + + public boolean acceptId0(String id) { + return id.startsWith(getType().getName()); + } + + public Class<?> getType() { + return type; + } + + public String getOpenProperty() { + return openProperty; + } + + public boolean canOpen() { + return openProperty != null; + } + + public boolean isOpen(DataContext context) { + return false; + } + + public String getOpenId(DataContext context) { + return null; + } + + public abstract String getSelectedId(DataContext context); + + public abstract void setSelectedId(DataContext context, String id); + + public static DataContextType acceptId(String s) { + DataContextType result = null; + for (DataContextType type : DataContextType.values()) { + + String[] entityFullClass = s.split("#")[0].split("\\."); + String typeName = type.getType().getSimpleName(); + if (typeName.startsWith(entityFullClass[entityFullClass.length - 1])) { + result = type; + break; + } + } + return result; + } + + public void setOpenId(DataContext dataContext, String id) { + // rien a faire par defaut + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/constants/DbMode.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/constants/DbMode.java new file mode 100644 index 0000000..28cc939 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/constants/DbMode.java @@ -0,0 +1,70 @@ +/* + * #%L + * ObServe :: Business + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.db.constants; + +import static org.nuiton.i18n.I18n.n; + +/** + * Pour caractériser le type de connexion requis. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public enum DbMode { + /** Pour utiliser une base locale */ + USE_LOCAL( + n("observe.storage.dbMode.useLocal"), + n("observe.storage.dbMode.useLocal.description") + ), + /** Pour creer une base locale */ + CREATE_LOCAL( + n("observe.storage.dbMode.createLocal"), + n("observe.storage.dbMode.createLocal.description") + ), + /** Pour utiliser une base distante */ + USE_REMOTE( + n("observe.storage.dbMode.useRemote"), + n("observe.storage.dbMode.useRemote.description") + ), + /** Pour utiliser une base via un serveur web distant */ + USE_SERVER( + n("observe.storage.dbMode.useServer"), + n("observe.storage.dbMode.useServer.description") + ); + + private final String label; + + private final String description; + + DbMode(String label, String description) { + this.label = label; + this.description = description; + } + + public String getLabel() { + return label; + } + + public String getDescription() { + return description; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/event/ObserveSwingDataSourceEvent.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/event/ObserveSwingDataSourceEvent.java new file mode 100644 index 0000000..23240e8 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/event/ObserveSwingDataSourceEvent.java @@ -0,0 +1,83 @@ +/* + * #%L + * ObServe :: Business + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.db.event; + +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; + +import java.util.EventObject; + +/** + * Les évènements produits lors des changements du cycle de vie d'une source + * de données. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ObserveSwingDataSourceEvent extends EventObject { + + private static final long serialVersionUID = 1L; + + /** an extra message to be used when using {@link ObserveSwingDataSourceListener#onNewMessage(ObserveSwingDataSourceEvent)}. */ + protected String message; + + public enum MessageLevel { + FATAL, + ERROR, + WARN, + INFO, + DEBUG, + TRACE + } + + protected MessageLevel messageLevel; + + /** + * Constructs a prototypical Event. + * + * @param source The object on which the Event initially occurred. + * @throws IllegalArgumentException if source is null. + */ + public ObserveSwingDataSourceEvent(ObserveSwingDataSource source) { + super(source); + } + + public ObserveSwingDataSourceEvent(ObserveSwingDataSource source, + String message, + MessageLevel messageLevel) { + super(source); + this.message = message; + this.messageLevel = messageLevel; + } + + @Override + public ObserveSwingDataSource getSource() { + return (ObserveSwingDataSource) super.getSource(); + } + + public String getMessage() { + return message; + } + + public MessageLevel getMessageLevel() { + return messageLevel; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/event/ObserveSwingDataSourceListener.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/event/ObserveSwingDataSourceListener.java new file mode 100644 index 0000000..ef9a02d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/event/ObserveSwingDataSourceListener.java @@ -0,0 +1,75 @@ +/* + * #%L + * ObServe :: Business + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.db.event; + +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; + +import java.util.EventListener; + +/** + * Le contrat d'un listener sur une source de données. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public interface ObserveSwingDataSourceListener extends EventListener { + + + /** + * Déclanché avant l'ouverture d'un service (i.e au debut de la méthode + * {@link ObserveSwingDataSource#open()}). + * + * @param event l'evenement de pre-ouverture + */ + void onOpening(ObserveSwingDataSourceEvent event); + + /** + * Déclanché apres une ouverture d'un service (i.e à la fin de la méthode + * {@link ObserveSwingDataSource#open()}). + * + * @param event l'evenement d'ouverture + */ + void onOpened(ObserveSwingDataSourceEvent event); + + /** + * Déclanché avant la fermeture d'un service (i.e au avant la méthode {@link + * ObserveSwingDataSource#close()}). + * + * @param event l'evenement de pre-fermeture + */ + void onClosing(ObserveSwingDataSourceEvent event); + + /** + * Déclanché apres la fermeture d'un service (i.e apres de la méthode {@link + * ObserveSwingDataSource#close()}). + * + * @param event l'evenement de fermeture + */ + void onClosed(ObserveSwingDataSourceEvent event); + + /** + * Déclanché pour envoyer un nouveau message. + * + * @param event l'evenement de message + */ + void onNewMessage(ObserveSwingDataSourceEvent event); +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/event/ObserveSwingDataSourceListenerAdapter.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/event/ObserveSwingDataSourceListenerAdapter.java new file mode 100644 index 0000000..d458fe2 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/db/event/ObserveSwingDataSourceListenerAdapter.java @@ -0,0 +1,56 @@ +/* + * #%L + * ObServe :: Business + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.db.event; + +/** + * Un adapteur de {@link ObserveSwingDataSourceListener}. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ObserveSwingDataSourceListenerAdapter implements ObserveSwingDataSourceListener { + + @Override + public void onOpening(ObserveSwingDataSourceEvent event) { + // ne fait rien + } + + @Override + public void onOpened(ObserveSwingDataSourceEvent event) { + // ne fait rien + } + + @Override + public void onClosing(ObserveSwingDataSourceEvent event) { + // ne fait rien + } + + @Override + public void onClosed(ObserveSwingDataSourceEvent event) { + // ne fait rien + } + + @Override + public void onNewMessage(ObserveSwingDataSourceEvent event) { + // ne fait rien + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/package.html b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/package.html new file mode 100644 index 0000000..0b39016 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/package.html @@ -0,0 +1,27 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<html> +<body> +<h1>Paquetage principal fr.ird.observe.application.swing</h1> +TODO +</body> +</html> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/ObserveCommon.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/ObserveCommon.jcss new file mode 100644 index 0000000..f75db75 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/ObserveCommon.jcss @@ -0,0 +1,94 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +JToolBar { + borderPainted:false; + floatable:false; + opaque:false; +} + +JTabbedPane { + _notBlocking: true; +} + +JXDatePicker { + formats:{"dd/MM/yyyy"}; +} + +DateTimeEditor { + dateFormat:{"dd/MM/yyyy"}; + showTimeEditorSlider: {config.isShowTimeEditorSlider()}; + _selectOnFocus: true; +} + +TimeEditor { + showTimeEditorSlider: {config.isShowTimeEditorSlider()}; + _selectOnFocus: true; +} + +NumberEditor { + autoPopup:{config.isAutoPopupNumberEditor()}; + showPopupButton:{config.isShowNumberEditorButton()}; + showReset:true; +} + +CoordinatesEditor { + format: {org.nuiton.jaxx.widgets.gis.CoordinateFormat.dms}; +} + +FilterableDoubleList { + showDecorator:false; + showReset:true; + showSelectPopupEnabled: true; + filterable:false; + _notBlocking: true; +} + +BeanComboBox { + showReset:true; +} + +BlockingLayerUI { + acceptedComponentTypes: {javax.swing.JScrollBar.class}; +} + +.resetButton { + opaque:false; + actionIcon:combobox-reset; + focusTraversalKeysEnabled:false; + focusable:false; +} + +.integer { + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + useFloat:false; +} + +.float { + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL3_PATTERN}; + useFloat:true; +} + +.float2 { + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL2_PATTERN}; + useFloat:true; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/ObserveMainUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/ObserveMainUI.jaxx new file mode 100644 index 0000000..c4b7ace --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/ObserveMainUI.jaxx @@ -0,0 +1,341 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<JFrame id='mainFrame' width='800' height='800' + onWindowClosing='new fr.ird.observe.application.swing.ui.actions.CloseApplicationAction(this).run()'> + + <import> + fr.ird.observe.application.swing.ObserveSwingApplicationContext + fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig + fr.ird.observe.application.swing.db.DataContext + + fr.ird.observe.services.dto.referential.ProgramDto + fr.ird.observe.services.dto.seine.ActivitySeineDto + fr.ird.observe.services.dto.seine.RouteDto + fr.ird.observe.services.dto.seine.SetSeineDto + fr.ird.observe.services.dto.seine.TripSeineDto + fr.ird.observe.services.dto.constants.ReferentialLocale + + fr.ird.observe.application.swing.ui.actions.shared.ReOpenUIAction + + fr.ird.observe.application.swing.ui.admin.AdminStep + fr.ird.observe.application.swing.ui.actions.ChangeStorageAction + fr.ird.observe.application.swing.ui.actions.CloseStorageAction + fr.ird.observe.application.swing.ui.actions.ReloadStorageAction + fr.ird.observe.application.swing.ui.actions.SaveStorageToFileAction + fr.ird.observe.application.swing.ui.actions.ShowStorageInfoAction + fr.ird.observe.application.swing.ui.content.ContentUIManager + fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper + fr.ird.observe.application.swing.ui.tree.NavigationTreeCellRenderer + + jaxx.runtime.swing.CardLayout2 + jaxx.runtime.swing.CardLayout2Ext + jaxx.runtime.swing.BlockingLayerUI + jaxx.runtime.swing.StatusMessagePanel + jaxx.runtime.validator.swing.SwingValidatorMessageTableModel + + org.jdesktop.swingx.JXTitledPanel + + java.util.Locale + + javax.swing.BoxLayout + javax.swing.JComponent + javax.swing.UIManager + javax.swing.Icon + + <!-- FIXME --> + <!--fr.ird.observe.services.dto.TripDto--> + <!--fr.ird.observe.services.dto.ActivityDto--> + <!--fr.ird.observe.services.dto.SetDto--> + </import> + + <ObserveUIMode id='mode' javaBean='ObserveUIMode.NO_DB'/> + + <Boolean id='h2WebServer' javaBean='Boolean.FALSE'/> + + <ChangeStorageAction id="changeStorageAction" constructorParams='this'/> + <CloseStorageAction id="closeStorageAction" constructorParams='this'/> + <ReloadStorageAction id="reloadStorageAction" constructorParams='this'/> + <SaveStorageToFileAction id="saveStorageToFileAction" constructorParams='this'/> + <ShowStorageInfoAction id="showStorageInfoAction" constructorParams='this'/> + + + <ContentUIManager id='contentUIManager' initializer='ObserveSwingApplicationContext.get().getContentUIManager()'/> + + <JPopupMenu id='scopeUpPopup'/> + <JPopupMenu id='scopeDownPopup'/> + <JPopupMenu id='navigationPopup'> + <JMenuItem id="navigationNoAction"/> + <JMenu id="navigationMoveAction"/> + <JMenuItem id="navigationOpenAction"/> + <JMenuItem id="navigationCloseAction"/> + <JMenuItem id="navigationDeleteAction"/> + </JPopupMenu> + + <ObserveSwingApplicationConfig id='config' initializer='ObserveSwingApplicationContext.get().getConfig()'/> + + <ObserveMainUIHandler id='handler' initializer='getContextValue(ObserveMainUIHandler.class)'/> + + <ObserveTreeHelper id='treeHelper' initializer='getContextValue(ObserveTreeHelper.class)'/> + + <DataContext id='dataContext' initializer='ObserveSwingApplicationContext.get().getDataContext()'/> + + <Boolean id='mainFromSynchro' javaBean='false'/> + + <Boolean id='busy' javaBean='false'/> + + <CardLayout2 id='contentLayout'/> + + <CardLayout2Ext id='bodyLayout' constructorParams='this, "body"'/> + + <BlockingLayerUI id='busyBlockLayerUI'/> + + <script><![CDATA[ + +protected Icon updateStorageSatutIcon(boolean isOpened) { + return getHandler().updateStorageSatutIcon(this, isOpened); +} + +protected String updateStorageSatutText(boolean isOpened) { + return getHandler().updateStorageSatutText(this, isOpened); +} + +protected String updateStorageStatutToolTipText(boolean isOpened) { + return getHandler().updateStorageStatutToolTipText(this, isOpened); +} + +@Override +public void dispose() { + log.debug("dispose main ui " + this); + destroy(); + super.dispose(); +} + +public void destroy() { + log.info("destroy ui " + getName()); + UIHelper.destroy(this); +} + +@Override +protected void finalize() throws Throwable { + super.finalize(); + destroy(); +} + +void $afterCompleteSetup() { + getHandler().$afterCompleteSetup(this); +} + +]]> + </script> + + <!-- menu --> + <JMenuBar id='menu'> + + <JMenu id='menuFile'> + <JMenuItem id='menuFileReloadApplication'/> + <JMenuItem id='menuFileCloseApplication'/> + </JMenu> + + <JMenu id='menuStorage'> + <JMenuItem id='menuStorageChange'/> + <JMenuItem id='menuStorageReload'/> + <JMenuItem id='menuStorageClose'/> + <JMenuItem id='menuStorageInfo'/> + <JSeparator/> + <JMenuItem id='menuStorageLoadFromFile'/> + <JMenuItem id='menuStorageSaveToFile'/> + <JMenuItem id='menuStorageStartServerMode'/> + </JMenu> + + <JMenu id='menuActions'> + <JMenuItem id='menuActionsSynchronize'/> + <JMenuItem id='menuActionsReferentialSynchro'/> + <JMenuItem id='menuActionsDataSynchro'/> + <JSeparator/> + <JMenuItem id='menuActionsValidateData'/> + <JMenuItem id='menuActionsExportData'/> + <JMenuItem id='menuActionsReport'/> + <JMenuItem id='menuActionsConsolidate'/> + </JMenu> + + <JMenu id='menuNavigation'> + <JMenuItem id='menuNavigationProgram' + onActionPerformed="getTreeHelper().selectOpenNode(ProgramDto.class)"/> + <JMenuItem id='menuNavigationTrip' + onActionPerformed="getTreeHelper().selectOpenNode(TripSeineDto.class)"/> + <JMenuItem id='menuNavigationRoute' + onActionPerformed="getTreeHelper().selectOpenNode(RouteDto.class)"/> + <JMenuItem id='menuNavigationActivity' + onActionPerformed="getTreeHelper().selectOpenNode(ActivitySeineDto.class)"/> + <JMenuItem id='menuNavigationSet' + onActionPerformed="getTreeHelper().selectOpenNode(SetSeineDto.class)"/> + <JSeparator/> + <JMenuItem id='menuNavigationReferentiel' + onActionPerformed='getTreeHelper().selectNode("observe.common.referentiel")'/> + </JMenu> + <JMenu id='menuConfiguration'> + <JMenu id='menuLanguage'> + <JMenu id='menuApplicationLanguage'> + <JMenuItem id='menuApplicationLanguageUK'/> + <JMenuItem id='menuApplicationLanguageFR'/> + <JMenuItem id='menuApplicationLanguageES'/> + </JMenu> + <JMenu id='menuDbLanguage'> + <JMenuItem id='menuDbLanguageUK'/> + <JMenuItem id='menuDbLanguageFR'/> + <JMenuItem id='menuDbLanguageES'/> + </JMenu> + </JMenu> + <JSeparator/> + <JMenuItem id='menuFileConfiguration'/> + <JMenuItem id='menuConfigurationReloadDefault'/> + <JMenuItem id='menuConfigurationReloadResources'/> + </JMenu> + + <JMenu id='menuHelp'> + <JMenuItem id='menuHelpSite'/> + <JMenuItem id='menuHelpAbout'/> + </JMenu> + + <JToolBar id='toolbar'> + + <javax.swing.Box.Filler + constructorParams='UIHelper.newMinDimension(), UIHelper.newMinDimension(), UIHelper.newMaxXDimension()'/> + <!-- pour afficher le status du service de persistance et changer de + service de persistance --> + <JButton id='storageStatus' + enabled='{getHandler().acceptMode(getMode(), !isBusy(), ObserveUIMode.DB, ObserveUIMode.NO_DB)}' + onActionPerformed="JComponent c = (JComponent) event.getSource(); storageStatusPopup.show(c, 0, c.getHeight());"/> + </JToolBar> + + </JMenuBar> + + <!-- contenu principal --> + + <JPanel id='body' constraints="BorderLayout.CENTER" decorator='boxed'> + + <JPanel constraints='"invisible"'> + + <JPopupMenu id='storageStatusPopup'> + <JMenuItem id='storageStatusChange'/> + <JMenuItem id='storageStatusReload'/> + <JMenuItem id='storageStatusClose'/> + <JMenuItem id='storageStatusInfo'/> + </JPopupMenu> + </JPanel> + + <!-- ecran lorsqu'aucune source de données n'est chargée --> + + <JLabel id="modeNoDb" constraints='ObserveUIMode.NO_DB.name()'/> + + <!-- ecran avec une navigation sur les données d'une source --> + + <JSplitPane id='splitpane' constraints="ObserveUIMode.DB.name()"> + + <!-- left : navigation --> + + <JXTitledPanel id='navigationView'> + <JScrollPane id='navigationScrollPane'> + <JTree id="navigation"/> + </JScrollPane> + </JXTitledPanel> + + <!-- right : (content + messages) --> + + <JSplitPane id='splitpane2'> + + <!-- right up : content --> + + <JPanel id="content"/> + + <!-- right down : message view --> + <JXTitledPanel id='messageView'> + <JScrollPane> + <JTable id='errorTable'/> + </JScrollPane> + </JXTitledPanel> + + </JSplitPane> + </JSplitPane> + + <!-- ecran pour les opérations de synchronisation et validation --> + + <JXTitledPanel id='synchroWizard' constraints='ObserveUIMode.SYNCHRO.name()'/> + + <!-- ecran du mode serveur --> + + <JXTitledPanel id='serverMode' constraints='ObserveUIMode.SERVER.name()'> + <JPanel layout='{new BorderLayout()}'> + + <JPanel layout='{new GridLayout(0,1)}' constraints='BorderLayout.NORTH'> + + <JLabel id='serverModeInfo'/> + + <Table id='serverModeParameters' fill="both"> + <row> + <cell> + <JLabel id="serverModeURLLabel"/> + </cell> + <cell weightx='1' fill="both"> + <JTextField id='serverModeURL'/> + </cell> + </row> + <row> + <cell> + <JLabel id="serverModeLoginLabel"/> + </cell> + <cell> + <JTextField id='serverModeLogin'/> + </cell> + </row> + <row> + <cell> + <JLabel id="serverModePasswordLabel"/> + </cell> + <cell> + <JTextField id='serverModePassword'/> + </cell> + </row> + + </Table> + + </JPanel> + + <JPanel constraints='BorderLayout.CENTER' layout='{new GridLayout(0,1)}'> + <JButton id="stopServerMode"/> + <JSeparator/> + <JButton id="startH2WebServer"/> + <JButton id="stopH2WebServer"/> + + </JPanel> + + </JPanel> + + </JXTitledPanel> + + </JPanel> + + <!-- status message bar --> + <StatusMessagePanel id='status' constraints="BorderLayout.SOUTH"/> + +</JFrame> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/ObserveMainUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/ObserveMainUI.jcss new file mode 100644 index 0000000..f38666b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/ObserveMainUI.jcss @@ -0,0 +1,474 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +JToolBar { + borderPainted: false; + floatable: false; + opaque: false; +} + +JSplitPane { + oneTouchExpandable: true; + continuousLayout: false; + dividerSize: 6; +} + +#mainFrame { + defaultCloseOperation: "do_nothing_on_close"; + iconImage: {SwingUtil.createImageIcon("logo-OT_web.png").getImage()}; +} + +#menu { + enabled: {!isBusy()}; +} + +#navigationNoAction { + text: "observe.navigationMenu.noAction"; + toolTipText: "observe.navigationMenu.noAction"; + enabled: false; +} + +// trip menu + +#navigationOpenAction { + action: {new fr.ird.observe.application.swing.ui.actions.shared.ReOpenUIAction(this)}; +} + +#navigationCloseAction { + action: {new fr.ird.observe.application.swing.ui.actions.shared.CloseOpenUIAction(this)}; +} + +#navigationDeleteAction { + action: {new fr.ird.observe.application.swing.ui.actions.shared.DeleteDataUIAction(this)}; +} + +#menuFile { + text: "observe.menu.file"; + mnemonic: F; + enabled: {getHandler().acceptMode(getMode(), !isBusy(), !isMainFromSynchro(), ObserveUIMode.NO_DB, ObserveUIMode.DB)}; +} + +#menuFileConfiguration { + action: {new fr.ird.observe.application.swing.ui.actions.ShowConfigAction(this)}; +} + +#menuConfiguration { + text: "observe.menu.configuration"; + toolTipText: "observe.menu.configuration.tip"; + mnemonic: C; + enabled: {getHandler().acceptMode(getMode(), !isBusy(), !isMainFromSynchro(), ObserveUIMode.DB, ObserveUIMode.NO_DB)}; +} + +#menuLanguage { + text: "observe.menu.locale"; + toolTipText: "observe.menu.locale"; + actionIcon: "translate"; + mnemonic: L; + enabled: {getHandler().acceptMode(getMode(), !isBusy(), !isMainFromSynchro(), ObserveUIMode.DB, ObserveUIMode.NO_DB)}; +} + +#menuApplicationLanguage { + text: "observe.menu.application.locale"; + toolTipText: "observe.menu.application.locale"; + actionIcon: "application-translate"; + mnemonic: A; +} + +#menuApplicationLanguageFR { + action: {new fr.ird.observe.application.swing.ui.actions.ChangeApplicationLanguageAction(this, Locale.FRANCE, t("observe.action.locale.fr"), t("observe.action.locale.fr.tip"))}; + enabled: {!getHandler().acceptLocale(getConfig().getLocale(), "fr_FR")}; +} + +#menuApplicationLanguageUK { + action: {new fr.ird.observe.application.swing.ui.actions.ChangeApplicationLanguageAction(this, Locale.UK, t("observe.action.locale.uk"), t("observe.action.locale.uk.tip"))}; + enabled: {!getHandler().acceptLocale(getConfig().getLocale(), "en_GB")}; +} + +#menuApplicationLanguageES { + action: {new fr.ird.observe.application.swing.ui.actions.ChangeApplicationLanguageAction(this, new Locale("es","ES"), t("observe.action.locale.es"), t("observe.action.locale.es.tip"))}; + enabled: {!getHandler().acceptLocale(getConfig().getLocale(), "es_ES")}; +} + +#menuDbLanguage { + text: "observe.menu.db.locale"; + toolTipText: "observe.menu.db.locale"; + actionIcon: "db-translate"; + mnemonic: D; +} + +#menuDbLanguageFR { + action: {new fr.ird.observe.application.swing.ui.actions.ChangeDbLanguageAction(this, ReferentialLocale.FR, t("observe.action.locale.fr"), t("observe.action.db.locale.fr.tip"))}; + enabled: {!getHandler().acceptLocale(getConfig().getDbLocale(), "fr_FR")}; +} + +#menuDbLanguageUK { + action: {new fr.ird.observe.application.swing.ui.actions.ChangeDbLanguageAction(this, ReferentialLocale.UK, t("observe.action.locale.uk"), t("observe.action.db.locale.uk.tip"))}; + enabled: {!getHandler().acceptLocale(getConfig().getDbLocale(), "en_GB")}; +} + +#menuDbLanguageES { + action: {new fr.ird.observe.application.swing.ui.actions.ChangeDbLanguageAction(this, ReferentialLocale.ES, t("observe.action.locale.es"), t("observe.action.db.locale.es.tip"))}; + enabled: {!getHandler().acceptLocale(getConfig().getDbLocale(), "es_ES")}; +} + +#menuConfigurationReloadDefault { + action: {new fr.ird.observe.application.swing.ui.actions.ReloadDefaultConfigurationAction(this)}; +} + +#menuConfigurationReloadResources { + action: {new fr.ird.observe.application.swing.ui.actions.ReloadResourcesAction(this)}; + visible: {getConfig().isDevMode()}; +} + +#menuFileReloadApplication { + action: {new fr.ird.observe.application.swing.ui.actions.ReloadApplicationAction(this)}; +} + +#menuFileCloseApplication { + action: {new fr.ird.observe.application.swing.ui.actions.CloseApplicationAction(this)}; +} + +#menuStorage { + text: "observe.menu.storage"; + mnemonic: S; + enabled: {getHandler().acceptMode(getMode(), !isBusy(), !isMainFromSynchro(), ObserveUIMode.DB, ObserveUIMode.NO_DB)}; +} + +#menuStorageInfo { + action: {new fr.ird.observe.application.swing.ui.actions.ShowStorageInfoAction(this)}; +} + +#reloadStorageAction { + enabled: {getHandler().acceptMode(getMode(), getConfig().isMainStorageOpened(), ObserveUIMode.DB)}; +} + +#closeStorageAction { + enabled: {getHandler().acceptMode(getMode(), getConfig().isMainStorageOpened(), ObserveUIMode.DB)}; +} + +#saveStorageToFileAction { + enabled: {getHandler().acceptMode(getMode(), getConfig().isMainStorageOpened(), ObserveUIMode.DB)}; +} + +#menuStorageReload { + action: {reloadStorageAction}; + enabled: {reloadStorageAction.isEnabled()}; +} + +#menuStorageClose { + action: {closeStorageAction}; + enabled: {closeStorageAction.isEnabled()}; +} + +#menuStorageStartServerMode { + action: {new fr.ird.observe.application.swing.ui.actions.StartServerModeAction(this)}; + visible: {getHandler().acceptMode(getMode(), getConfig().isLocalStorageExist() && !isBusy() && !isMainFromSynchro(), ObserveUIMode.NO_DB)}; +} + +#menuStorageChange { + action: {changeStorageAction}; +} + +#menuStorageLoadFromFile { + action: {new fr.ird.observe.application.swing.ui.actions.ImportStorageFromFileAction(this)}; + enabled: {getHandler().acceptMode(getMode(), ObserveUIMode.DB, ObserveUIMode.NO_DB)}; +} + +#menuStorageSaveToFile { + action: {saveStorageToFileAction}; + enabled: {saveStorageToFileAction.isEnabled()}; +} + +#menuActions { + text: "observe.menu.actions"; + mnemonic: A; + enabled: {getHandler().acceptMode(getMode(), !isBusy() && !isMainFromSynchro(), ObserveUIMode.DB, ObserveUIMode.NO_DB)}; +} + +#menuActionsDataSynchro { + action: {new fr.ird.observe.application.swing.ui.actions.LaunchAdminAction(this, AdminStep.DATA_SYNCHRONIZE)}; +} + +#menuActionsReferentialSynchro { + action: {new fr.ird.observe.application.swing.ui.actions.LaunchAdminAction(this, AdminStep.REFERENTIAL_SYNCHRONIZE)}; +} + +#menuActionsSynchronize { + action: {new fr.ird.observe.application.swing.ui.actions.LaunchAdminAction(this, AdminStep.SYNCHRONIZE)}; +} + +#menuActionsValidateData { + action: {new fr.ird.observe.application.swing.ui.actions.LaunchAdminAction(this, AdminStep.VALIDATE)}; +} + +#menuActionsExportData { + action: {new fr.ird.observe.application.swing.ui.actions.LaunchAdminAction(this, AdminStep.EXPORT_DATA)}; +} + +#menuActionsReport { + action: {new fr.ird.observe.application.swing.ui.actions.LaunchAdminAction(this, AdminStep.REPORT)}; +} + +#menuActionsConsolidate { + action: {new fr.ird.observe.application.swing.ui.actions.LaunchAdminAction(this, AdminStep.CONSOLIDATE)}; +} + +#menuNavigation { + text: "observe.menu.navigation"; + mnemonic: n; + enabled: {getHandler().acceptMode(getMode(), !isBusy(), ObserveUIMode.DB)}; +} + +#menuNavigationProgram { + text: "observe.content.action.goto.open.program.short"; + toolTipText: "observe.content.action.goto.open.program.tip"; + icon: "navigation.fr.ird.observe.services.dto.referential.ProgramDto"; + mnemonic: P; + enabled: {getDataContext().isOpenProgram()}; +} + +#menuNavigationTrip { + text: "observe.content.action.goto.open.trip.short"; + toolTipText: "observe.content.action.goto.open.trip.tip"; + icon: "navigation.fr.ird.observe.services.dto.TripDto"; + mnemonic: M; + enabled: {getDataContext().isOpenTrip()}; +} + +#menuNavigationRoute { + text: "observe.content.action.goto.open.route.short"; + toolTipText: "observe.content.action.goto.open.route.tip"; + icon: "navigation.fr.ird.observe.services.dto.seine.RouteDto"; + mnemonic: R; + enabled: {getDataContext().isOpenRoute()}; +} + +#menuNavigationActivity { + text: "observe.content.action.goto.open.activity.short"; + toolTipText: "observe.content.action.goto.open.activity.tip"; + icon: "navigation.fr.ird.observe.services.dto.ActivityDto"; + mnemonic: A; + enabled: {getDataContext().isOpenActivity()}; +} + +#menuNavigationSet { + text: "observe.content.action.goto.open.set.short"; + toolTipText: "observe.content.action.goto.open.set.tip"; + icon: "navigation.fr.ird.observe.services.dto.SetDto"; + mnemonic: C; + enabled: {getDataContext().isOpenSet()}; +} + +#menuNavigationReferentiel { + text: "observe.action.goto.referentiel.short"; + toolTipText: "observe.action.goto.referentiel.tip"; + icon: "navigation.referentiel"; + mnemonic: f; +} + +#menuHelp { + text: "observe.menu.help"; + mnemonic: e; + enabled: {!isBusy()}; +} + +#menuHelpHelp { + text: "observe.action.help"; + toolTipText: "observe.action.help.tip"; + actionIcon: "help"; + mnemonic: e; +} + +#menuHelpSite { + action: {new fr.ird.observe.application.swing.ui.actions.GotoSiteAction(this)}; +} + +#menuHelpAbout { + action: {new fr.ird.observe.application.swing.ui.actions.ShowAboutAction(this)}; +} + +#storageStatus { + opaque: false; + borderPainted: false; + focusable: false; + toolTipText: {updateStorageStatutToolTipText(getConfig().isMainStorageOpened())}; + text: {updateStorageSatutText(getConfig().isMainStorageOpened())}; + icon: {updateStorageSatutIcon(getConfig().isMainStorageOpened())}; + _localIcon: {SwingUtil.getUIManagerActionIcon("db-local")}; + _remoteIcon: {SwingUtil.getUIManagerActionIcon("db-remote")}; + _serverIcon: {SwingUtil.getUIManagerActionIcon("db-server")}; + _noneIcon: {SwingUtil.getUIManagerActionIcon("db-none")}; +} + +#storageStatusInfo { + action: {showStorageInfoAction}; +} + +#storageStatusChange { + action: {changeStorageAction}; +} + +#storageStatusClose { + action: {closeStorageAction}; + enabled: {closeStorageAction.isEnabled()}; +} + +#storageStatusReload { + action: {reloadStorageAction}; + enabled: {reloadStorageAction.isEnabled()}; +} + +#closeHelp { + action: {new fr.ird.observe.application.swing.ui.actions.CloseHelpAction(this)}; + borderPainted: false; + rolloverEnabled: false; + focusable: false; +} + +#errorTable { + rowSelectionAllowed: true; + autoCreateRowSorter: true; + autoResizeMode: 2; + cellSelectionEnabled: false; + selectionMode: 0; + minimumSize: {UIHelper.newMinDimension()}; + model: {getContextValue(SwingValidatorMessageTableModel.class)}; +} + +#busyBlockLayerUI { + useIcon: false; + blockingColor: {UIManager.getColor("BlockingLayerUI.blockingColor")}; + block: {isBusy()}; + acceptedComponentNames: {UIHelper.ACCEPTABLE_COMPONENTS}; +} + +#navigation { + rootVisible: false; + largeModel: true; + minimumSize: {UIHelper.newMinDimension()}; + font-size:11; + model: {getTreeHelper().getModel()}; + selectionModel: {getTreeHelper().newNavigationSelectionModel()}; + cellRenderer: {new NavigationTreeCellRenderer()}; +} + +#splitpane { + orientation: {JSplitPane.HORIZONTAL_SPLIT}; + resizeWeight: 1.0; +} + +#splitpane2 { + orientation: {JSplitPane.VERTICAL_SPLIT}; + resizeWeight: 0.80; +} + +#contentLayout { + useOnlyVisibleComponentDimension: true; +} + +#navigationView { + title: "observe.view.navigation"; +} + +#messageView { + title: "observe.view.message"; +} + +#modeNoDb { + text: "observe.message.db.none.loaded"; + horizontalAlignment: center; +} + +#serverMode { + title: "observe.view.server"; +} + +#serverModeInfo { + text: "observe.message.server.info"; + horizontalAlignment: center; +} + +#serverModeURLLabel { + text: "observe.message.h2.server.url"; + labelFor: {serverModeURL}; +} + +#serverModeURL { + editable: false; +} + +#serverModeLoginLabel { + text: "observe.message.h2.server.login"; + labelFor: {serverModeLogin}; +} + +#serverModeLogin { + editable: false; +} + +#serverModePasswordLabel { + text: "observe.message.h2.server.password"; + labelFor: {serverModePassword}; +} + +#serverModePassword { + editable: false; +} + +#startH2WebServer{ + action: {new fr.ird.observe.application.swing.ui.actions.StartH2WebServerAction(this)}; + enabled: {!isH2WebServer()}; +} + +#stopH2WebServer{ + action: {new fr.ird.observe.application.swing.ui.actions.StopH2WebServerAction(this)}; + enabled: {isH2WebServer()}; +} + +#stopServerMode { + action: {new fr.ird.observe.application.swing.ui.actions.StopServerModeAction(this)}; +} + +#serverModeParameters { + border: {new TitledBorder(t("observe.title.h2.server.parameters"))}; +} + +#bodyLayout { + selected: {getMode().name()}; +} +#body { + layout: {bodyLayout}; +} + +#content { + layout: {contentLayout}; +} + +#status { + showBusy: {true}; + busy: {isBusy()}; +} + +#toolbar { + layout: {new BoxLayout(toolbar, 0)}; + enabled: {!isBusy()}; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/ObserveMainUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/ObserveMainUIHandler.java new file mode 100755 index 0000000..8dfbb8c --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/ObserveMainUIHandler.java @@ -0,0 +1,512 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.AbstractObserveDto; +import fr.ird.observe.services.dto.constants.ReferentialLocale; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.ContentUI; +import fr.ird.observe.application.swing.ui.content.ContentUIManager; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; +import fr.ird.observe.application.swing.ui.content.ObserveContentUI; +import fr.ird.observe.application.swing.ui.tree.ObserveNavigationTreeShowPopupAction; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import fr.ird.observe.application.swing.ui.util.ObserveSwingValidatorMessageTableModel; +import fr.ird.observe.application.swing.ui.util.ObserveValidatorMessageTableRenderer; +import jaxx.runtime.JAXXContext; +import jaxx.runtime.context.DefaultApplicationContext; +import jaxx.runtime.context.JAXXInitialContext; +import jaxx.runtime.swing.ErrorDialogUI; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; +import jaxx.runtime.validator.swing.SwingValidatorUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.i18n.I18n; + +import javax.swing.Icon; +import javax.swing.SwingUtilities; +import javax.swing.event.TreeExpansionEvent; +import javax.swing.event.TreeSelectionEvent; +import javax.swing.event.TreeSelectionListener; +import javax.swing.event.TreeWillExpandListener; +import javax.swing.tree.ExpandVetoException; +import javax.swing.tree.TreePath; +import java.awt.Cursor; +import java.util.ArrayList; +import java.util.List; +import java.util.Locale; + +import static org.nuiton.i18n.I18n.t; + +/** + * Le handler de l'ui principale. + * + * @author Tony Chemit - chemit@codelutin.com + * @see ObserveMainUI + * @since 1.0 + */ +@DefaultApplicationContext.AutoLoad +public class ObserveMainUIHandler { + + /** Logger */ + private static final Log log = LogFactory.getLog(ObserveMainUIHandler.class); + + public void changeNavigationNode(ObserveMainUI ui, TreeSelectionEvent event) { + + + ObserveSwingDataSource source = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); + if (source == null || !source.isOpen()) { + + // no open data source + if (log.isDebugEnabled()) { + log.debug("No open Data source."); + } + return; + } + if (ui.getNavigation().isSelectionEmpty()) { + if (log.isDebugEnabled()) { + log.debug("No selection, do nothing..."); + } + return; + } + + TreePath path = event.getPath(); + ObserveNode node = (ObserveNode) path.getLastPathComponent(); + ContentUIManager manager = ui.getContentUIManager(); + + // obtain the ui type to show + Class<? extends ObserveContentUI<?>> uiClass = manager.convertNodeToContentUI(node); + if (log.isDebugEnabled()) { + log.debug("new selected path = " + node + ", ui = " + uiClass); + } + + if (uiClass == null) { + + // pas d'ui trouvé, on ne fait donc rien + return; + } + + ui.setBusy(true); + + try { + + doOpencontent(ui, path, uiClass); + + } catch (Exception e) { + UIHelper.handlingError(e); + } finally { + ui.setBusy(false); + String params; + if (node.isStringNode()) { + params = t(node.getId()); + } else { + params = t(DecoratorService.getEntityLabel(node.getInternalClass())); + } + ui.getStatus().setStatus(t("observe.action.open.screen", params)); + } + } + + public void doOpencontent(ObserveMainUI ui, + TreePath path, + Class<? extends ObserveContentUI<?>> uiClass) { + + ContentUIManager manager = ui.getContentUIManager(); + + // compute the selected ids to put in data context + Object[] nodes = path.getPath(); + List<String> ids = new ArrayList<>(); + for (Object o : nodes) { + ObserveNode n = (ObserveNode) o; + + if (n.isStringNode() || n.isReferentielNode() || n.isRoot() || !n.isDataNode()) { + continue; + } + ids.add(n.getId()); + } + + if (log.isDebugEnabled()) { + log.debug("new selected ids from tree = " + ids); + } + String[] selectedIds = ids.toArray(new String[ids.size()]); + + // update selected ids in data context + DataContext context = ui.getDataContext(); + context.populateSelectedIds(selectedIds); + + // on recherche l'ui (voir si elle existe déjà) + ObserveContentUI<?> content = manager.getContent(uiClass); + + if (content == null) { + + content = manager.createContent(uiClass); + } + + // on ouvre l'écran + manager.openContent(content); + } + + /** + * Methode pour initialiser l'ui principale sans l'afficher. + * + * @param context le context applicatif + * @param config la configuration a utiliser + * @return l'ui instancie et initialisee mais non visible encore + */ + public ObserveMainUI initUI(ObserveSwingApplicationContext context, ObserveSwingApplicationConfig config) { + + SwingValidatorMessageTableModel errorModel = + new ObserveSwingValidatorMessageTableModel(); + + DecoratorService decoratorService = context.getDecoratorService(); + + boolean reloadDecorators = false; + Locale currentLocale = I18n.getDefaultLocale(); +// if (!config.getLocale().equals( +// I18n.getStore().getLanguage().getLocale())) { + Locale configurationLocale = config.getLocale(); + if (!configurationLocale.equals(currentLocale)) { + if (log.isInfoEnabled()) { + log.info("re-init I18n with locale " + configurationLocale); + } + I18n.setDefaultLocale(configurationLocale); +// I18n.init(configurationLocale); + reloadDecorators = true; + } + if (!config.getDbLocale().equals( + decoratorService.getReferentialLocale().getLocale())) { + if (log.isInfoEnabled()) { + log.info("re-init db with locale " + config.getDbLocale()); + } + decoratorService.setReferentialLocale(ReferentialLocale.valueOf(config.getDbLocale())); + + reloadDecorators = true; + } + + if (reloadDecorators) { + if (log.isInfoEnabled()) { + log.info("reload decorators"); + } + decoratorService.reload(); + } + + ObserveTreeHelper treeHelper = new ObserveTreeHelper(); + ObserveSwingDataSource source = context.getDataSourcesManager().getMainDataSource(); + + boolean open = context.getDataContext().getEnabled(); + if (open) { + treeHelper.createModel(source); + } else { + treeHelper.createEmptyModel(); + } + + JAXXInitialContext tx = new JAXXInitialContext(); + + tx.add(context).add(treeHelper).add(errorModel); + + // show main ui + ObserveMainUI ui = new ObserveMainUI(tx); + ui.setUndecorated(config.isFullScreen()); + + String title = t("observe.title.welcome.admin"); + title += " v " + config.getVersion(); + ui.setTitle(title); + + context.setMainUI(ui); + + ErrorDialogUI.init(ui); + + // set fullscreen propery on main ui + ui.getGraphicsConfiguration().getDevice().setFullScreenWindow(config.isFullScreen() ? ui : null); + + // on enregistre les actions communes à toutes les écrans d'édition + // les bouttons utilisant ces actions seront automatiquement + // chargés (à partir des actions) lors de l'ouverture des ui + // et mis à jour + + context.registerShareActions(); + + new ObserveNavigationTreeShowPopupAction(treeHelper, ui.getNavigationScrollPane(), ui.getNavigationPopup()); + + return ui; + } + + public static final String H2_SERVER_URL_PATTERN = "jdbc:h2:%s/%s/obstuna"; + + public static void restartEdit() { + ContentUI<?> selectedUI = ObserveSwingApplicationContext.get().getContentUIManager().getSelectedContentUI(); + if (selectedUI == null) { + + // pas d'écran selectionne + return; + } + ContentUIModel<? extends AbstractObserveDto> model = selectedUI.getModel(); + if (!model.isEditable()) { + + // modele non editable + return; + } + + ContentMode contentMode = model.getMode(); + if (ContentMode.UPDATE != contentMode) { + + // ecran non en mode mis a jour + return; + } + + if (log.isDebugEnabled()) { + log.debug("Will restart edit for " + selectedUI.getName()); + } + selectedUI.restartEdit(); + + } + + /** + * Permet de recharger l'ui principale et de changer de le mode + * d'affichage. + * + * @param rootContext le contexte applicatif + * @param config la configuration a utiliser + */ + protected void reloadUI(ObserveSwingApplicationContext rootContext, ObserveSwingApplicationConfig config) { + + // must remove all properties listener on config + config.removeJaxxPropertyChangeListener(); + + // scan main ui + ObserveMainUI ui = getUI(rootContext); + + ObserveSwingDataSource mainStorage = rootContext.getDataSourcesManager().getMainDataSource(); + + ObserveUIMode oldMode = null; + String[] ids = null; + if (ui != null) { + + oldMode = ui.getMode(); + + ids = ui.getTreeHelper().getSelectedIds(); + + ErrorDialogUI.init(null); + + rootContext.removeMainUI(); + + ui.dispose(); + + ui.setVisible(false); + + System.runFinalization(); + } + + ui = initUI(rootContext, config); + + if (oldMode == null) { + if (mainStorage == null) { + oldMode = ObserveUIMode.NO_DB; + + } else { + oldMode = ObserveUIMode.DB; + } + } + + ui.setMode(oldMode); + + if (oldMode == ObserveUIMode.DB) { + + // on conserve les noeuds a reselectionner + rootContext.setNodesToReselect(ids); + + // selection du noeud d'ouverture (le noeud precedemment selectionne, + // ou le noeud le plus ouvert + // ou le premier program si aucune donnée ouverte) + ui.getTreeHelper().selectInitialNode(); + } + + // show ui + UIHelper.setMainUIVisible(ui); + } + + protected Icon updateStorageSatutIcon(ObserveMainUI ui, boolean isOpened) { + Icon icon; + + if (ui.getConfig().isMainStorageOpened()) { + + ObserveSwingDataSource service = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); + + if (service.isLocal()) { + icon = (Icon) ui.storageStatus.getClientProperty("localIcon"); + } else if (service.isRemote()) { + icon = (Icon) ui.storageStatus.getClientProperty("remoteIcon"); + } else { + icon = (Icon) ui.storageStatus.getClientProperty("serverIcon"); + } + } else { + icon = (Icon) ui.storageStatus.getClientProperty("noneIcon"); + } + return icon; + } + + protected String updateStorageSatutText(ObserveMainUI ui, boolean isOpened) { + String text; + if (ui.getConfig().isMainStorageOpened()) { + ObserveSwingDataSource source = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); + text = source.getLabel(); + } else { + text = t("observe.message.db.none.loaded"); + } + return text; + } + + protected String updateStorageStatutToolTipText(ObserveMainUI ui, boolean isOpened) { + String text; + if (ui.getConfig().isMainStorageOpened()) { + ObserveSwingDataSource source = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); + text = t("observe.message.loaded.tip", source.getLabel()); + } else { + text = t("observe.message.db.none.loaded.tip"); + } + return text; + } + + public boolean acceptMode(ObserveUIMode mode, ObserveUIMode... modes) { + return acceptMode(mode, true, modes); + } + + public boolean acceptMode(ObserveUIMode mode, boolean condition, ObserveUIMode... modes) { + if (condition) { + for (ObserveUIMode m : modes) { + if (m.equals(mode)) { + return true; + } + } + } + return false; + } + + public boolean acceptMode(ObserveUIMode mode, boolean notBusy, boolean condition, ObserveUIMode... modes) { + if (notBusy && condition) { + for (ObserveUIMode m : modes) { + if (m.equals(mode)) { + return true; + } + } + } + return false; + } + + public boolean rejectMode(ObserveUIMode mode, ObserveUIMode... modes) { + for (ObserveUIMode m : modes) { + if (m.equals(mode)) { + return false; + } + } + return true; + } + + public boolean acceptLocale(Locale l, String expected) { + return l != null && l.toString().equals(expected); + } + + public ObserveMainUI getUI(JAXXContext context) { + if (context instanceof ObserveMainUI) { + return (ObserveMainUI) context; + } + ObserveMainUI ui = ObserveSwingApplicationContext.get().getMainUI(); + return ui; + } + + protected void $afterCompleteSetup(final ObserveMainUI ui) { + + ui.getStatus().init(); + + // ajout d'un ecouteur sur la navigation pour toujours mettre la scrollbar + // tout à droite a chaque selection + TreeSelectionListener listener; + listener = e -> { + changeNavigationNode(ui, e); + SwingUtilities.invokeLater(() -> { + ui.getNavigationScrollPane().getHorizontalScrollBar().setValue(0); + ui.getSplitpane2().resetToPreferredSizes(); + }); + }; + TreeWillExpandListener veteobableTreeWillExpand = new TreeWillExpandListener() { + @Override + public void treeWillExpand(TreeExpansionEvent event) { + } + + @Override + public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException { + + // le seul posant problème est la fermeture d'un noeud parent + // du noeud courant : cela va changer la selection + ObserveNode selectedNode = ui.getTreeHelper().getSelectedNode(); + if (selectedNode == null) { + // pas de noeud selectionne + return; + } + + ObserveNode o = (ObserveNode) event.getPath().getLastPathComponent(); + if (selectedNode.equals(o) || !selectedNode.isNodeAncestor(o)) { + return; + } + boolean canChange = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); + if (!canChange) { + throw new ExpandVetoException(event, "Can not collapse node " + event.getPath()); + } + } + }; + + ui.getTreeHelper().setUI(ui.getNavigation(), true, true, listener, veteobableTreeWillExpand); + + SwingValidatorUtil.installUI(ui.getErrorTable(), new ObserveValidatorMessageTableRenderer()); + + // installation layer de blocage en mode busy + UIHelper.setLayerUI(ui.getBody(), ui.getBusyBlockLayerUI()); + + // ecoute des changements de l'état busy + ui.addPropertyChangeListener(ObserveMainUI.PROPERTY_BUSY, evt -> { + Boolean newvalue = (Boolean) evt.getNewValue(); + updateBusyState(ui, newvalue != null && newvalue); + }); + } + + protected void updateBusyState(ObserveMainUI ui, boolean busy) { + if (busy) { + // ui bloquee + if (log.isDebugEnabled()) { + log.debug("block ui in busy mode"); + } + ui.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); + } else { + // ui debloquee + if (log.isDebugEnabled()) { + log.debug("unblock ui in none busy mode"); + } + ui.setCursor(Cursor.getDefaultCursor()); + } + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/ObserveUICallback.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/ObserveUICallback.java new file mode 100644 index 0000000..a7dd4b6 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/ObserveUICallback.java @@ -0,0 +1,115 @@ +package fr.ird.observe.application.swing.ui; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveRunner; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.ui.actions.CloseApplicationAction; +import fr.ird.observe.application.swing.ui.actions.ReloadStorageAction; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.ImageIcon; + +import static org.nuiton.i18n.I18n.n; + +/** + * Définition des callback possibles lors d'une action. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public enum ObserveUICallback implements Runnable { + + application(n("observe.action.reload.application"), + "application-reload") { + @Override + public void run() { + if (log.isInfoEnabled()) { + log.info("will reload application"); + } + ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); + ObserveMainUIHandler handler = new ObserveMainUIHandler(); + ObserveMainUI ui = handler.getUI(context); + + if (log.isDebugEnabled()) { + log.debug("Ask to reload."); + } + ObserveRunner.getRunner().setReload(true); + new CloseApplicationAction(ui).run(); + } + }, + ui(n("observe.action.reload.ui"), + "ui-reload") { + @Override + public void run() { + if (log.isInfoEnabled()) { + log.info("will reload ui"); + } + ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); + ObserveMainUIHandler handler = new ObserveMainUIHandler(); + ObserveMainUI ui = handler.getUI(context); + ObserveSwingApplicationConfig config = ui.getConfig(); + handler.reloadUI(context, config); + } + }, + db(n("observe.action.reload.storage"), + "db-reload") { + @Override + public void run() { + if (log.isInfoEnabled()) { + log.info("will reload db"); + } + + ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); + ObserveMainUIHandler handler = new ObserveMainUIHandler(); + ObserveMainUI ui = handler.getUI(context); + new ReloadStorageAction(ui).run(); +// handler.launchReloadStorage(ui); + } + }; + + /** Logger. */ + private static final Log log = LogFactory.getLog(ObserveUICallback.class); + + private final String label; + + private final String iconPath; + + ObserveUICallback(String label, String iconPath) { + this.iconPath = iconPath; + this.label = label; + + getIcon(); + } + + public ImageIcon getIcon() { + ImageIcon icon = UIHelper.createActionIcon(iconPath); + return icon; + } + + public String getLabel() { + return label; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/ObserveUIMode.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/ObserveUIMode.java new file mode 100644 index 0000000..6ab417e --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/ObserveUIMode.java @@ -0,0 +1,43 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui; + +/** + * Pour caractériser le mode en cours d'utilisation. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public enum ObserveUIMode { + + /** Pas de source de données chargé */ + NO_DB, + + /** Affichage - édition d'une source de données */ + DB, + + /** Pour affiher le mode server */ + SERVER, + + /** Opérations complexes */ + SYNCHRO +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/UIHelper.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/UIHelper.java new file mode 100644 index 0000000..54aea7d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/UIHelper.java @@ -0,0 +1,595 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.ObserveSwingTechnicalException; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.services.dto.DataDto; +import fr.ird.observe.services.dto.DataFileDto; +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.security.InvalidAuthenticationTokenException; +import fr.ird.observe.application.swing.ui.util.table.ObserveBooleanTableCellRenderer; +import jaxx.runtime.FileChooserUtil; +import jaxx.runtime.JAXXObject; +import jaxx.runtime.SwingUtil; +import jaxx.runtime.swing.ErrorDialogUI; +import jaxx.runtime.swing.renderer.DecoratorTableCellRenderer; +import org.apache.commons.io.FileUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.jdesktop.swingx.painter.Painter; +import org.nuiton.decorator.Decorator; + +import javax.swing.JComponent; +import javax.swing.JOptionPane; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JTree; +import javax.swing.SwingUtilities; +import javax.swing.UIDefaults; +import javax.swing.event.HyperlinkEvent; +import javax.swing.table.TableCellEditor; +import javax.swing.table.TableCellRenderer; +import java.awt.Color; +import java.awt.Component; +import java.awt.Desktop; +import java.awt.Toolkit; +import java.awt.datatransfer.Clipboard; +import java.awt.datatransfer.StringSelection; +import java.io.File; +import java.io.IOException; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; + +import static org.nuiton.i18n.I18n.t; + +/** + * Une classe d'aide pour les ui + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class UIHelper extends SwingUtil { + + /** Logger */ + static private final Log log = LogFactory.getLog(UIHelper.class); + + /** + * Pattern to use for short numeric values in editors with max 3 digits. + * + * @since 2.3 + */ + public static final String INT_3_DIGITS_PATTERN = "\\d{0,3}"; + + /** + * Pattern to use for integer numeric values in editors with max 6 digits. + * + * @since 2.3 + */ + public static final String INT_6_DIGITS_PATTERN = "\\d{0,6}"; + + /** + * Pattern to use for integer numeric values in editors with max 7 digits. + * + * @since 2.3 + */ + public static final String INT_7_DIGITS_PATTERN = "\\d{0,7}"; + + /** + * Pattern to use for long numeric values in editors with max 10 digits. + * + * @since 3.7 + */ + public static final String LONG_10_DIGITS_PATTERN = "\\d{0,10}"; + + /** + * Pattern to use for decimal numeric values with 1 decimal digits in + * editors. + * + * @since 2.3 + */ + public static final String DECIMAL1_PATTERN = "\\d{0,6}|\\d{1,6}.\\d{0,1}"; + + /** + * Pattern to use for decimal numeric values with 2 decimal digits in + * editors. + * + * @since 2.3 + */ + public static final String DECIMAL2_PATTERN = "\\d{0,6}|\\d{1,6}.\\d{0,2}"; + + /** + * Pattern to use for decimal numeric values with 3 decimal digits in + * editors. + * + * @since 2.3 + */ + public static final String DECIMAL3_PATTERN = "\\d{0,6}|\\d{1,6}.\\d{0,3}"; + + /** + * Components which must NOT be blocked by any layer in ui. + * + * @since 2.0 + */ + public static final String[] ACCEPTABLE_COMPONENTS = { + // show progress ui in acess import + "showProgressButton", + // copy global progression of resume admin tab to clipboard + "globalProgressionCopyToClipBoard", + // copy progression of any admin tab to clipboard + "progressionTopCopyCliptBoard" + }; + + public static void displayInfo(String text) { + + ObserveMainUI ui = ObserveSwingApplicationContext.get().getMainUI(); + if (ui == null) { + JOptionPane.showMessageDialog(null, text); + } else { + ui.getStatus().setStatus(text); + } + } + + public static void displayWarning(String title, String text) { + + ObserveMainUI ui = ObserveSwingApplicationContext.get().getMainUI(); + JOptionPane.showMessageDialog(ui, text, title, JOptionPane.WARNING_MESSAGE); + + } + + public static int askUser(String title, + String message, + int typeMessage, + Object[] options, + int defaultOption) { + return askUser( + null, + title, + message, + typeMessage, + options, + defaultOption + ); + } + + public static int askUser(Component parent, + String title, + Object message, + int typeMessage, + Object[] options, + int defaultOption) { + if (parent == null) { + ObserveSwingApplicationContext tx = ObserveSwingApplicationContext.get(); + if (tx != null) { + parent = ObserveSwingApplicationContext.get().getMainUI(); + } + } + int response = JOptionPane.showOptionDialog( + parent, + message, + title, + JOptionPane.DEFAULT_OPTION, + typeMessage, + null, + options, + options[defaultOption] + ); + return response; + } + + /** + * Choisir un fichier via un sélecteur graphique de fichiers. + * + * @param parent le component swing appelant le controle + * @param title le titre du dialogue de sélection + * @param buttonLabel le label du boutton d'acceptation + * @param incoming le fichier de base à utilier + * @param filters les filtres + descriptions sur le sélecteur de + * fichiers + * @return le fichier choisi ou le fichier incoming si l'opération a été + * annulée + */ + public static File chooseFile(Component parent, + String title, + String buttonLabel, + File incoming, + String... filters) { + File oldBasedir = FileChooserUtil.getCurrentDirectory(); + if (incoming != null) { + File basedir; + if (incoming.isFile()) { + basedir = incoming.getParentFile(); + } else { + basedir = incoming; + } + if (basedir.exists()) { + FileChooserUtil.setCurrentDirectory(basedir); + } + } + File file = FileChooserUtil.getFile(title, buttonLabel, parent, filters); + if (log.isDebugEnabled()) { + log.debug(title + " : " + file); + } + FileChooserUtil.setCurrentDirectory(oldBasedir); + File result = file == null ? incoming : file; + return result; + } + + /** + * Choisir un répertoire via un sélecteur graphique de fichiers. + * + * @param parent le component swing appelant le controle + * @param title le titre de la boite de dialogue de sléection + * @param buttonLabel le label de l'action d'acceptation + * @param incoming le fichier de base à utiliser + * @return le répertoire choisi ou le répertoire incoming si l'opération a + * été annulée + */ + public static File chooseDirectory(Component parent, + String title, + String buttonLabel, + File incoming) { + File oldBasedir = FileChooserUtil.getCurrentDirectory(); + if (incoming != null) { + File basedir; + if (incoming.isFile()) { + basedir = incoming.getParentFile(); + } else { + basedir = incoming; + } + if (basedir.exists()) { + FileChooserUtil.setCurrentDirectory(basedir); + } + } + String file = FileChooserUtil.getDirectory(parent, title, buttonLabel); + if (log.isDebugEnabled()) { + log.debug(title + " : " + file); + } + FileChooserUtil.setCurrentDirectory(oldBasedir); + return file == null ? incoming : new File(file); + } + + /** + * Ouvre une demande de confirmation, avant suppression d'une entité. + * + * @param <E>le type de l'entité à supprimer + * @param parent le component graphique demande l'action + * @param beanClass le tyê de l'entité à supprimer + * @param bean l'entité à supprimer + * @return {@code true} si l'utilisateur a confitmé la suppression, + * {@code false} sinon. + */ + public static <E extends IdDto> boolean confirmForEntityDelete( + JAXXObject parent, + Class<E> beanClass, + E bean) { + + return confirmForEntityDelete(parent, beanClass, bean, null); + } + + /** + * Ouvre une demande de confirmation, avant suppression d'une entité. + * + * @param <E> le type de l'entité à supprimer + * @param parent le component graphique demande l'action + * @param beanClass le tyê de l'entité à supprimer + * @param bean l'entité à supprimer + * @param extraMessage un message supplémentaire a ajouter + * @return {@code true} si l'utilisateur a confitmé la suppression, + * {@code false} sinon. + */ + public static <E extends IdDto> boolean confirmForEntityDelete( + JAXXObject parent, + Class<E> beanClass, + E bean, + String extraMessage) { + ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); + + if (parent == null) { + // on cherche l'ui principale + parent = mainUI; + } + + if (mainUI != null) { + mainUI.setBusy(true); + } + DecoratorService decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); + Decorator<E> decorator = decoratorService.getDecoratorByType(beanClass); + String beanStr; + String messageDelete; + String type = DecoratorService.getEntityLabel(beanClass); + type = t(type); + + if (bean == null || bean.getId() == null || decorator == null) { + // delete new entity + messageDelete = t("observe.message.delete.new", type); + } else { + try { + // delete existing entity + beanStr = decorator.toString(bean); + messageDelete = t("observe.message.delete", type, beanStr); + } catch (Exception e) { + messageDelete = t("observe.message.delete.new", type); + } + } + + if (extraMessage != null) { + messageDelete += '\n' + extraMessage; + } + + int response = askUser((Component) parent, + t("observe.title.delete"), + messageDelete, + JOptionPane.WARNING_MESSAGE, + new Object[]{t("observe.choice.confirm.delete"), + t("observe.choice.cancel")}, + 1); + if (mainUI != null) { + mainUI.setBusy(true); + } + return response == 0; + } + + public static boolean confirmOverwriteFileIfExist(Component parent, File file) { + boolean write = true; + if (file.exists()) { + write = UIHelper.askUser( + parent, + t("observe.common.saveFile.overwrite.title"), + t("observe.common.saveFile.overwrite"), + JOptionPane.OK_CANCEL_OPTION, + new Object[] { + t("observe.common.saveFile.overwrite.ok"), + t("observe.common.saveFile.overwrite.cancel")}, + 1) == 0; + } + + return write; + } + + + public static DecoratorTableCellRenderer newDecorateTableCellRenderer( + TableCellRenderer renderer, Class<?> entityClass) { + Decorator<?> decorator = ObserveSwingApplicationContext.get().getDecoratorService().getDecoratorByType(entityClass); + return new DecoratorTableCellRenderer(renderer, decorator); + } + + public static DecoratorTableCellRenderer newDecorateTableCellRenderer( + TableCellRenderer renderer, Class<?> entityClass, String context) { + Decorator<?> decorator = ObserveSwingApplicationContext.get().getDecoratorService().getDecoratorByType(entityClass, context); + return new DecoratorTableCellRenderer(renderer, decorator); + } + + public static <T extends DataDto> DecoratorTableCellRenderer newDataReferenceDecorateTableCellRenderer(TableCellRenderer renderer, + Class<T> entityClass, + String context) { + Decorator<?> decorator = ObserveSwingApplicationContext.get().getDecoratorService().getDataReferenceDecorator(entityClass, context); + return new DecoratorTableCellRenderer(renderer, decorator); + } + + public static <T extends ReferentialDto> DecoratorTableCellRenderer newReferentialReferenceDecorateTableCellRenderer(TableCellRenderer renderer, + Class<T> entityClass) { + Decorator<?> decorator = ObserveSwingApplicationContext.get().getDecoratorService().getReferentialReferenceDecorator(entityClass); + return new DecoratorTableCellRenderer(renderer, decorator); + } + + /** + * Pour trier les types du référentiel selon leur décoration. + * + * @param classes les classes à trier + * @since 1.5 + */ + public static void sortReferentiel(List<Class> classes) { + + Collections.sort(classes, REFERENTIEL_COMPARATOR); + } + + /** + * Copy to clipBoard the content of the given text. + * + * @param text text to copy to clipboard + * @since 2.0 + */ + public static void copyToClipBoard(String text) { + + Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); + if (log.isInfoEnabled()) { + log.info("Put in clipboard :\n" + text); + } + StringSelection selection = new StringSelection(text); + clipboard.setContents(selection, selection); + } + + public static void setMainUIVisible(final ObserveMainUI ui) { + + // force le redimensionnement du splitpane + ui.getSplitpane().revalidate(); + + // force le redimensionnement du splitpane2 + ui.getSplitpane2().revalidate(); + + // affichage de l'interface graphique + SwingUtilities.invokeLater(() -> ui.setVisible(true)); + } + + public static <E extends IdDto> E getEntity(List<E> list, E entity) { + for (E e : list) { + if (e.getId().equals(entity.getId())) { + return e; + } + } + return null; + } + + public static final Comparator<Class> REFERENTIEL_COMPARATOR = new Comparator<Class>() { + + @Override + public int compare(Class o1, Class o2) { + String s1 = t(DecoratorService.getEntityLabel(o1)); + String s2 = t(DecoratorService.getEntityLabel(o2)); + return s1.compareTo(s2); + } + }; + + /** + * Open a link coming from a {@link HyperlinkEvent}. + * + * And try to open the link if an url in a browser. + * + * @param he the event to treate + * @since 1.6.0 + */ + public static void openLink(HyperlinkEvent he) { + if (he.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { + + if (Desktop.isDesktopSupported()) { + try { + URL u = he.getURL(); + if (u.getProtocol().equalsIgnoreCase("mailto") || + u.getProtocol().equalsIgnoreCase("http") || + u.getProtocol().equalsIgnoreCase("ftp") || + u.getProtocol().equalsIgnoreCase("file")) { + Desktop.getDesktop().browse(u.toURI()); + } + } catch (IOException | URISyntaxException e) { + if (log.isErrorEnabled()) { + log.error("Error while opening link", e); + } + } + } + } + } + + public static void stopEditing(JTable table) { + TableCellEditor cellEditor = table.getCellEditor(); + if (cellEditor != null) { + cellEditor.cancelCellEditing(); + } + } + + public static TableCellRenderer newBooleanTableCellRenderer( + TableCellRenderer renderer) { + return new ObserveBooleanTableCellRenderer(renderer); + } + + public static DataFileDto fileToDataFileDto(File file) { + + DataFileDto result = new DataFileDto(); + + try { + + byte[] fileContent = FileUtils.readFileToByteArray(file); + + result.setContent(fileContent); + result.setName(file.getName()); + + } catch (IOException e) { + throw new ObserveSwingTechnicalException("Could not read file: " + file, e); + } + + return result; + } + + public static void handlingError(Exception e) { + handlingError(e.getMessage(), e); + + } + + public static void handlingError(String message, Exception e) { + + if (log.isErrorEnabled()) { + log.error(message, e); + } + + if (containsExceptionInStack(e, InvalidAuthenticationTokenException.class)) { + + ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); + + // on indique que la source de donnée a expiré + context.getDataSourcesManager().getMainDataSource().expired(); + + ObserveMainUI observeMainUI = context.getMainUI(); + + int result = askUser(observeMainUI, + t("observe.storage.server.sessionExpire.title"), + t("observe.storage.server.sessionExpire"), + JOptionPane.OK_CANCEL_OPTION, + new Object[] { + t("observe.storage.server.sessionExpire.reload"), + t("observe.storage.server.sessionExpire.change"), + t("observe.storage.server.sessionExpire.close")}, + 0); + + + // FIXME SBavencoff 23/03/2016 est on sùr que l'erreur proviens du main storage ? + switch (result) { + case 0 : observeMainUI.getReloadStorageAction().run(); break; + case 1 : observeMainUI.getChangeStorageAction().run(); break; + default: observeMainUI.getCloseStorageAction().run(); break; + } + + } else { + ErrorDialogUI.showError(e); + } + + } + + static protected <E extends Throwable> boolean containsExceptionInStack(Throwable e, Class<E> type) { + + if (type.isInstance(e)) { + return true; + } + + while (e.getCause() != null) { + e = e.getCause(); + + if (type.isInstance(e)) { + return true; + } + + } + + return false; + + } + + + public static void initUI(JScrollPane selectedTreePane, JTree tree) { + + // customize tree selection colors + UIDefaults defaults = new UIDefaults(); + + Painter<JComponent> painter = (g, c, w, h) -> g.fillRect(0, 0, w, h); + defaults.put("Tree:TreeCell[Enabled+Selected].backgroundPainter", painter); + defaults.put("Tree:TreeCell[Enabled+Focused].backgroundPainter", painter); + defaults.put("Tree:TreeCell[Focused+Selected].backgroundPainter", painter); + + tree.putClientProperty("Nimbus.Overrides", defaults); + // Fix http://forge.codelutin.com/issues/2781 + selectedTreePane.getViewport().setBackground(Color.WHITE); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/AbstractObserveAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/AbstractObserveAction.java new file mode 100644 index 0000000..a786d1b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/AbstractObserveAction.java @@ -0,0 +1,54 @@ +package fr.ird.observe.application.swing.ui.actions; + +/*- + * #%L + * ObServe :: Application Swing + * %% + * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import javax.swing.AbstractAction; +import javax.swing.Icon; +import java.beans.PropertyChangeListener; + +/** + * Created on 03/11/15. + * + * @author Tony Chemit - chemit@codelutin.com + */ +public abstract class AbstractObserveAction extends AbstractAction { + + private static final long serialVersionUID = 1L; + + protected AbstractObserveAction(String name, Icon icon) { + super(name, icon); + } + + public synchronized void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { + if (changeSupport != null) { + changeSupport.addPropertyChangeListener(propertyName,listener); + } + + } + + public synchronized void removePropertyChangeListener(String propertyName,PropertyChangeListener listener) { + if (changeSupport != null) { + changeSupport.removePropertyChangeListener(propertyName,listener); + } + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ChangeApplicationLanguageAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ChangeApplicationLanguageAction.java new file mode 100644 index 0000000..9e1420a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ChangeApplicationLanguageAction.java @@ -0,0 +1,82 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfigOption; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.ObserveUICallback; +import jaxx.runtime.SwingUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.AbstractAction; +import java.awt.event.ActionEvent; +import java.util.Locale; + +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.13 + */ +public class ChangeApplicationLanguageAction extends AbstractAction { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(ChangeApplicationLanguageAction.class); + + private final ObserveMainUI ui; + + private final Locale newLocale; + + public ChangeApplicationLanguageAction(ObserveMainUI ui, Locale newLocale, String name, String description) { + + super(name, SwingUtil.getUIManagerActionIcon("i18n-" + newLocale.getLanguage())); + this.ui = ui; + this.newLocale = newLocale; + putValue(SHORT_DESCRIPTION, description); + putValue(MNEMONIC_KEY, (int) newLocale.getLanguage().toUpperCase().charAt(0)); + + } + + @Override + public void actionPerformed(ActionEvent event) { + + if (log.isInfoEnabled()) { + log.info("ObServe changing application language..."); + } + boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); + if (canContinue) { + ObserveSwingApplicationConfig config = ui.getConfig(); + + // sauvegarde de la nouvelle locale + config.setOption(ObserveSwingApplicationConfigOption.LOCALE, newLocale); + ObserveUICallback.ui.run(); + } + + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ChangeDbLanguageAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ChangeDbLanguageAction.java new file mode 100644 index 0000000..3f09ff4 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ChangeDbLanguageAction.java @@ -0,0 +1,83 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfigOption; +import fr.ird.observe.services.dto.constants.ReferentialLocale; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.ObserveUICallback; +import jaxx.runtime.SwingUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.AbstractAction; +import java.awt.event.ActionEvent; + +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.13 + */ +public class ChangeDbLanguageAction extends AbstractAction { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(ChangeDbLanguageAction.class); + + private final ObserveMainUI ui; + + private final ReferentialLocale newLocale; + + public ChangeDbLanguageAction(ObserveMainUI ui, ReferentialLocale newLocale, String name, String description) { + + super(name, SwingUtil.getUIManagerActionIcon("i18n-" + newLocale.getLocale().getLanguage())); + this.ui = ui; + this.newLocale = newLocale; + putValue(SHORT_DESCRIPTION, description); + putValue(MNEMONIC_KEY, (int) newLocale.getLocale().getLanguage().toUpperCase().charAt(0)); + + } + + @Override + public void actionPerformed(ActionEvent event) { + + if (log.isInfoEnabled()) { + log.info("ObServe changing db language..."); + } + boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); + if (!canContinue) { + return; + } + ObserveSwingApplicationConfig config = ui.getConfig(); + + // sauvegarde de la nouvelle locale + config.setOption(ObserveSwingApplicationConfigOption.DB_LOCALE, newLocale.getLocale()); + ObserveUICallback.ui.run(); + + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ChangeStorageAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ChangeStorageAction.java new file mode 100644 index 0000000..04590a6 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ChangeStorageAction.java @@ -0,0 +1,97 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.constants.DbMode; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.storage.StorageUILauncher; +import jaxx.runtime.SwingUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.AbstractAction; +import java.awt.event.ActionEvent; +import java.util.EnumSet; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.13 + */ +public class ChangeStorageAction extends AbstractAction { + + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(ChangeStorageAction.class); + + private final ObserveMainUI ui; + + private final Set<DbMode> dbModes; + + private final String title; + + public ChangeStorageAction(ObserveMainUI ui) { + this(ui, null, null); + } + + public ChangeStorageAction(ObserveMainUI ui, Set<DbMode> dbModes, String title) { + + super(t("observe.action.change.storage"), SwingUtil.getUIManagerActionIcon("db-change")); + this.ui = ui; + this.dbModes = dbModes == null ? EnumSet.noneOf(DbMode.class) : dbModes; + this.title = title; + putValue(SHORT_DESCRIPTION, t("observe.action.change.storage.tip")); + putValue(MNEMONIC_KEY, (int) 'C'); + + } + + @Override + public void actionPerformed(ActionEvent e) { + + run(); + + } + + public void run() { + + boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); + if (canContinue) { + + if (log.isInfoEnabled()) { + log.info("Start change storage with dbMode: " + dbModes.stream().map(DbMode::name).collect(Collectors.joining(", "))); + } + + StorageUILauncher.changeStorage(ui, ui, dbModes, t(title)); + + } + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/CloseApplicationAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/CloseApplicationAction.java new file mode 100644 index 0000000..83afbbd --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/CloseApplicationAction.java @@ -0,0 +1,87 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveRunner; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import jaxx.runtime.SwingUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.AbstractAction; +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.13 + */ +public class CloseApplicationAction extends AbstractAction { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(CloseApplicationAction.class); + + private final ObserveMainUI ui; + + public CloseApplicationAction(ObserveMainUI ui) { + + super(t("observe.action.exit"), SwingUtil.getUIManagerActionIcon("exit")); + this.ui = ui; + putValue(SHORT_DESCRIPTION, t("observe.action.exit.tip")); + putValue(MNEMONIC_KEY, (int) 'X'); + + } + + @Override + public void actionPerformed(ActionEvent e) { + + + run(); + } + + public void run() { + + if (log.isInfoEnabled()) { + log.info("ObServe quitting..."); + } + boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); + if (canContinue) { + try { + ui.dispose(); + } finally { + if (log.isDebugEnabled()) { + log.debug("Ask to release runner."); + } + ObserveRunner.unlock(); + } + } + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/CloseHelpAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/CloseHelpAction.java new file mode 100644 index 0000000..f86e48b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/CloseHelpAction.java @@ -0,0 +1,76 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.ObserveUIMode; +import jaxx.runtime.SwingUtil; + +import javax.swing.AbstractAction; +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.13 + */ +public class CloseHelpAction extends AbstractAction { + + private static final long serialVersionUID = 1L; + + private final ObserveMainUI ui; + + public CloseHelpAction(ObserveMainUI ui) { + + super(null, SwingUtil.getUIManagerActionIcon("closeTab")); + this.ui = ui; + putValue(SHORT_DESCRIPTION, t("observe.action.quitHelp.tip")); + putValue(MNEMONIC_KEY, (int) 'F'); + + } + + @Override + public void actionPerformed(ActionEvent event) { + + ObserveUIMode oldMode = ui.getContextValue(ObserveUIMode.class, "oldMode"); + if (oldMode == null) { + + // on regarde si une base est chargee + ObserveSwingDataSource mainStorage = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); + + if (mainStorage == null) { + oldMode = ObserveUIMode.NO_DB; + } else { + oldMode = ObserveUIMode.DB; + } + } + ui.setMode(oldMode); + + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/CloseStorageAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/CloseStorageAction.java new file mode 100644 index 0000000..3a0ea8a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/CloseStorageAction.java @@ -0,0 +1,86 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import jaxx.runtime.SwingUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.13 + */ +public class CloseStorageAction extends AbstractObserveAction { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(CloseStorageAction.class); + + private final ObserveMainUI ui; + + public CloseStorageAction(ObserveMainUI ui) { + + super(t("observe.action.close.storage"), SwingUtil.getUIManagerActionIcon("db-none")); + this.ui = ui; + putValue(SHORT_DESCRIPTION, t("observe.action.close.storage.tip")); + putValue(MNEMONIC_KEY, (int) 'F'); + + } + + @Override + public void actionPerformed(ActionEvent e) { + + run(); + + } + + public void run() { + + boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); + if (canContinue) { + ui.setBusy(true); + + try { + ObserveSwingDataSource source = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); + if (log.isDebugEnabled()) { + log.debug(">>> close main storage " + source); + } + // on doit fermer le storage en cours d'utilisation + source.close(); + } finally { + ui.setBusy(false); + } + } + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/GotoSiteAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/GotoSiteAction.java new file mode 100644 index 0000000..ddd4583 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/GotoSiteAction.java @@ -0,0 +1,87 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.UIHelper; +import jaxx.runtime.SwingUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.AbstractAction; +import java.awt.Desktop; +import java.awt.event.ActionEvent; +import java.net.URL; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class GotoSiteAction extends AbstractAction { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(GotoSiteAction.class); + + private final ObserveMainUI ui; + + public GotoSiteAction(ObserveMainUI ui) { + + super(t("observe.action.site"), SwingUtil.getUIManagerActionIcon("site")); + this.ui = ui; + putValue(SHORT_DESCRIPTION, t("observe.action.site.tip")); + putValue(MNEMONIC_KEY, (int) 's'); + + } + + @Override + public void actionPerformed(ActionEvent e) { + + ObserveSwingApplicationConfig config = ui.getConfig(); + + URL siteURL = config.getOptionAsURL("application.site.url"); + + UIHelper.displayInfo( + t("observe.message.goto.site", siteURL)); + + if (log.isInfoEnabled()) { + log.info("goto " + siteURL); + } + if (Desktop.isDesktopSupported() && + Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { + try { + Desktop.getDesktop().browse(siteURL.toURI()); + } catch (Exception ex) { + UIHelper.handlingError(ex); + } + } + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ImportStorageFromFileAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ImportStorageFromFileAction.java new file mode 100644 index 0000000..faa13db --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ImportStorageFromFileAction.java @@ -0,0 +1,105 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.constants.CreationMode; +import fr.ird.observe.application.swing.db.constants.DbMode; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.storage.StorageStep; +import fr.ird.observe.application.swing.ui.storage.StorageUI; +import fr.ird.observe.application.swing.ui.storage.StorageUIHandler; +import fr.ird.observe.application.swing.ui.storage.StorageUILauncher; +import fr.ird.observe.application.swing.ui.storage.StorageUIModel; +import jaxx.runtime.SwingUtil; + +import javax.swing.AbstractAction; +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.13 + */ +public class ImportStorageFromFileAction extends AbstractAction { + + private static final long serialVersionUID = 1L; + + private final ObserveMainUI ui; + + public ImportStorageFromFileAction(ObserveMainUI ui) { + + super(t("observe.action.load.from.file"), SwingUtil.getUIManagerActionIcon("local-import")); + this.ui = ui; + putValue(SHORT_DESCRIPTION, t("observe.action.load.from.file.tip")); + putValue(MNEMONIC_KEY, (int) 'I'); + + } + + @Override + public void actionPerformed(ActionEvent e) { + + boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); + if (canContinue) { + + new StorageUILauncher(ui, ui, t("observe.title.import.localDB")) { + @Override + protected void init(StorageUI ui) { + super.init(ui); + StorageUIModel model = ui.getModel(); + + model.setCanCreateLocalService(true); + model.setCanUseLocalService(false); + model.setCanUseRemoteService(false); + model.setCanUseServerService(false); + model.setDbMode(DbMode.CREATE_LOCAL); + model.setCreationMode(CreationMode.IMPORT_EXTERNAL_DUMP); + if (model.isLocalStorageExist()) { + // sauvegarde base locale possible + model.setSteps(StorageStep.CONFIG, + StorageStep.BACKUP, + StorageStep.CONFIRM); + + // et requise par défaut + model.setDoBackup(true); + } else { + model.setSteps(StorageStep.CONFIG, StorageStep.CONFIRM); + } + } + + @Override + protected void doAction(StorageUI ui) { + super.doAction(ui); + StorageUIHandler handler = getStorageUIHandler(); + handler.doChangeStorage(ui.getModel()); + } + + }.start(); + } + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/LaunchAdminAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/LaunchAdminAction.java new file mode 100644 index 0000000..9d642d6 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/LaunchAdminAction.java @@ -0,0 +1,79 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.admin.AdminStep; +import fr.ird.observe.application.swing.ui.admin.AdminUILauncher; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.AbstractAction; +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.13 + */ +public class LaunchAdminAction extends AbstractAction { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(LaunchAdminAction.class); + + private final ObserveMainUI ui; + + private final AdminStep action; + + public LaunchAdminAction(ObserveMainUI ui, AdminStep action) { + + super(t(action.getOperationLabel()), action.getIcon()); + this.ui = ui; + this.action = action; + putValue(SHORT_DESCRIPTION, t(action.getOperationDescription())); + putValue(MNEMONIC_KEY, (int) t(action.getOperationLabel()).charAt(0)); + + } + + @Override + public void actionPerformed(ActionEvent event) { + + boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); + if (canContinue) { + + if (log.isInfoEnabled()) { + log.info("Will start admin action: " + action.getLabel()); + } + AdminUILauncher launcher = AdminUILauncher.newLauncher(ui, action); + launcher.start(); + } + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ReloadApplicationAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ReloadApplicationAction.java new file mode 100644 index 0000000..15cb582 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ReloadApplicationAction.java @@ -0,0 +1,73 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.ObserveUICallback; +import jaxx.runtime.SwingUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.AbstractAction; +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ReloadApplicationAction extends AbstractAction { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(ReloadApplicationAction.class); + + private final ObserveMainUI ui; + + public ReloadApplicationAction(ObserveMainUI ui) { + + super(t("observe.action.restart.application"), SwingUtil.getUIManagerActionIcon("application-reload")); + this.ui = ui; + putValue(SHORT_DESCRIPTION, t("observe.action.restart.application.tip")); + putValue(MNEMONIC_KEY, (int) 'X'); + + } + + @Override + public void actionPerformed(ActionEvent event) { + + if (log.isInfoEnabled()) { + log.info("ObServe reloading..."); + } + boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); + if (canContinue) { + ObserveUICallback.application.run(); + } + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ReloadDefaultConfigurationAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ReloadDefaultConfigurationAction.java new file mode 100644 index 0000000..0946218 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ReloadDefaultConfigurationAction.java @@ -0,0 +1,95 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.ObserveUICallback; +import jaxx.runtime.SwingUtil; +import org.apache.commons.io.FileUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.AbstractAction; +import java.awt.event.ActionEvent; +import java.io.File; +import java.io.IOException; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ReloadDefaultConfigurationAction extends AbstractAction { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(ReloadDefaultConfigurationAction.class); + + private final ObserveMainUI ui; + + public ReloadDefaultConfigurationAction(ObserveMainUI ui) { + + super(t("observe.action.reloadDefaultConfiguration"), SwingUtil.getUIManagerActionIcon("application-reload")); + this.ui = ui; + putValue(SHORT_DESCRIPTION, t("observe.action.reloadDefaultConfiguration.tip")); + putValue(MNEMONIC_KEY, (int) 'R'); + + } + + @Override + public void actionPerformed(ActionEvent event) { + + if (log.isInfoEnabled()) { + log.info("ObServe reloading default configuration..."); + } + + boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); + if (canContinue) { + ObserveSwingApplicationConfig config = ui.getConfig(); + + File directory = config.getResourcesDirectory(); + + if (log.isInfoEnabled()) { + log.info(t("observe.message.delete.directory", directory)); + } + + // suppression du répertoire des ressources + try { + FileUtils.deleteDirectory(directory); + } catch (IOException e) { + if (log.isErrorEnabled()) { + log.error("Could not delete resources directory: " + directory, e); + } + } + + ObserveUICallback.application.run(); + } + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ReloadResourcesAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ReloadResourcesAction.java new file mode 100644 index 0000000..8837cde --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ReloadResourcesAction.java @@ -0,0 +1,109 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.ObserveRunner; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.ObserveUICallback; +import jaxx.runtime.SwingUtil; +import org.apache.commons.io.FileUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.i18n.I18n; + +import javax.swing.AbstractAction; +import java.awt.event.ActionEvent; +import java.io.File; +import java.io.IOException; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.13 + */ +public class ReloadResourcesAction extends AbstractAction { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(ReloadResourcesAction.class); + + private final ObserveMainUI ui; + + public ReloadResourcesAction(ObserveMainUI ui) { + + super(t("observe.action.reloadResources"), SwingUtil.getUIManagerActionIcon("application-reload")); + this.ui = ui; + putValue(SHORT_DESCRIPTION, t("observe.action.reloadResources.tip")); + putValue(MNEMONIC_KEY, (int) 'R'); + + } + + @Override + public void actionPerformed(ActionEvent event) { + + if (log.isInfoEnabled()) { + log.info("ObServe reloading resources..."); + } + + boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); + if (canContinue) { + ObserveSwingApplicationConfig config = ui.getConfig(); + + File directory = config.getResourcesDirectory(); + + if (log.isInfoEnabled()) { + log.info(t("observe.message.delete.directory", directory)); + } + + // suppression du répertoire + try { + FileUtils.deleteDirectory(directory); + } catch (IOException e) { + if (log.isErrorEnabled()) { + log.error("Could not delete resources directory: " + directory, e); + } + } + + I18n.reload(); + + DecoratorService decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); + + if (log.isInfoEnabled()) { + log.info("reload decorators"); + } + decoratorService.reload(); + + ObserveRunner.getRunner().loadUIConfig(config); + + ObserveUICallback.ui.run(); + } + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ReloadStorageAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ReloadStorageAction.java new file mode 100644 index 0000000..41765de --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ReloadStorageAction.java @@ -0,0 +1,125 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaH2; +import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaPG; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.UIHelper; +import jaxx.runtime.SwingUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.t; +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.13 + */ +public class ReloadStorageAction extends AbstractObserveAction { + + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(ReloadStorageAction.class); + + private final ObserveMainUI ui; + + public ReloadStorageAction(ObserveMainUI ui) { + + super(t("observe.action.reload.storage"), SwingUtil.getUIManagerActionIcon("db-reload")); + this.ui = ui; + putValue(SHORT_DESCRIPTION, t("observe.action.reload.storage.tip")); + putValue(MNEMONIC_KEY, (int) 'R'); + + } + + @Override + public void actionPerformed(ActionEvent e) { + + run(); + + } + + public void run() { + + ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); + boolean canContinue = context.getContentUIManager().closeSelectedContentUI(); + + ObserveSwingDataSource storage = context.getDataSourcesManager().getMainDataSource(); + + if (canContinue && storage != null) { + + ui.setBusy(false); + + String[] ids = ui.getTreeHelper().getSelectedIds(); + + try { + + if (log.isDebugEnabled()) { + log.debug(">>> close main storage " + storage); + } + // fermeture du storage courant + storage.close(); + + ObserveSwingApplicationConfig appConfig = context.getConfig(); + + if (storage.isLocal()) { + + ObserveDataSourceConfigurationTopiaH2 h2Config = (ObserveDataSourceConfigurationTopiaH2) storage.getConfiguration(); + + h2Config.setCanMigrate(appConfig.isCanMigrateH2()); + } else if (storage.isRemote()) { + ObserveDataSourceConfigurationTopiaPG pgConfig = (ObserveDataSourceConfigurationTopiaPG) storage.getConfiguration(); + pgConfig.setCanMigrate(appConfig.isCanMigrateObstuna()); + } + + try { + + + // on conserve les noeuds a selectionner + context.setNodesToReselect(ids); + + // attachement a l'ui + context.prepareMainStorage(storage, false); + + // ouverture du service + storage.open(); + } catch (Exception e) { + UIHelper.handlingError(e); + } + + } finally { + ui.setBusy(false); + } + + } + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/SaveStorageToFileAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/SaveStorageToFileAction.java new file mode 100644 index 0000000..45b545a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/SaveStorageToFileAction.java @@ -0,0 +1,92 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.storage.StorageBackupUILauncher; +import jaxx.runtime.SwingUtil; + +import javax.swing.JOptionPane; +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.13 + */ +public class SaveStorageToFileAction extends AbstractObserveAction { + + private static final long serialVersionUID = 1L; + + private final ObserveMainUI ui; + + public SaveStorageToFileAction(ObserveMainUI ui) { + + super(t("observe.action.save.to.file"), SwingUtil.getUIManagerActionIcon("local-export")); + this.ui = ui; + putValue(SHORT_DESCRIPTION, t("observe.action.save.to.file.tip")); + putValue(MNEMONIC_KEY, (int) 'L'); + + } + + @Override + public void actionPerformed(ActionEvent e) { + + boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); + if (canContinue) { + + // on teste que l'utilisateur peut lire-ecrire sur la source de données + + ObserveSwingDataSource service = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); + + if (!service.isLocal() && !(service.canReadData() && service.canWriteData())) { + + UIHelper.askUser( + null, + t("observe.title.can.not.export.obstuna"), + t("observe.storage.required.rw.on.data", service), + JOptionPane.ERROR_MESSAGE, + new Object[]{t("observe.choice.cancel")}, + 0 + ); + return; + } + + String title = service.isLocal() ? + t("observe.title.save.localDB") : + t("observe.title.save.remoteDB"); + + StorageBackupUILauncher launcher = + new StorageBackupUILauncher(ui, ui, title); + launcher.start(); + } + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ShowAboutAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ShowAboutAction.java new file mode 100644 index 0000000..66b3488 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ShowAboutAction.java @@ -0,0 +1,126 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveRunner; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.UIHelper; +import jaxx.runtime.SwingUtil; +import jaxx.runtime.swing.AboutPanel; +import org.nuiton.util.Resource; + +import javax.swing.AbstractAction; +import javax.swing.Icon; +import javax.swing.JEditorPane; +import javax.swing.JLabel; +import javax.swing.JScrollPane; +import java.awt.BorderLayout; +import java.awt.event.ActionEvent; +import java.io.File; +import java.net.MalformedURLException; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.13 + */ +public class ShowAboutAction extends AbstractAction { + + private static final long serialVersionUID = 1L; + + private final ObserveMainUI ui; + + public ShowAboutAction(ObserveMainUI ui) { + + super(t("observe.action.about"), SwingUtil.getUIManagerActionIcon("about")); + this.ui = ui; + putValue(SHORT_DESCRIPTION, t("observe.action.about.tip")); + putValue(MNEMONIC_KEY, (int) 'A'); + + } + + @Override + public void actionPerformed(ActionEvent event) { + + AboutPanel about = new AboutPanel() { + + private static final long serialVersionUID = 1L; + + @Override + public void buildTopPanel() { + topPanel.setLayout(new BorderLayout()); + JLabel labelIcon; + Icon logoIcon; + logoIcon = Resource.getIcon("/icons/logo-OT_web.png"); + labelIcon = new JLabel(logoIcon); + topPanel.add(labelIcon, BorderLayout.WEST); + + logoIcon = Resource.getIcon("/icons/logo_ird.png"); + labelIcon = new JLabel(logoIcon); + topPanel.add(labelIcon, BorderLayout.EAST); + } + }; + + String name = ObserveRunner.getRunner().getRunnerName(); + about.setTitle(t("observe.title.about")); + about.setAboutText(t("observe.about.message")); + about.setBottomText(ui.getConfig().getCopyrightText()); + about.setIconPath("/icons/logo-OT_web.png"); + about.setLicenseFile("META-INF/" + name + "-LICENSE.txt"); + about.setThirdpartyFile("META-INF/" + name + "-THIRD-PARTY.txt"); + about.buildTopPanel(); + + // + // translate tab + // + + JScrollPane translatePane = new JScrollPane(); + JEditorPane translateArea = new JEditorPane(); + translateArea.setContentType("text/html"); + translateArea.setEditable(false); + if (translateArea.getFont() != null) { + translateArea.setFont(translateArea.getFont().deriveFont((float) 11)); + } + + translateArea.setBorder(null); + File csvFile = new File(ui.getConfig().getI18nDirectory(), "observe-i18n.csv"); + String translateText; + try { + translateText = t("observe.about.translate.content", csvFile.toURI().toURL()); + } catch (MalformedURLException e) { + throw new RuntimeException("Could not obtain url from " + csvFile, e); + } + translateArea.setText(translateText); + translatePane.getViewport().add(translateArea); + translateArea.addHyperlinkListener(UIHelper::openLink); + + about.getTabs().add(t("observe.about.translate.title"), translatePane); + + about.init(); + about.showInDialog(ui, true); + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ShowConfigAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ShowConfigAction.java new file mode 100644 index 0000000..3917534 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ShowConfigAction.java @@ -0,0 +1,500 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfigOption; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.SpeciesListDto; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.ObserveMainUIHandler; +import fr.ird.observe.application.swing.ui.ObserveUICallback; +import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; +import jaxx.runtime.SwingUtil; +import jaxx.runtime.swing.config.ConfigUIHelper; +import jaxx.runtime.swing.config.model.ConfigUIModelBuilder; +import jaxx.runtime.swing.config.model.MainCallBackFinalizer; +import jaxx.runtime.swing.editor.bean.BeanFilterableComboBox; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.jdesktop.swingx.renderer.DefaultTableRenderer; +import org.nuiton.config.ConfigOptionDef; +import org.nuiton.decorator.Decorator; +import org.nuiton.decorator.MultiJXPathDecorator; + +import javax.swing.AbstractAction; +import javax.swing.DefaultCellEditor; +import javax.swing.Icon; +import javax.swing.JComboBox; +import javax.swing.JTable; +import java.awt.Component; +import java.awt.event.ActionEvent; +import java.awt.event.MouseEvent; +import java.util.Collection; +import java.util.EventObject; +import java.util.Map; +import java.util.Set; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.13 + */ +public class ShowConfigAction extends AbstractAction { + + private static final long serialVersionUID = 3038774900992805790L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(ShowConfigAction.class); + + private final ObserveMainUI ui; + + public ShowConfigAction(ObserveMainUI ui) { + + super(t("observe.action.configuration"), SwingUtil.getUIManagerActionIcon("config")); + this.ui = ui; + putValue(SHORT_DESCRIPTION, t("observe.action.configuration.tip")); + putValue(MNEMONIC_KEY, (int) 'C'); + + } + + @Override + public void actionPerformed(ActionEvent event) { + + + if (log.isInfoEnabled()) { + log.info("ObServe opening configuration ui..."); + } + boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); + if (canContinue) { + + ObserveSwingDataSource dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); + + ObserveSwingApplicationConfig config = ui.getConfig(); + + ObserveConfigUIBuilder helper; + + helper = buildUI(config, dataSource); + + helper.buildUI(ui, "observe.config.category.directories"); + + helper.displayUI(ui, false); + + } + + } + + protected ObserveConfigUIBuilder buildUI(ObserveSwingApplicationConfig config, ObserveSwingDataSource dataSource) { + + SpeciesListTableCellEditor editor = null; + SpeciesListsTableCellRenderer renderer = null; + + if (dataSource != null) { + + Set<ReferentialReference<SpeciesListDto>> speciesLists = dataSource.getReferentialReferences(SpeciesListDto.class); + + Map<String, ReferentialReference<SpeciesListDto>> speciesListMap = ReferentialReference.splitById(speciesLists); + + ReferentialReferenceDecorator<SpeciesListDto> referenceDecorator = ObserveSwingApplicationContext.get().getDecoratorService().getReferentialReferenceDecorator(SpeciesListDto.class); + + editor = new SpeciesListTableCellEditor(speciesLists, speciesListMap, referenceDecorator); + renderer = new SpeciesListsTableCellRenderer(speciesListMap, referenceDecorator); + + } + + ObserveConfigUIBuilder helper = new ObserveConfigUIBuilder(config, editor, renderer); + + + for (ObserveUICallback callback : ObserveUICallback.values()) { + helper.registerCallBack(callback); + } + + helper.setFinalizer(new MainCallBackFinalizer(ObserveUICallback.application.name())); + + helper.setCloseAction(ObserveMainUIHandler::restartEdit); + + // categorie repertoires + addDirectoriesOptions(helper); + + // categorie h2 + addH2Options(helper); + + // categorie obtuna + addObstunaOptions(helper); + + // categorie change storage + addChangeStorageOptions(helper); + + // categorie gps + addGpsOptions(helper); + + // categorie synchro + addSynchroOptions(helper); + + // categorie observations (seine) + addObservationsOptions(helper); + + if (dataSource != null) { + + // categorie speciesList (seine) + addSeineSpeciesListOptions(helper); + + // categorie speciesList (longline) + addLonglineSpeciesListOptions(helper); + + } + + // catégories map + addMapOptions(helper); + + // others + addOthersOptions(helper); + + return helper; + + } + + protected void addDirectoriesOptions(ObserveConfigUIBuilder helper) { + + helper.addCategory( + n("observe.config.category.directories"), + n("observe.config.category.directories.description")); + + helper.addOption(ObserveSwingApplicationConfigOption.CONFIG_FILE); + helper.addOption(ObserveSwingApplicationConfigOption.DATA_DIRECTORY); + helper.addOption(ObserveSwingApplicationConfigOption.DB_DIRECTORY); + helper.addOption(ObserveSwingApplicationConfigOption.BACKUP_DIRECTORY); + helper.addOption(ObserveSwingApplicationConfigOption.TMP_DIRECTORY); + helper.addOption(ObserveSwingApplicationConfigOption.VALIDATION_REPORT_DIRECTORY); + helper.addOption(ObserveSwingApplicationConfigOption.RESOURCES_DIRECTORY, ObserveUICallback.application); + + } + + protected void addH2Options(ObserveConfigUIBuilder helper) { + + helper.addCategory(n("observe.config.category.h2"), + n("observe.config.category.h2.description")); + + helper.addOption(ObserveSwingApplicationConfigOption.H2_LOGIN); + helper.addOption(ObserveSwingApplicationConfigOption.H2_PASSWORD); + helper.addOption(ObserveSwingApplicationConfigOption.H2_CAN_MIGRATE); + helper.addOption(ObserveSwingApplicationConfigOption.H2_SERVER_PORT); + + } + + protected void addObstunaOptions(ObserveConfigUIBuilder helper) { + + helper.addCategory(n("observe.config.category.obstuna"), + n("observe.config.category.obstuna.description")); + + helper.addOption(ObserveSwingApplicationConfigOption.OBSTUNA_URL); + helper.addOption(ObserveSwingApplicationConfigOption.OBSTUNA_LOGIN); + helper.addOption(ObserveSwingApplicationConfigOption.OBSTUNA_USE_SSL_CERT); +// helper.addOption(ObserveSwingApplicationConfigOption.OBSTUNA_SSL_CERTIFICAT_FILE); + + helper.addOption(ObserveSwingApplicationConfigOption.OBSTUNA_CAN_MIGRATE, ObserveUICallback.db); + + } + + protected void addChangeStorageOptions(ObserveConfigUIBuilder helper) { + + helper.addCategory( + n("observe.config.category.changeStorage"), + n("observe.config.category.changeStorage.description")); + + helper.addOption(ObserveSwingApplicationConfigOption.DEFAULT_DB_MODE); + helper.addOption(ObserveSwingApplicationConfigOption.DEFAULT_CREATION_MODE); + helper.addOption(ObserveSwingApplicationConfigOption.STORE_REMOTE_STORAGE); + helper.addOption(ObserveSwingApplicationConfigOption.SHOW_MIGRATION_PROGRESSION); + helper.addOption(ObserveSwingApplicationConfigOption.SHOW_MIGRATION_SQL); + helper.addOption(ObserveSwingApplicationConfigOption.SHOW_SQL, ObserveUICallback.application); + + } + + protected void addGpsOptions(ObserveConfigUIBuilder helper) { + + helper.addCategory(n("observe.config.category.gps"), + n("observe.config.category.gps.description")); + + helper.addOption(ObserveSwingApplicationConfigOption.DEFAULT_GPS_MAX_DELAY); + helper.addOption(ObserveSwingApplicationConfigOption.DEFAULT_GPS_MAX_SPEED); + + } + + protected void addSynchroOptions(ObserveConfigUIBuilder helper) { + + helper.addCategory(n("observe.config.category.synchro"), + n("observe.config.category.synchro.description")); + + helper.addOption(ObserveSwingApplicationConfigOption.CHANGE_SYNCHRO_SRC); + helper.addOption(ObserveSwingApplicationConfigOption.H2_CAN_MIGRATE); + + } + + protected void addObservationsOptions(ObserveConfigUIBuilder helper) { + + helper.addCategory( + n("observe.config.category.observation"), + n("observe.config.category.observation.description"), + ObserveUICallback.ui.name()); + + helper.addOption(ObserveSwingApplicationConfigOption.DETAILLED_ACTIVITIES_OBSERVATION); + helper.addOption(ObserveSwingApplicationConfigOption.NON_TARGET_OBSERVATION); + helper.addOption(ObserveSwingApplicationConfigOption.BAIT_OBSERVATION); + helper.addOption(ObserveSwingApplicationConfigOption.MAMMALS_OBSERVATION); + helper.addOption(ObserveSwingApplicationConfigOption.SAMPLES_OBSERVATION); + helper.addOption(ObserveSwingApplicationConfigOption.OBJECTS_OBSERVATION); + helper.addOption(ObserveSwingApplicationConfigOption.BIRDS_OBSERVATION); + helper.addOption(ObserveSwingApplicationConfigOption.TARGET_DISCARDS_OBSERVATION); + + } + + protected void addSeineSpeciesListOptions(ObserveConfigUIBuilder helper) { + + helper.addCategory( + n("observe.config.category.speciesList.seine"), + n("observe.config.category.speciesList.seine.description"), + ObserveUICallback.ui.name()); + + helper.addSpeciesListOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_TARGET_CATCH_ID); + helper.addSpeciesListOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_SCHOOL_ESTIMATE_ID); + helper.addSpeciesListOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_OBJECT_SCHOOL_ESTIMATE_ID); + helper.addSpeciesListOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_NON_TARGET_CATCH_ID); + helper.addSpeciesListOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_OBJECT_OBSERVED_SPECIES_ID); + + } + + protected void addLonglineSpeciesListOptions(ObserveConfigUIBuilder helper) { + + + helper.addCategory( + n("observe.config.category.speciesList.longline"), + n("observe.config.category.speciesList.longline.description"), + ObserveUICallback.ui.name()); + + helper.addSpeciesListOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_LONGLINE_CATCH_ID); + helper.addSpeciesListOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_LONGLINE_ENCOUNTER_ID); + + } + + protected void addMapOptions(ObserveConfigUIBuilder helper) { + + helper.addCategory( + n("observe.config.category.map"), + n("observe.config.category.map.description"), + ObserveUICallback.ui.name()); + + helper.addOption(ObserveSwingApplicationConfigOption.MAP_BACKGROUND_COLOR); + for (ObserveSwingApplicationConfigOption layerOption : ObserveSwingApplicationConfigOption.MAP_LAYERS) { + helper.addOption(layerOption); + } + helper.addOption(ObserveSwingApplicationConfigOption.MAP_STYLE_FILE); + + } + + protected void addOthersOptions(ObserveConfigUIBuilder helper) { + + helper.addCategory(n("observe.config.category.other"), + n("observe.config.category.other.description")); + + helper.addOption(ObserveSwingApplicationConfigOption.SHOW_NUMBER_EDITOR_BUTTON); + helper.addOption(ObserveSwingApplicationConfigOption.AUTO_POPUP_NUMBER_EDITOR); + helper.addOption(ObserveSwingApplicationConfigOption.SHOW_DATE_TIME_EDITOR_SLIDER); + helper.addOption(ObserveSwingApplicationConfigOption.LOAD_LOCAL_STORAGE, ObserveUICallback.application); +// helper.addOption(ObserveSwingApplicationConfigOption.FULL_SCREEN, ObserveUICallback.ui); + helper.addOption(ObserveSwingApplicationConfigOption.LOCALE, ObserveUICallback.ui); + helper.addOption(ObserveSwingApplicationConfigOption.DB_LOCALE, ObserveUICallback.ui); + + } + + protected class ObserveConfigUIBuilder extends ConfigUIHelper { + + private final SpeciesListTableCellEditor speciesListTableCellEditor; + + private final SpeciesListsTableCellRenderer speciesListsTableCellRenderer; + + protected ObserveConfigUIBuilder(ObserveSwingApplicationConfig config, + SpeciesListTableCellEditor speciesListTableCellEditor, + SpeciesListsTableCellRenderer speciesListsTableCellRenderer) { + super(config); + this.speciesListTableCellEditor = speciesListTableCellEditor; + this.speciesListsTableCellRenderer = speciesListsTableCellRenderer; + } + + @Override + public ConfigUIModelBuilder addOption(ConfigOptionDef option) { + + // add the option + super.addOption(option); + + String beanProperty = ((ObserveSwingApplicationConfigOption) option).getPropertyKey(); + + if (StringUtils.isNotEmpty(beanProperty)) { + setOptionPropertyName(beanProperty); + } + + return modelBuilder; + + } + + public ConfigUIModelBuilder addOption(ObserveSwingApplicationConfigOption option, ObserveUICallback callBack) { + + addOption(option); + setOptionCallBack(callBack.name()); + + return modelBuilder; + + } + + public ConfigUIModelBuilder registerCallBack(ObserveUICallback callback) { + + String name = callback.name(); + String description = callback.getLabel(); + Icon icon = callback.getIcon(); + Runnable action = callback; + registerCallBack(name, description, icon, action); + + return modelBuilder; + + } + + protected ConfigUIModelBuilder addSpeciesListOption(ObserveSwingApplicationConfigOption option) { + + addOption(option) + .setOptionPropertyName(option.getPropertyKey()) + .setOptionEditor(speciesListTableCellEditor) + .setOptionRenderer(speciesListsTableCellRenderer); + + return modelBuilder; + + } + + } + + protected class SpeciesListsTableCellRenderer extends DefaultTableRenderer { + + private static final long serialVersionUID = 1L; + + private final Map<String, ReferentialReference<SpeciesListDto>> entityMap; + + private final Decorator<ReferentialReference<SpeciesListDto>> decorator; + + public SpeciesListsTableCellRenderer(Map<String, ReferentialReference<SpeciesListDto>> entityMap, Decorator<ReferentialReference<SpeciesListDto>> decorator) { + this.entityMap = entityMap; + this.decorator = decorator; + } + + @Override + public Component getTableCellRendererComponent(JTable table, Object value, + boolean isSelected, boolean hasFocus, + int row, int column) { + + String speciesListId = String.valueOf(value); + ReferentialReference<SpeciesListDto> speciesList = entityMap.get(speciesListId); + return super.getTableCellRendererComponent(table, decorator.toString(speciesList), isSelected, hasFocus, row, column); + + } + } + + protected class SpeciesListTableCellEditor extends DefaultCellEditor { + + private static final long serialVersionUID = 1L; + + private final Map<String, ReferentialReference<SpeciesListDto>> entityMap; + + private final ReferentialReferenceDecorator<SpeciesListDto> decorator; + + protected SpeciesListTableCellEditor(Collection<ReferentialReference<SpeciesListDto>> entities, + Map<String, ReferentialReference<SpeciesListDto>> entityMap, + ReferentialReferenceDecorator<SpeciesListDto> decorator) { + + super(new JComboBox()); + + this.entityMap = entityMap; + this.decorator = decorator; + + final BeanFilterableComboBox<ReferentialReference<SpeciesListDto>> component = new BeanFilterableComboBox<>(); + component.setI18nPrefix("observe.common."); + component.setShowReset(true); + component.setBeanType((Class) ReferentialReference.class); + + setClickCountToStart(1); + + editorComponent = component; + delegate = new DefaultCellEditor.EditorDelegate() { + + private static final long serialVersionUID = 1L; + + @Override + public void setValue(Object value) { + if (value != null && String.class.isInstance(value)) { + + value = SpeciesListTableCellEditor.this.entityMap.get(value); + } + component.setSelectedItem(value); + } + + @Override + public Object getCellEditorValue() { + String result = null; + Object selectedItem = component.getSelectedItem(); + if (selectedItem != null && ReferentialReference.class.isInstance(selectedItem)) { + ReferentialReference reference = (ReferentialReference) selectedItem; + result = reference.getId(); + } + return result; + } + + @Override + public boolean shouldSelectCell(EventObject anEvent) { + if (anEvent instanceof MouseEvent) { + MouseEvent e = (MouseEvent) anEvent; + return e.getID() != MouseEvent.MOUSE_DRAGGED; + } + return true; + } + + @Override + public boolean stopCellEditing() { + if (component.isEditable()) { + // Commit edited value. + component.getCombobox().actionPerformed( + new ActionEvent(SpeciesListTableCellEditor.this, 0, "")); + } + return super.stopCellEditing(); + } + }; + + component.init((MultiJXPathDecorator) this.decorator, Lists.newArrayList(entities)); + } + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ShowStorageInfoAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ShowStorageInfoAction.java new file mode 100644 index 0000000..6347b19 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/ShowStorageInfoAction.java @@ -0,0 +1,81 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.ObserveTextGenerator; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import jaxx.runtime.SwingUtil; + +import javax.swing.AbstractAction; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.13 + */ +public class ShowStorageInfoAction extends AbstractAction { + + private static final long serialVersionUID = 1L; + + private final ObserveMainUI ui; + + public ShowStorageInfoAction(ObserveMainUI ui) { + + super(t("observe.action.info.storage"), SwingUtil.getUIManagerActionIcon("information")); + this.ui = ui; + putValue(SHORT_DESCRIPTION, t("observe.action.info.storage.tip")); + putValue(MNEMONIC_KEY, (int) 'I'); + + } + + @Override + public void actionPerformed(ActionEvent e) { + + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + + ObserveSwingDataSource source; + if (ui.getConfig().isMainStorageOpened()) { + source = applicationContext.getDataSourcesManager().getMainDataSource(); + } else { + source = null; + } + + ObserveTextGenerator textGenerator = applicationContext.getTextGenerator(); + String text = textGenerator.getDataSourceInfo(source); + JOptionPane.showMessageDialog( + ui, + new JLabel(text), + t("observe.title.storage.info"), + JOptionPane.INFORMATION_MESSAGE); + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/StartH2WebServerAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/StartH2WebServerAction.java new file mode 100644 index 0000000..a3edbaa --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/StartH2WebServerAction.java @@ -0,0 +1,100 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.UIHelper; +import jaxx.runtime.SwingUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.h2.tools.Server; + +import javax.swing.AbstractAction; +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.13 + */ +public class StartH2WebServerAction extends AbstractAction { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(StartH2WebServerAction.class); + + private final ObserveMainUI ui; + + public StartH2WebServerAction(ObserveMainUI ui) { + + super(t("observe.action.start.h2.web.server"), SwingUtil.getUIManagerActionIcon("db-start-server")); + this.ui = ui; + putValue(SHORT_DESCRIPTION, t("observe.action.start.h2.web.server.tip")); + putValue(MNEMONIC_KEY, (int) 'S'); + + } + + @Override + public void actionPerformed(ActionEvent event) { + + if (ui.isH2WebServer()) { + + if (log.isWarnEnabled()) { + log.warn("Can not start h2 web server... (web server already found)"); + } + + } else { + + if (log.isInfoEnabled()) { + log.info("Will start h2 web server ..."); + } + + try { + + Server server = Server.createWebServer("-webAllowOthers"); + server.start(); + + Server.openBrowser(server.getURL()); + + // On mémorise l'instance du server dans le contexte applicatif afin de pouvoir la récupérer plus tard, + // par exemple lorsque l'on souhaitera arrêter le server. + ObserveSwingApplicationContext.get().setH2WebServer(server); + + ui.setH2WebServer(true); + + } catch (Exception e) { + + UIHelper.handlingError("Could not start h2 web server ", e); + } + + } + + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/StartServerModeAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/StartServerModeAction.java new file mode 100644 index 0000000..2f187d5 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/StartServerModeAction.java @@ -0,0 +1,127 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.ObserveMainUIHandler; +import fr.ird.observe.application.swing.ui.ObserveUIMode; +import jaxx.runtime.SwingUtil; +import jaxx.runtime.swing.ErrorDialogUI; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.h2.tools.Server; + +import javax.swing.AbstractAction; +import java.awt.event.ActionEvent; +import java.io.File; +import java.sql.SQLException; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.13 + */ +public class StartServerModeAction extends AbstractAction { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(StartServerModeAction.class); + + private final ObserveMainUI ui; + + public StartServerModeAction(ObserveMainUI ui) { + + super(t("observe.action.start.server.mode"), SwingUtil.getUIManagerActionIcon("db-start-server")); + this.ui = ui; + putValue(SHORT_DESCRIPTION, t("observe.action.start.server.mode.tip")); + putValue(MNEMONIC_KEY, (int) 'S'); + + } + + @Override + public void actionPerformed(ActionEvent e) { + + run(); + + } + + public void run() { + + if (log.isInfoEnabled()) { + log.info("Will start server mode..."); + } + ObserveSwingApplicationConfig config = ui.getConfig(); + File dbDirectory = new File(config.getLocalDBDirectory(), "obstuna"); + String h2Login = config.getH2Login(); + String h2Password = new String(config.getH2Password()); + Integer port = config.getH2ServerPort(); + + ui.setMode(ObserveUIMode.SERVER); + + try { + + Server server = Server.createTcpServer("-tcp", + "-tcpAllowOthers", + "-ifExists", + "-baseDir", dbDirectory.getAbsolutePath(), + "-tcpDaemon", + "-tcpPort", + String.valueOf(port)); + + String url = String.format(ObserveMainUIHandler.H2_SERVER_URL_PATTERN, + server.getURL(), + dbDirectory.getAbsolutePath()); + + server.start(); + if (log.isInfoEnabled()) { + log.info("server starts at " + url); + } + + String text = t("observe.message.server.info", dbDirectory); + ui.getServerModeInfo().setText(text); + + ui.getServerModeURL().setText(url); + ui.getServerModeLogin().setText(h2Login); + ui.getServerModePassword().setText(h2Password); + + // On mémorise l'instance du server dans le contexte applicatif afin de pouvoir la récupérer plus tard, + // par exemple lorsque l'on souhaitera arrêter le server. + ObserveSwingApplicationContext.get().setH2Server(server); + + } catch (SQLException e) { + + if (log.isErrorEnabled()) { + log.error("Could not start h2 server ", e); + } + ErrorDialogUI.showError(e); + } + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/StopH2WebServerAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/StopH2WebServerAction.java new file mode 100644 index 0000000..2dd9d56 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/StopH2WebServerAction.java @@ -0,0 +1,82 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import jaxx.runtime.SwingUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.h2.tools.Server; + +import javax.swing.AbstractAction; +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.13 + */ +public class StopH2WebServerAction extends AbstractAction { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(StopH2WebServerAction.class); + + private final ObserveMainUI ui; + + public StopH2WebServerAction(ObserveMainUI ui) { + + super(t("observe.action.stop.h2.web.server"), SwingUtil.getUIManagerActionIcon("db-stop-server")); + this.ui = ui; + putValue(SHORT_DESCRIPTION, t("observe.action.stop.h2.web.server.tip")); + putValue(MNEMONIC_KEY, (int) 'S'); + + } + + @Override + public void actionPerformed(ActionEvent e) { + + if (ui.isH2WebServer()) { + if (log.isInfoEnabled()) { + log.info("Will stop web server mode..."); + } + + Server server = ObserveSwingApplicationContext.get().getH2WebServer(); + if (server != null) { + server.stop(); + } + ui.setH2WebServer(false); + } else { + if (log.isWarnEnabled()) { + log.warn("Can not stop h2 web server... (no web server found)"); + } + } + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/StopServerModeAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/StopServerModeAction.java new file mode 100644 index 0000000..099ed7b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/StopServerModeAction.java @@ -0,0 +1,105 @@ +package fr.ird.observe.application.swing.ui.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.ObserveUIMode; +import jaxx.runtime.SwingUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.h2.tools.Server; + +import javax.swing.AbstractAction; +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 1/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.13 + */ +public class StopServerModeAction extends AbstractAction { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(StopServerModeAction.class); + + private final ObserveMainUI ui; + + public StopServerModeAction(ObserveMainUI ui) { + + super(t("observe.action.stop.server.mode"), SwingUtil.getUIManagerActionIcon("db-stop-server")); + this.ui = ui; + putValue(SHORT_DESCRIPTION, t("observe.action.stop.server.mode.tip")); + putValue(MNEMONIC_KEY, (int) 'S'); + + } + + @Override + public void actionPerformed(ActionEvent e) { + + if (log.isInfoEnabled()) { + log.info("Will stop server mode..."); + } + + Server server = ObserveSwingApplicationContext.get().getH2Server(); + + if (server != null) { + server.stop(); + } + ui.setMode(ObserveUIMode.NO_DB); + + if (ui.isH2WebServer()) { + + // stop also the h2 web server + launchStopH2WebServer(ui); + } + + } + + public void launchStopH2WebServer(ObserveMainUI ui) { + + if (ui.isH2WebServer()) { + if (log.isInfoEnabled()) { + log.info("Will stop web server mode..."); + } + + Server server = ObserveSwingApplicationContext.get().getH2WebServer(); + if (server != null) { + server.stop(); + } + ui.setH2WebServer(false); + } else { + if (log.isWarnEnabled()) { + log.warn("Can not stop h2 web server... (no web server found)"); + } + } + + } + + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/AbstractUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/AbstractUIAction.java new file mode 100644 index 0000000..1348fb4 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/AbstractUIAction.java @@ -0,0 +1,113 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.actions.shared; + +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.content.ObserveContentUI; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import jaxx.runtime.SwingUtil; + +import javax.swing.AbstractAction; +import javax.swing.AbstractButton; +import javax.swing.Icon; +import javax.swing.JTree; +import javax.swing.tree.TreePath; + +import static org.nuiton.i18n.I18n.t; + +/** + * Pour implanter les actions communes. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public abstract class AbstractUIAction extends AbstractAction { + + private static final long serialVersionUID = 1L; + + private final ObserveMainUI mainUI; + + private final String actionId; + + public AbstractUIAction(ObserveMainUI mainUI, + String actionId, + String label, + String shortDescription, + String actionIcon) { + super(t(label), SwingUtil.getUIManagerActionIcon(actionIcon)); + this.actionId = actionId; + this.mainUI = mainUI; + putValue(SHORT_DESCRIPTION, t(shortDescription)); + } + + public ObserveMainUI getMainUI() { + return mainUI; + } + + public String getActionId() { + return actionId; + } + + public void initAction(ObserveContentUI<?> ui, AbstractButton editor) { + editor.setAction(this); + editor.putClientProperty("mainUI", mainUI); + } + + public void updateAction(ObserveContentUI<?> ui, AbstractButton editor) { + editor.putClientProperty("ui", ui); + String tip = (String) editor.getClientProperty("toolTipText"); + if (tip != null) { + editor.setToolTipText(tip); + } + String text = (String) editor.getClientProperty("text"); + if (text != null) { + editor.setText(text); + } + String actionIcon = (String) editor.getClientProperty("actionIcon"); + if (actionIcon != null) { + Icon icon = SwingUtil.getUIManagerActionIcon(actionIcon); + editor.setIcon(icon); + } + } + + public static boolean isOpenActivityNodeCollapsed(JTree tree, + ObserveTreeHelper treeHelper, + DataContext dataContext) { + + // on regarde si le noeud de l'activity ouverte est collapsé + + ObserveNode node = treeHelper.getSelectedNode(); + + TreePath path = tree.getSelectionPath(); + + String id = dataContext.getOpenActivityId(); + + ObserveNode node1 = treeHelper.findNode(node, id); + + TreePath activityPath = path.pathByAddingChild(node1); + + boolean wasCollapsed = tree.isCollapsed(activityPath); + return wasCollapsed; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/CancelCreateUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/CancelCreateUIAction.java new file mode 100644 index 0000000..864edba --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/CancelCreateUIAction.java @@ -0,0 +1,72 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.actions.shared; + +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.content.ContentUI; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; + +import javax.swing.JComponent; +import javax.swing.SwingUtilities; +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.n; + +/** + * Action pour sélectionner un noeud (attaché à l'éditeur) dans l'arbre de + * navigation. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class CancelCreateUIAction extends AbstractUIAction { + + private static final long serialVersionUID = 1L; + + public static final String ACTION_NAME = "cancelCreate"; + + public CancelCreateUIAction(ObserveMainUI mainUI) { + super(mainUI, + ACTION_NAME, + n("observe.action.cancel"), + n("observe.action.cancel.create.tip"), + "cancel" + ); + } + + @Override + public void actionPerformed(final ActionEvent e) { + SwingUtilities.invokeLater(() -> { + JComponent c = (JComponent) e.getSource(); + ContentUI<?> ui = (ContentUI<?>) + c.getClientProperty("ui"); + if (ui == null) { + throw new IllegalStateException( + "could not find client property " + + "ui on component" + c); + } + ui.stopEdit(); + ObserveNode parentNode = ui.getTreeHelper().removeNode(ui.getTreeHelper().getSelectedNode()); + ui.getTreeHelper().selectNode(parentNode); + }); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/CloseAndCreateUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/CloseAndCreateUIAction.java new file mode 100644 index 0000000..69f8f8f --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/CloseAndCreateUIAction.java @@ -0,0 +1,157 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.actions.shared; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.longline.ActivityLonglineDto; +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.content.ContentUI; +import fr.ird.observe.application.swing.ui.content.list.impl.longline.ActivityLonglinesUI; +import fr.ird.observe.application.swing.ui.content.list.impl.seine.ActivitySeinesUI; +import fr.ird.observe.application.swing.ui.content.open.ContentOpenableUI; +import fr.ird.observe.application.swing.ui.content.open.impl.longline.ActivityLonglineUI; +import fr.ird.observe.application.swing.ui.content.open.impl.seine.ActivitySeineUI; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; + +import javax.swing.JComponent; +import javax.swing.JTree; +import javax.swing.SwingUtilities; +import javax.swing.tree.TreePath; +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.n; + +/** + * Action pour fermer l'objet sous-jacent à l'écran et en créer un nouveau. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.5 + */ +public class CloseAndCreateUIAction extends AbstractUIAction { + + private static final long serialVersionUID = 1L; + + public static final String ACTION_NAME = "closeAndCreate"; + + public CloseAndCreateUIAction(ObserveMainUI mainUI) { + super(mainUI, + ACTION_NAME, + n("observe.content.action.closeAndCreate"), + n("observe.content.action.closeAndCreate.tip"), + "add" + ); + } + + @Override + public void actionPerformed(final ActionEvent e) { + + SwingUtilities.invokeLater(() -> { + JComponent c = (JComponent) e.getSource(); + ContentUI<?> ui = (ContentUI<?>) + c.getClientProperty("ui"); + if (ui == null) { + throw new IllegalStateException( + "could not find client property " + + "ui on component" + c); + } + if (ui instanceof ContentOpenableUI) { + ((ContentOpenableUI<?>) ui).closeAndCreateData(); + return; + } + + if (ui instanceof ActivitySeinesUI) { + + // cas particulier pour l'écran des activitys + + JTree tree = getMainUI().getNavigation(); + ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); + + boolean wasCollapsed = isOpenActivityNodeCollapsed( + tree, + treeHelper, + getMainUI().getDataContext() + ); + + // selection du noeud de l'activity ouverte + treeHelper.selectOpenNode(ActivitySeineDto.class); + + // on conserve le path de l'activity + TreePath path = tree.getSelectionPath(); + + // recuperation de l'écran associé + ActivitySeineUI selectedUI = (ActivitySeineUI) + ObserveSwingApplicationContext.get().getContentUIManager().getSelectedContentUI(); + + // fermeture de l'activity et création d'une nouvelle + selectedUI.closeAndCreateData(); + + if (wasCollapsed) { + + // on ferme le noeud de l'activity (qui a ete ouvert + // lors de la selection de celle-ci) + tree.collapsePath(path); + } + + return; + } + + if (ui instanceof ActivityLonglinesUI) { + + // cas particulier pour l'écran des activitys + + JTree tree = getMainUI().getNavigation(); + ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); + + boolean wasCollapsed = isOpenActivityNodeCollapsed( + tree, + treeHelper, + getMainUI().getDataContext() + ); + + // selection du noeud de l'activity ouverte + treeHelper.selectOpenNode(ActivityLonglineDto.class); + + // on conserve le path de l'activity + TreePath path = tree.getSelectionPath(); + + // recuperation de l'écran associé + ActivityLonglineUI selectedUI = (ActivityLonglineUI) + ObserveSwingApplicationContext.get().getContentUIManager().getSelectedContentUI(); + + // fermeture de l'activity et création d'une nouvelle + selectedUI.closeAndCreateData(); + + if (wasCollapsed) { + + // on ferme le noeud de l'activity (qui a ete ouvert + // lors de la selection de celle-ci) + tree.collapsePath(path); + } + + return; + } + + throw new IllegalStateException("Can not come here!"); + }); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/CloseOpenUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/CloseOpenUIAction.java new file mode 100644 index 0000000..a2e42b4 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/CloseOpenUIAction.java @@ -0,0 +1,173 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.actions.shared; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.longline.ActivityLonglineDto; +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.content.ContentUI; +import fr.ird.observe.application.swing.ui.content.list.impl.longline.ActivityLonglinesUI; +import fr.ird.observe.application.swing.ui.content.list.impl.seine.ActivitySeinesUI; +import fr.ird.observe.application.swing.ui.content.open.ContentOpenableUI; +import fr.ird.observe.application.swing.ui.content.open.impl.longline.ActivityLonglineUI; +import fr.ird.observe.application.swing.ui.content.open.impl.seine.ActivitySeineUI; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; + +import javax.swing.JComponent; +import javax.swing.JTree; +import javax.swing.SwingUtilities; +import javax.swing.tree.TreePath; +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.n; + +/** + * Action pour fermer l'objet sous-jacent à l'écran. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class CloseOpenUIAction extends AbstractUIAction { + + private static final long serialVersionUID = 1L; + + public static final String ACTION_NAME = "closeOpen"; + + public CloseOpenUIAction(ObserveMainUI mainUI) { + super(mainUI, + ACTION_NAME, + n("observe.action.close.open"), + n("observe.action.close.open.tip"), + "close" + ); + } + + @Override + public void actionPerformed(final ActionEvent e) { + + SwingUtilities.invokeLater(() -> { + JComponent c = (JComponent) e.getSource(); + ContentUI<?> ui = (ContentUI<?>) + c.getClientProperty("ui"); + if (ui == null) { + throw new IllegalStateException( + "could not find client property " + + "ui on component" + c); + } + + if (ui instanceof ContentOpenableUI) { + ((ContentOpenableUI<?>) ui).closeData(); + return; + } + + if (ui instanceof ActivitySeinesUI) { + + // cas particulier pour l'écran des activités + + JTree tree = getMainUI().getNavigation(); + ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); + + // recuperation du noeud courant (activitys) + ObserveNode node = treeHelper.getSelectedNode(); + + boolean wasCollapsed = isOpenActivityNodeCollapsed( + tree, + treeHelper, + getMainUI().getDataContext() + ); + + // selection du noeud de l'activity ouverte + treeHelper.selectOpenNode(ActivitySeineDto.class); + + // on conserve le path de l'activity + TreePath path = tree.getSelectionPath(); + + // recuperation de l'écran associé + ActivitySeineUI selectedUI = (ActivitySeineUI) + ObserveSwingApplicationContext.get().getContentUIManager().getSelectedContentUI(); + + // fermeture de l'activity + selectedUI.closeData(); + + if (wasCollapsed) { + + // on ferme le noeud de l'activity (qui a ete ouvert + // lors de la selection de celle-ci) + tree.collapsePath(path); + } + + // retour sur le noeud des activitys + treeHelper.selectNode(node); + + return; + } + + if (ui instanceof ActivityLonglinesUI) { + + // cas particulier pour l'écran des activités + + JTree tree = getMainUI().getNavigation(); + ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); + + // recuperation du noeud courant (activitys) + ObserveNode node = treeHelper.getSelectedNode(); + + boolean wasCollapsed = isOpenActivityNodeCollapsed( + tree, + treeHelper, + getMainUI().getDataContext() + ); + + // selection du noeud de l'activity ouverte + treeHelper.selectOpenNode(ActivityLonglineDto.class); + + // on conserve le path de l'activity + TreePath path = tree.getSelectionPath(); + + // recuperation de l'écran associé + ActivityLonglineUI selectedUI = (ActivityLonglineUI) + ObserveSwingApplicationContext.get().getContentUIManager().getSelectedContentUI(); + + // fermeture de l'activity + selectedUI.closeData(); + + if (wasCollapsed) { + + // on ferme le noeud de l'activity (qui a ete ouvert + // lors de la selection de celle-ci) + tree.collapsePath(path); + } + + // retour sur le noeud des activitys + treeHelper.selectNode(node); + + return; + } + + throw new IllegalStateException("Can not come here!"); + }); + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/DeleteDataUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/DeleteDataUIAction.java new file mode 100644 index 0000000..c2a34ca --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/DeleteDataUIAction.java @@ -0,0 +1,80 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.actions.shared; + +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.content.ContentUI; + +import javax.swing.JComponent; +import javax.swing.SwingUtilities; +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.n; + +/** + * Action pour sélectionner un noeud (attaché à l'éditeur) dans l'arbre de + * navigation. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class DeleteDataUIAction extends AbstractUIAction { + + private static final long serialVersionUID = 1L; + + public static final String ACTION_NAME = "deleteData"; + + public DeleteDataUIAction(ObserveMainUI mainUI) { + super(mainUI, + ACTION_NAME, + n("observe.action.delete"), + n("observe.action.delete.tip"), + "delete" + ); + } + + @Override + public void actionPerformed(final ActionEvent e) { + + getMainUI().setBusy(true); + + SwingUtilities.invokeLater(() -> { + try { + + JComponent c = (JComponent) e.getSource(); + ContentUI<?> ui = (ContentUI<?>) + c.getClientProperty("ui"); + if (ui == null) { + throw new IllegalStateException( + "could not find client property " + + "ui on component" + c); + } + + + ui.delete(); + } finally { + getMainUI().setBusy(false); + } + + }); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/DeleteReferenceUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/DeleteReferenceUIAction.java new file mode 100644 index 0000000..2570ac3 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/DeleteReferenceUIAction.java @@ -0,0 +1,74 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.actions.shared; + +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.content.ContentUI; + +import javax.swing.JComponent; +import javax.swing.SwingUtilities; +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.n; + +/** + * Action pour sélectionner un noeud (attaché à l'éditeur) dans l'arbre de + * navigation. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class DeleteReferenceUIAction extends AbstractUIAction { + + private static final long serialVersionUID = 1L; + + public static final String ACTION_NAME = "deleteReferentiel"; + + public DeleteReferenceUIAction(ObserveMainUI mainUI) { + super(mainUI, + ACTION_NAME, + n("observe.action.delete"), + n("observe.action.delete.tip"), + "delete" + ); + } + + @Override + public void actionPerformed(final ActionEvent e) { + SwingUtilities.invokeLater(() -> { + try { + JComponent c = (JComponent) e.getSource(); + + ContentUI<?> ui = (ContentUI<?>) + c.getClientProperty("ui"); + if (ui == null) { + throw new IllegalStateException( + "could not find client property " + + "ui on component" + c); + } + ui.delete(); + } finally { + getMainUI().setBusy(false); + } + }); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/GoDownUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/GoDownUIAction.java new file mode 100644 index 0000000..3ee8dd6 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/GoDownUIAction.java @@ -0,0 +1,151 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.actions.shared; + +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.content.ObserveContentUI; +import fr.ird.observe.application.swing.ui.tree.AbstractObserveTreeCellRenderer; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; + +import javax.swing.AbstractButton; +import javax.swing.Action; +import javax.swing.Icon; +import javax.swing.JComponent; +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; +import javax.swing.SwingUtilities; +import java.awt.Color; +import java.awt.event.ActionEvent; +import java.util.Enumeration; + +import static org.nuiton.i18n.I18n.n; + +/** + * Action pour sélectionner un noeud (attaché à l'éditeur) dans l'arbre de + * navigation. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class GoDownUIAction extends AbstractUIAction { + + private static final long serialVersionUID = 1L; + + public static final String ACTION_NAME = "goDown"; + + public GoDownUIAction(ObserveMainUI mainUI) { + super(mainUI, + ACTION_NAME, + n("observe.action.goDown"), + n("observe.action.goDown.tip"), + "go-down" + ); + } + + @Override + public void actionPerformed(final ActionEvent e) { + + SwingUtilities.invokeLater(() -> { + JComponent c = (JComponent) e.getSource(); + JPopupMenu p = (JPopupMenu) + c.getClientProperty("popup"); + if (p == null) { + throw new IllegalStateException( + "could not find client property " + + "popup on component" + c); + } + p.show(c, 2, c.getHeight()); + }); + } + + @Override + public void initAction(ObserveContentUI<?> ui, AbstractButton editor) { + super.initAction(ui, editor); + editor.putClientProperty("popup", getMainUI().getScopeDownPopup()); + } + + @Override + public void updateAction(ObserveContentUI<?> ui, AbstractButton editor) { + ObserveMainUI mainUI = getMainUI(); + + ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); + + AbstractObserveTreeCellRenderer render = treeHelper.getTreeCellRenderer(); + + ObserveNode node; + + super.updateAction(ui, editor); + + JPopupMenu scopePopup = mainUI.getScopeDownPopup(); + Action action = + mainUI.getRootPane().getActionMap().get(SelectNodeUIAction.ACTION_NAME); + node = treeHelper.getSelectedNode(); + ObserveNode nodeOriginal = node; + scopePopup.removeAll(); + Enumeration<?> e = node.children(); + while (e.hasMoreElements()) { + node = (ObserveNode) e.nextElement(); + String text = render.getNodeText(node); + if (text == null) { + continue; + } + Color color = + render.getNavigationTextColor(node); + Icon icon = render.getNavigationIcon(node, "-16"); + JMenuItem mi = new JMenuItem(); + mi.setAction(action); + mi.setText(text.trim()); + mi.setIcon(icon); + mi.setForeground(color); + mi.putClientProperty("node", node); + mi.putClientProperty("ui", ui); + mi.setAction(action); + scopePopup.add(mi); + } + + if (nodeOriginal.getChildCount() == 1 && + !nodeOriginal.getChildAt(0).isLeaf()) { + e = nodeOriginal.getChildAt(0).children(); + while (e.hasMoreElements()) { + node = (ObserveNode) e.nextElement(); + Color color = render.getNavigationTextColor( + node); + Icon icon = render.getNavigationIcon(node, "-16"); + String text = render.getNodeText(node); + JMenuItem mi = new JMenuItem(); + mi.setAction(action); + mi.setText(text.trim()); + mi.setIcon(icon); + mi.setForeground(color); + mi.putClientProperty("node", node); + mi.putClientProperty("ui", ui); + mi.setAction(action); + scopePopup.add(mi); + } + } + + int nbNodes = scopePopup.getComponentCount(); + + editor.setEnabled(nbNodes > 0); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/GoUpUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/GoUpUIAction.java new file mode 100644 index 0000000..9434a5a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/GoUpUIAction.java @@ -0,0 +1,129 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.actions.shared; + +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.content.ObserveContentUI; +import fr.ird.observe.application.swing.ui.tree.AbstractObserveTreeCellRenderer; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; + +import javax.swing.AbstractButton; +import javax.swing.Action; +import javax.swing.Icon; +import javax.swing.JComponent; +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; +import javax.swing.SwingUtilities; +import javax.swing.tree.TreeNode; +import java.awt.Color; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.n; + +/** + * Action pour sélectionner un noeud (attaché à l'éditeur) dans l'arbre de + * navigation. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class GoUpUIAction extends AbstractUIAction { + + private static final long serialVersionUID = 1L; + + public static final String ACTION_NAME = "goUp"; + + public GoUpUIAction(ObserveMainUI mainUI) { + super(mainUI, + ACTION_NAME, + n("observe.action.goUp"), + n("observe.action.goUp.tip"), + "go-up" + ); + } + + @Override + public void actionPerformed(final ActionEvent e) { + + SwingUtilities.invokeLater(() -> { + JComponent c = (JComponent) e.getSource(); + JPopupMenu p = (JPopupMenu) c.getClientProperty("popup"); + if (p == null) { + throw new IllegalStateException( + "could not find client property " + + "popup on component" + c); + } + p.show(c, 2, c.getHeight()); + }); + } + + @Override + public void initAction(ObserveContentUI<?> ui, AbstractButton editor) { + super.initAction(ui, editor); + editor.putClientProperty("popup", getMainUI().getScopeUpPopup()); + } + + @Override + public void updateAction(ObserveContentUI<?> ui, AbstractButton editor) { + super.updateAction(ui, editor); + + ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); + + AbstractObserveTreeCellRenderer render = treeHelper.getTreeCellRenderer(); + + ObserveNode node; + + JPopupMenu scopePopup = getMainUI().getScopeUpPopup(); + + Action action = + getMainUI().getRootPane().getActionMap().get(SelectNodeUIAction.ACTION_NAME); + + node = treeHelper.getSelectedNode(); + TreeNode root = node.getRoot(); + scopePopup.removeAll(); + scopePopup.setLayout(new GridLayout(0, 1)); + while (!root.equals(node.getParent())) { + node = node.getParent(); + Color color = + render.getNavigationTextColor(node); + Icon icon = render.getNavigationIcon(node, "-16"); + String text = render.getNodeText(node); + JMenuItem mi = new JMenuItem(); + mi.setAction(action); + mi.setText(text.trim()); + mi.setIcon(icon); + mi.setForeground(color); + mi.setBackground(Color.WHITE); + mi.putClientProperty("node", node); + mi.putClientProperty("ui", ui); + mi.setAction(action); + scopePopup.add(mi); + } + scopePopup.revalidate(); + + int nbNodes = scopePopup.getComponentCount(); + + editor.setEnabled(nbNodes > 0); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/MoveActivityLonglinesUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/MoveActivityLonglinesUIAction.java new file mode 100644 index 0000000..3eae513 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/MoveActivityLonglinesUIAction.java @@ -0,0 +1,197 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.actions.shared; + +import fr.ird.observe.application.swing.ObserveOpenDataManager; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.decoration.decorators.DataReferenceDecorator; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.longline.ActivityLonglineDto; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.service.longline.ActivityLonglineService; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.content.ContentUI; +import fr.ird.observe.application.swing.ui.content.list.impl.longline.ActivityLonglinesUI; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import fr.ird.observe.application.swing.ui.tree.TripLonglineNode; +import fr.ird.observe.application.swing.ui.util.DecoratedNodeEntity; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JComponent; +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import java.awt.event.ActionEvent; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Action pour changer le programme d'une ou plusieurs marée dans la liste. + * + * @author Kevin Morin (Code Lutin) + * @since 5.0 + */ +public class MoveActivityLonglinesUIAction extends AbstractUIAction { + + private static final long serialVersionUID = 1L; + + /** + * Logger. + */ + private static final Log log = LogFactory.getLog(MoveActivityLonglinesUIAction.class); + + public static final String ACTION_NAME = "moveActivityLonglines"; + + public MoveActivityLonglinesUIAction(ObserveMainUI mainUI) { + super(mainUI, + ACTION_NAME, + n("observe.content.action.move.activities.longline"), + n("observe.content.action.move.activities.longline.tip"), + "move-activities" + ); + } + + @Override + public void actionPerformed(final ActionEvent e) { + + SwingUtilities.invokeLater(() -> { + JComponent c = (JComponent) e.getSource(); + ContentUI<?> ui = (ContentUI<?>) + c.getClientProperty("ui"); + if (ui == null) { + throw new IllegalStateException( + "could not find client property " + + "ui on component" + c); + } + + if (!(ui instanceof ActivityLonglinesUI)) { + throw new IllegalStateException("Can not come here!"); + } + ActivityLonglinesUI activityLonglinesUI = (ActivityLonglinesUI) ui; + + + // get current triplongline id + ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); + ObserveNode oldActivitiesNode = treeHelper.getSelectedNode(); + ObserveNode oldTripLonglineNode = oldActivitiesNode.getParent(); + + // choose the new tripLongline + String tripLonglineId = chooseNewTripLongline(ui, oldTripLonglineNode); + + if (tripLonglineId != null) { + + if (log.isInfoEnabled()) { + log.info("Will move activities to trip: " + tripLonglineId); + } + // change the tripLongline of the selected activities + List<DataReference<ActivityLonglineDto>> selectedDatas = activityLonglinesUI.getModel().getSelectedDatas(); + List<String> activityIds = selectedDatas.stream() + .map(DataReference.ID_FUNCTION) + .collect(Collectors.toList()); + ActivityLonglineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivityLonglineService(); +// List<Integer> positions = + service.moveActivityLonglinesToTripLongline(activityIds, tripLonglineId); + + // update the tree + updateTree(oldActivitiesNode, tripLonglineId, activityIds); + } + + }); + + } + + protected String chooseNewTripLongline(ContentUI<?> ui, ObserveNode oldTripLonglineNode) { + ObserveNode programNode = oldTripLonglineNode.getParent(); + String oldTripLonglineId = oldTripLonglineNode.getId(); + int tripLonglineNb = programNode.getChildCount(); + + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + DataReferenceDecorator<TripLonglineDto> decorator = applicationContext.getDecoratorService().getDataReferenceDecorator(TripLonglineDto.class); + + //on crée un tableau avec une marée en moins car on ne propose pas la marée actuelle + DecoratedNodeEntity[] decoratedTripLonglines = new DecoratedNodeEntity[tripLonglineNb - 1]; + + int j = 0; + for (int i = 0; i < tripLonglineNb; i++) { + + TripLonglineNode tripLonglineNode = (TripLonglineNode) programNode.getChildAt(i); + + String tripLonglineId = tripLonglineNode.getId(); + + if (!oldTripLonglineId.equals(tripLonglineId)) { + decoratedTripLonglines[j++] = DecoratedNodeEntity.newDecoratedNodeEntity(tripLonglineNode, decorator); + } + } + + Object decoratedTripLongline = JOptionPane.showInputDialog(ui, + t("observe.action.choose.tripLongline.message"), + t("observe.action.choose.tripLongline.title"), + JOptionPane.QUESTION_MESSAGE, + null, + decoratedTripLonglines, + null); + return decoratedTripLongline != null ? ((DecoratedNodeEntity) decoratedTripLongline).getId() : null; + } + + protected void updateTree(ObserveNode oldActivitiesNode, + String tripLonglineId, + List<String> activityIds) { + + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ObserveOpenDataManager openDataManager = applicationContext.getOpenDataManager(); + ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); + + ObserveNode oldTripLonglineNode = oldActivitiesNode.getParent(); + ObserveNode programNode = oldTripLonglineNode.getParent(); + ObserveNode newTripLonglineNode = treeHelper.getChild(programNode, tripLonglineId); + String activitiesNodeId = DecoratorService.getPropertyLabel(ObserveTreeHelper.TREE_NODE_PREFIX, + TripLonglineDto.PROPERTY_ACTIVITY_LONGLINE); + ObserveNode newActivitiesNode = treeHelper.getChild(newTripLonglineNode, activitiesNodeId); + + // Let's check if we're moving an open activity + Optional<String> openActivity = activityIds + .stream() + .filter(openDataManager::isOpenActivityLongline) + .findFirst(); + + // If so, we close it to avoid ending up with an open activity into a closed trip. + if (openActivity.isPresent()) { + openDataManager.closeActivityLongline(openActivity.get()); + } + + // Let's reload the sub tree of each activities node. + // As the change have already be done in database, we just call the child loaders to regenerate the activities nodes sub trees + treeHelper.reloadNodeSubTree(oldActivitiesNode, true); + treeHelper.reloadNodeSubTree(newActivitiesNode, true); + + // Let's put the focus on the activities node which received the activities + treeHelper.selectNode(newActivitiesNode); + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/MoveActivitySeinesUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/MoveActivitySeinesUIAction.java new file mode 100644 index 0000000..db642f9 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/MoveActivitySeinesUIAction.java @@ -0,0 +1,192 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.actions.shared; + +import fr.ird.observe.application.swing.ObserveOpenDataManager; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.decoration.decorators.DataReferenceDecorator; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.services.service.seine.ActivitySeineService; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.content.ContentUI; +import fr.ird.observe.application.swing.ui.content.list.impl.seine.ActivitySeinesUI; +import fr.ird.observe.application.swing.ui.content.list.impl.seine.ActivitySeinesUIModel; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import fr.ird.observe.application.swing.ui.tree.RouteSeineNode; +import fr.ird.observe.application.swing.ui.util.DecoratedNodeEntity; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JComponent; +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import java.awt.event.ActionEvent; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Action pour changer le programme d'une ou plusieurs marée dans la liste. + * + * @author Kevin Morin (Code Lutin) + * @since 5.0 + */ +public class MoveActivitySeinesUIAction extends AbstractUIAction { + + private static final long serialVersionUID = 1L; + + /** + * Logger. + */ + private static final Log log = LogFactory.getLog(MoveActivitySeinesUIAction.class); + + public static final String ACTION_NAME = "moveActivitySeines"; + + public MoveActivitySeinesUIAction(ObserveMainUI mainUI) { + super(mainUI, + ACTION_NAME, + n("observe.content.action.move.activities.seine"), + n("observe.content.action.move.activities.seine.tip"), + "move-activities" + ); + } + + @Override + public void actionPerformed(final ActionEvent e) { + + SwingUtilities.invokeLater(() -> { + JComponent c = (JComponent) e.getSource(); + ContentUI<?> ui = (ContentUI<?>) + c.getClientProperty("ui"); + if (ui == null) { + throw new IllegalStateException( + "could not find client property " + + "ui on component" + c); + } + + if (!(ui instanceof ActivitySeinesUI)) { + throw new IllegalStateException("Can not come here!"); + } + + // get current route id + ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); + ObserveNode oldActivitiesNode = treeHelper.getSelectedNode(); + ObserveNode oldRouteNode = oldActivitiesNode.getParent(); + + // choose the new route + String routeId = chooseNewRoute(ui, oldRouteNode); + + if (routeId != null) { + // change the route of the selected activities + List<DataReference<ActivitySeineDto>> selectedDatas = ((ActivitySeinesUIModel) ui.getModel()).getSelectedDatas(); + List<String> activityIds = selectedDatas.stream() + .map(DataReference.ID_FUNCTION) + .collect(Collectors.toList()) ; + ActivitySeineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivitySeineService(); + List<Integer> positions = service.moveActivitySeinesToRoute(activityIds, routeId); + + // update the tree + updateTree(oldActivitiesNode, routeId, activityIds); + } + + }); + + } + + protected String chooseNewRoute(ContentUI<?> ui, ObserveNode oldRouteNode) { + ObserveNode routesNode = oldRouteNode.getParent(); + String oldRouteId = oldRouteNode.getId(); + int routeNb = routesNode.getChildCount(); + + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + DataReferenceDecorator<RouteDto> decorator = applicationContext.getDecoratorService().getDataReferenceDecorator(RouteDto.class); + + //on crée un tableau avec une route en moins car on ne propose pas la route actuel + DecoratedNodeEntity[] decoratedRoutes = new DecoratedNodeEntity[routeNb - 1]; + + int j = 0; + for (int i = 0; i < routeNb; i++) { + + RouteSeineNode routeNode = (RouteSeineNode) routesNode.getChildAt(i); + + String routeId = routeNode.getId(); + + if (!oldRouteId.equals(routeId)) { + decoratedRoutes[j++] = DecoratedNodeEntity.newDecoratedNodeEntity(routeNode, decorator); + } + } + + Object decoratedRoute = JOptionPane.showInputDialog(ui, + t("observe.action.choose.route.message"), + t("observe.action.choose.route.title"), + JOptionPane.QUESTION_MESSAGE, + null, + decoratedRoutes, + null); + + return decoratedRoute != null ? ((DecoratedNodeEntity) decoratedRoute).getId() : null; + } + + protected void updateTree(ObserveNode oldActivitiesNode, + String routeId, + List<String> activityIds) { + + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ObserveOpenDataManager openDataManager = applicationContext.getOpenDataManager(); + ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); + + ObserveNode oldRouteNode = oldActivitiesNode.getParent(); + ObserveNode routesNode = oldRouteNode.getParent(); + ObserveNode tripNode = routesNode.getParent(); + ObserveNode newRouteNode = treeHelper.getChild(routesNode, routeId); + String activitiesNodeId = DecoratorService.getPropertyLabel(ObserveTreeHelper.TREE_NODE_PREFIX, + RouteDto.PROPERTY_ACTIVITY_SEINE); + ObserveNode newActivitiesNode = treeHelper.getChild(newRouteNode, activitiesNodeId); + + // Let's check if we're moving an open activity + Optional<String> openActivity = activityIds + .stream() + .filter(openDataManager::isOpenActivitySeine) + .findFirst(); + + // If so, we close it to avoid ending up with an open activity into a closed route. + if (openActivity.isPresent()) { + openDataManager.closeActivitySeine(openActivity.get()); + } + + // Let's reload the sub tree of each activities node. + // As the change have already be done in database, we just call the child loaders to regenerate the activities nodes sub trees + treeHelper.reloadNodeSubTree(oldActivitiesNode, true); + treeHelper.reloadNodeSubTree(newActivitiesNode, true); + + // Let's put the focus on the activities node which received the activities + treeHelper.selectNode(newActivitiesNode); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/MoveRoutesUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/MoveRoutesUIAction.java new file mode 100644 index 0000000..7c286b0 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/MoveRoutesUIAction.java @@ -0,0 +1,199 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.actions.shared; + +import fr.ird.observe.application.swing.ObserveOpenDataManager; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.decoration.decorators.DataReferenceDecorator; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.services.service.seine.RouteService; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.content.ContentUI; +import fr.ird.observe.application.swing.ui.content.list.impl.seine.RoutesUI; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import fr.ird.observe.application.swing.ui.tree.TripSeineNode; +import fr.ird.observe.application.swing.ui.util.DecoratedNodeEntity; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JComponent; +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import java.awt.event.ActionEvent; +import java.util.List; +import java.util.Optional; +import java.util.stream.Collectors; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Action pour changer le programme d'une ou plusieurs marée dans la liste. + * + * @author Kevin Morin (Code Lutin) + * @since 5.0 + */ +public class MoveRoutesUIAction extends AbstractUIAction { + + private static final long serialVersionUID = 1L; + + /** + * Logger. + */ + private static final Log log = LogFactory.getLog(MoveRoutesUIAction.class); + + public static final String ACTION_NAME = "moveRoutes"; + + public MoveRoutesUIAction(ObserveMainUI mainUI) { + super(mainUI, + ACTION_NAME, + n("observe.content.action.move.routes"), + n("observe.content.action.move.routes.tip"), + "move-routes" + ); + } + + @Override + public void actionPerformed(final ActionEvent e) { + + SwingUtilities.invokeLater(() -> { + JComponent c = (JComponent) e.getSource(); + ContentUI<?> ui = (ContentUI<?>) + c.getClientProperty("ui"); + if (ui == null) { + throw new IllegalStateException( + "could not find client property " + + "ui on component" + c); + } + + if (!(ui instanceof RoutesUI)) { + throw new IllegalStateException("Can not come here!"); + } + + RoutesUI theUi = (RoutesUI) ui; + + // get current tripseine id + ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); + ObserveNode oldRoutesNode = treeHelper.getSelectedNode(); + ObserveNode oldTripSeineNode = oldRoutesNode.getParent(); + + // choose the new tripseine + String tripSeineId = chooseNewTripSeine(theUi, oldTripSeineNode); + + if (tripSeineId != null) { + // change the tripseine of the selected routes + List<DataReference<RouteDto>> selectedDatas = theUi.getModel().getSelectedDatas(); + List<String> routeIds = selectedDatas.stream().map(DataReference.ID_FUNCTION).collect(Collectors.toList()); + RouteService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newRouteService(); + List<Integer> positions = service.moveRoutesToTripSeine(routeIds, tripSeineId); + + // update the tree + updateTree(oldRoutesNode, tripSeineId, routeIds); + } + + }); + + } + + protected String chooseNewTripSeine(ContentUI<?> ui, ObserveNode oldTripSeineNode) { + ObserveNode programNode = oldTripSeineNode.getParent(); + String oldTripSeineId = oldTripSeineNode.getId(); + int tripSeineNb = programNode.getChildCount(); + + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + DataReferenceDecorator<TripSeineDto> decorator = applicationContext.getDecoratorService().getDataReferenceDecorator(TripSeineDto.class); + + //on crée un tableau avec une marée en moins car on ne propose pas la marée actuel + DecoratedNodeEntity[] decoratedTripSeines = new DecoratedNodeEntity[tripSeineNb - 1]; + + int j = 0; + for (int i = 0; i < tripSeineNb; i++) { + + TripSeineNode tripSeineNode = (TripSeineNode) programNode.getChildAt(i); + + String tripSeineId = tripSeineNode.getId(); + + if (!oldTripSeineId.equals(tripSeineId)) { + decoratedTripSeines[j++] = DecoratedNodeEntity.newDecoratedNodeEntity(tripSeineNode, decorator); + } + } + + Object decoratedTripSeine = JOptionPane.showInputDialog(ui, + t("observe.action.choose.tripSeine.message"), + t("observe.action.choose.tripSeine.title"), + JOptionPane.QUESTION_MESSAGE, + null, + decoratedTripSeines, + null); + return decoratedTripSeine != null ? ((DecoratedNodeEntity) decoratedTripSeine).getId() : null; + } + + protected void updateTree(ObserveNode oldRoutesNode, + String tripSeineId, + List<String> routeIds) { + + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ObserveOpenDataManager openDataManager = applicationContext.getOpenDataManager(); + ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); + + ObserveNode oldTripSeineNode = oldRoutesNode.getParent(); + ObserveNode programNode = oldTripSeineNode.getParent(); + ObserveNode newTripSeineNode = treeHelper.getChild(programNode, tripSeineId); + String routesNodeId = DecoratorService.getPropertyLabel(ObserveTreeHelper.TREE_NODE_PREFIX, + TripSeineDto.PROPERTY_ROUTE); + ObserveNode newRoutesNode = treeHelper.getChild(newTripSeineNode, routesNodeId); + + // Let's check if we're moving an open route + Optional<String> openRoute = routeIds + .stream() + .filter(openDataManager::isOpenRoute) + .findFirst(); + + // If so, we close it to avoid ending up with an open route into a closed trip. + if (openRoute.isPresent()) { + openDataManager.closeRoute(openRoute.get()); + } + + // Let's reload the sub tree of each routes node. + // As the change have already be done in database, we just call the child loaders to regenerate the routes nodes sub trees + treeHelper.reloadNodeSubTree(oldRoutesNode, true); + treeHelper.reloadNodeSubTree(newRoutesNode, true); + + // 1. Select the newRoutesNode : + // only a selected node can be reloaded (@see fr.ird.observe.application.swing.ui.tree.ObserveTreeBridge.canLoadChild). + // (And also it's better for user experience because it puts the focus on the routes node which receive the routes) + // + // However, the node selection has to be done after that the trip has been opened : + // selecting the newRoutesNode opens a list layout which compute a rendering mode associated to the trip state. + // After the mode has been computed, it is injected in the list component which triggers listeners on associated components, such as buttons. + // + // That's why, if we do this before the trip is opened, + // we will end up with an incoherent list view (some buttons will be deactivated while they should be activated for instance) + treeHelper.selectNode(newRoutesNode); + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/MoveTripLonglinesUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/MoveTripLonglinesUIAction.java new file mode 100644 index 0000000..5201b2c --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/MoveTripLonglinesUIAction.java @@ -0,0 +1,85 @@ +package fr.ird.observe.application.swing.ui.actions.shared; + +/*- + * #%L + * ObServe :: Application Swing + * %% + * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.constants.GearType; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.service.longline.TripLonglineService; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.content.ContentUI; +import fr.ird.observe.application.swing.ui.content.list.impl.longline.TripLonglinesUI; +import fr.ird.observe.application.swing.ui.content.list.impl.longline.TripLonglinesUIModel; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Kevin Morin (Code Lutin) + * @since 5.0 + */ +public class MoveTripLonglinesUIAction extends MoveTripsUIAction<TripLonglineDto> { + + private static final long serialVersionUID = 1L; + + /** + * Logger. + */ + private static final Log log = LogFactory.getLog(MoveTripLonglinesUIAction.class); + + public static final String ACTION_NAME = "moveTripLonglines"; + + public MoveTripLonglinesUIAction(ObserveMainUI mainUI) { + super(mainUI, ACTION_NAME); + } + + @Override + protected void checkUIClass(ContentUI<?> ui) throws IllegalStateException { + if (!(ui instanceof TripLonglinesUI)) { + throw new IllegalStateException("Can not come here!"); + } + } + + @Override + protected GearType getGearType(ContentUI<?> ui) { + return GearType.longline; + } + + @Override + protected List<Integer> getPositions(List<String> tripIds, String programId) { + TripLonglineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripLonglineService(); + return service.moveTripLonglinesToProgram(tripIds, programId); + } + + @Override + protected void updateModelData(ContentUI<?> ui) { + TripLonglinesUI tripLonglinesUI = (TripLonglinesUI) ui; + TripLonglinesUIModel model = tripLonglinesUI.getModel(); + List<DataReference<TripLonglineDto>> data = new ArrayList<>(model.getData()); + data.removeAll(model.getSelectedDatas()); + model.setData(data); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/MoveTripSeinesUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/MoveTripSeinesUIAction.java new file mode 100644 index 0000000..a0154ca --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/MoveTripSeinesUIAction.java @@ -0,0 +1,85 @@ +package fr.ird.observe.application.swing.ui.actions.shared; + +/*- + * #%L + * ObServe :: Application Swing + * %% + * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.constants.GearType; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.services.service.seine.TripSeineService; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.content.ContentUI; +import fr.ird.observe.application.swing.ui.content.list.impl.seine.TripSeinesUI; +import fr.ird.observe.application.swing.ui.content.list.impl.seine.TripSeinesUIModel; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Kevin Morin (Code Lutin) + * @since 5.0 + */ +public class MoveTripSeinesUIAction extends MoveTripsUIAction<TripSeineDto> { + + private static final long serialVersionUID = 1L; + + /** + * Logger. + */ + private static final Log log = LogFactory.getLog(MoveTripSeinesUIAction.class); + + public static final String ACTION_NAME = "moveTripSeines"; + + public MoveTripSeinesUIAction(ObserveMainUI mainUI) { + super(mainUI, ACTION_NAME); + } + + @Override + protected void checkUIClass(ContentUI<?> ui) throws IllegalStateException { + if (!(ui instanceof TripSeinesUI)) { + throw new IllegalStateException("Can not come here!"); + } + } + + @Override + protected GearType getGearType(ContentUI<?> ui) { + return GearType.seine; + } + + @Override + protected List<Integer> getPositions(List<String> tripIds, String programId) { + TripSeineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripSeineService(); + return service.moveTripSeinesToProgram(tripIds, programId); + } + + @Override + protected void updateModelData(ContentUI<?> ui) { + TripSeinesUI tripSeinesUI = (TripSeinesUI) ui; + TripSeinesUIModel model = tripSeinesUI.getModel(); + List<DataReference<TripSeineDto>> data = new ArrayList<>(model.getData()); + data.removeAll(model.getSelectedDatas()); + model.setData(data); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/MoveTripsUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/MoveTripsUIAction.java new file mode 100644 index 0000000..387408e --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/MoveTripsUIAction.java @@ -0,0 +1,197 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.actions.shared; + +import fr.ird.observe.application.swing.ObserveOpenDataManager; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.DataDto; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.constants.GearType; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.content.ContentUI; +import fr.ird.observe.application.swing.ui.content.list.ContentListUIModel; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import fr.ird.observe.application.swing.ui.tree.menu.MoveTripNodeMenuPopulator; +import fr.ird.observe.application.swing.ui.util.DecoratedNodeEntity; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JComponent; +import javax.swing.JOptionPane; +import javax.swing.SwingUtilities; +import java.awt.event.ActionEvent; +import java.util.ArrayList; +import java.util.List; +import java.util.stream.Collectors; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Action pour changer le programme d'une ou plusieurs marée dans la liste. + * + * @author Kevin Morin (Code Lutin) + * @since 5.0 + */ +public abstract class MoveTripsUIAction<T extends DataDto> extends AbstractUIAction { + + private static final long serialVersionUID = 1L; + + /** + * Logger. + */ + private static final Log log = LogFactory.getLog(MoveTripsUIAction.class); + + public static final String ACTION_NAME = "moveTrips"; + + public MoveTripsUIAction(ObserveMainUI mainUI, String actionName) { + super(mainUI, + actionName, + n("observe.content.action.move.trips"), + n("observe.content.action.move.trips.tip"), + "move-trips" + ); + } + + @Override + public void actionPerformed(final ActionEvent e) { + + SwingUtilities.invokeLater(() -> { + JComponent c = (JComponent) e.getSource(); + ContentUI<?> ui = (ContentUI<?>) + c.getClientProperty("ui"); + if (ui == null) { + throw new IllegalStateException( + "could not find client property " + + "ui on component" + c); + } + + checkUIClass(ui); + + // get current program id + ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); + ObserveNode oldProgramNode = treeHelper.getSelectedNode(); + String oldProgramId = oldProgramNode.getId(); + + // choose the new program + String programId = chooseNewProgram(ui, oldProgramId); + + if (programId != null) { + + // change the program of the selected trips + List<DataReference<T>> selectedDatas = ((ContentListUIModel) ui.getModel()).getSelectedDatas(); + List<String> tripIds = selectedDatas.stream().map(DataReference.ID_FUNCTION).collect(Collectors.toList()); + List<Integer> positions = getPositions(tripIds, programId); + + // update the tree + updateTree(ui, oldProgramNode, oldProgramId, programId, tripIds, positions); + } + + }); + + } + + protected String chooseNewProgram(ContentUI<?> ui, String oldProgramId) { + + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + + ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); + + GearType geartype = getGearType(ui); + + // racine + ObserveNode rootNode = treeHelper.getRootNode(); + + //on crée un tableau avec un programme en moins car on ne propose pas le programme actuel + List<DecoratedNodeEntity> decoratedProgramList = new ArrayList<>(); + + MoveTripNodeMenuPopulator.createPossibleParents(oldProgramId, decoratedProgramList, geartype, rootNode); + + DecoratedNodeEntity[] decoratedPrograms = + decoratedProgramList.toArray(new DecoratedNodeEntity[decoratedProgramList.size()]); + + DecoratedNodeEntity decoratedProgram = (DecoratedNodeEntity) JOptionPane.showInputDialog(ui, + t("observe.action.choose.program.message"), + t("observe.action.choose.program.title"), + JOptionPane.QUESTION_MESSAGE, + null, + decoratedPrograms, + null); + + return decoratedProgram == null ? null : decoratedProgram.getId(); + } + + protected void updateTree(ContentUI<?> ui, + ObserveNode oldProgramNode, + String oldProgramId, + String programId, + List<String> tripIds, + List<Integer> positions) { + + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ObserveOpenDataManager openDataManager = applicationContext.getOpenDataManager(); + ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); + + ObserveNode rootNode = treeHelper.getRootNode(); + ObserveNode newProgramNode = treeHelper.getChild(rootNode, programId); + + for (int i = 0, s = positions.size(); i < s; i++) { + + String tripId = tripIds.get(i); + ObserveNode tripNode = treeHelper.getChild(oldProgramNode, tripId); + boolean wasOpen = tripNode.isOpen(); + treeHelper.removeNode(tripNode); + + if (wasOpen) { + openDataManager.closeProgram(oldProgramId); + openDataManager.openProgram(programId); + } + + ObserveNode newTripNode = treeHelper.getChild(newProgramNode, tripId); + + if (newTripNode == null) { + + // create it + if (log.isInfoEnabled()) { + log.info("Insert trip node: "); + } + treeHelper.insertNode(newProgramNode, tripNode, positions.get(i)); + } + } + + updateModelData(ui); + + treeHelper.reloadNode(oldProgramNode, true); + treeHelper.reloadNode(newProgramNode, true); + treeHelper.selectNode(newProgramNode); + } + + protected abstract void checkUIClass(ContentUI<?> ui) throws IllegalStateException; + + protected abstract GearType getGearType(ContentUI<?> ui); + + protected abstract List<Integer> getPositions(List<String> tripIds, String programId); + + protected abstract void updateModelData(ContentUI<?> ui); + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/ReOpenUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/ReOpenUIAction.java new file mode 100644 index 0000000..8b37959 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/ReOpenUIAction.java @@ -0,0 +1,103 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.actions.shared; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.content.ContentUI; +import fr.ird.observe.application.swing.ui.content.list.ContentListUI; +import fr.ird.observe.application.swing.ui.content.open.ContentOpenableUI; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; + +import javax.swing.JComponent; +import javax.swing.SwingUtilities; +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.n; + +/** + * Action pour sélectionner un noeud (attaché à l'éditeur) dans l'arbre de + * navigation. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ReOpenUIAction extends AbstractUIAction { + + private static final long serialVersionUID = 1L; + + public static final String ACTION_NAME = "reopen"; + + public ReOpenUIAction(ObserveMainUI mainUI) { + super(mainUI, + ACTION_NAME, + n("observe.content.action.reopen"), + n("observe.content.action.reopen.tip"), + "reopen" + ); + } + + @Override + public void actionPerformed(final ActionEvent e) { + SwingUtilities.invokeLater(() -> { + JComponent c = (JComponent) e.getSource(); + ContentUI<?> ui = (ContentUI<?>) + c.getClientProperty("ui"); + + if (ui == null) { + throw new IllegalStateException( + "could not find client property ui " + + "on component" + c); + } + + ContentOpenableUI<?> openUI; + + if (ui instanceof ContentOpenableUI<?>) { + + openUI = (ContentOpenableUI<?>) ui; + } else if (ui instanceof ContentListUI<?, ?>) { + + DataReference<?> selectedData = ((ContentListUI<?, ?>) ui).getSelectedData(); + + String id = selectedData.getId(); + + ObserveTreeHelper treeHelper = ui.getTreeHelper(); + ObserveNode selectedNode = treeHelper.getSelectedNode(); + ObserveNode node = treeHelper.findNode(selectedNode, id); + + treeHelper.selectNode(node); + + openUI = (ContentOpenableUI<?>) + ObserveSwingApplicationContext.get().getContentUIManager().getSelectedContentUI(); + + } else { + throw new IllegalStateException("The action " + ACTION_NAME + " can not be executed from ui " + ui); + } + + if (openUI != null) { + openUI.openData(); + } + }); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/ResetEditUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/ResetEditUIAction.java new file mode 100644 index 0000000..f99e1a1 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/ResetEditUIAction.java @@ -0,0 +1,69 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.actions.shared; + +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.content.ContentUI; + +import javax.swing.JComponent; +import javax.swing.SwingUtilities; +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.n; + +/** + * Action pour sélectionner un noeud (attaché à l'éditeur) dans l'arbre de + * navigation. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ResetEditUIAction extends AbstractUIAction { + + private static final long serialVersionUID = 1L; + + public static final String ACTION_NAME = "reset"; + + public ResetEditUIAction(ObserveMainUI mainUI) { + super(mainUI, + ACTION_NAME, + n("observe.content.action.reset"), + n("observe.content.action.reset.tip"), + "revert" + ); + } + + @Override + public void actionPerformed(final ActionEvent e) { + SwingUtilities.invokeLater(() -> { + JComponent c = (JComponent) e.getSource(); + ContentUI<?> ui = (ContentUI<?>) + c.getClientProperty("ui"); + if (ui == null) { + throw new IllegalStateException( + "could not find client property " + + "ui on component" + c); + } + ui.resetEdit(); + }); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/SaveEditUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/SaveEditUIAction.java new file mode 100644 index 0000000..60e0b48 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/SaveEditUIAction.java @@ -0,0 +1,69 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.actions.shared; + +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.content.ContentUI; + +import javax.swing.JComponent; +import javax.swing.SwingUtilities; +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.n; + +/** + * Action pour sélectionner un noeud (attaché à l'éditeur) dans l'arbre de + * navigation. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class SaveEditUIAction extends AbstractUIAction { + + private static final long serialVersionUID = 1L; + + public static final String ACTION_NAME = "save"; + + public SaveEditUIAction(ObserveMainUI mainUI) { + super(mainUI, + ACTION_NAME, + n("observe.action.save"), + n("observe.action.save.tip"), + ACTION_NAME + ); + } + + @Override + public void actionPerformed(final ActionEvent e) { + SwingUtilities.invokeLater(() -> { + JComponent c = (JComponent) e.getSource(); + ContentUI<?> ui = (ContentUI<?>) + c.getClientProperty("ui"); + if (ui == null) { + throw new IllegalStateException( + "could not find client property " + + "ui on component" + c); + } + ui.save(true); + }); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/SelectNodeUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/SelectNodeUIAction.java new file mode 100644 index 0000000..0d7e2e0 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/SelectNodeUIAction.java @@ -0,0 +1,62 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.actions.shared; + +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; + +import javax.swing.JComponent; +import java.awt.event.ActionEvent; + +import static org.nuiton.i18n.I18n.n; + +/** + * Action pour sélectionner un noeud (attaché à l'éditeur) dans l'arbre de + * navigation. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class SelectNodeUIAction extends AbstractUIAction { + + private static final long serialVersionUID = 1L; + + public static final String ACTION_NAME = "selectNode"; + + public static final String NODE = "node"; + + public SelectNodeUIAction(ObserveMainUI mainUI) { + super(mainUI, + ACTION_NAME, + n("observe.action.selectNode"), + n("observe.action.selectNode.tip"), + "go-jump" + ); + } + + @Override + public void actionPerformed(ActionEvent e) { + JComponent source = (JComponent) e.getSource(); + ObserveNode node = (ObserveNode) source.getClientProperty(NODE); + getMainUI().getTreeHelper().selectNode(node); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/SelectOpenNodeUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/SelectOpenNodeUIAction.java new file mode 100644 index 0000000..1b6afb1 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/actions/shared/SelectOpenNodeUIAction.java @@ -0,0 +1,58 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.actions.shared; + +import fr.ird.observe.application.swing.ui.ObserveMainUI; + +import javax.swing.JComponent; +import java.awt.event.ActionEvent; + +/** + * Action pour sélectionner un noeud (attaché à l'éditeur) dans l'arbre de + * navigation. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class SelectOpenNodeUIAction extends AbstractUIAction { + + public static final String ACTION_NAME = "selectOpen"; + + private static final long serialVersionUID = 1L; + + public SelectOpenNodeUIAction(ObserveMainUI mainUI) { + super(mainUI, ACTION_NAME, "<NONE>", "<NONE>", "go-down"); + } + + @Override + public void actionPerformed(ActionEvent e) { + + JComponent c = (JComponent) e.getSource(); + Class<?> type = (Class<?>) c.getClientProperty("type"); + if (type == null) { + throw new IllegalStateException( + "could not find client property " + + "type on component" + c); + } + getMainUI().getTreeHelper().selectOpenNode(type); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminActionModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminActionModel.java new file mode 100644 index 0000000..938096a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminActionModel.java @@ -0,0 +1,38 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin; + +import jaxx.runtime.swing.wizard.ext.WizardExtStepModel; + +/** + * Le modèle de base pour les actions. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public abstract class AdminActionModel extends WizardExtStepModel<AdminStep> { + + protected AdminActionModel(AdminStep objectOperation) { + super(objectOperation); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminActionWorker.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminActionWorker.java new file mode 100644 index 0000000..e63f3e6 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminActionWorker.java @@ -0,0 +1,57 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin; + +import jaxx.runtime.swing.application.ActionWorker; +import jaxx.runtime.swing.wizard.ext.WizardState; + +import java.util.concurrent.Callable; + +/** + * Un worker pour les opération longues d'administration. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class AdminActionWorker extends ActionWorker<WizardState, String> { + + protected final AdminTabUIHandler handler; + + protected AdminActionWorker(AdminTabUIHandler handler, + String actionLabel) { + super(actionLabel); + this.handler = handler; + } + + public static AdminActionWorker newWorker( + AdminTabUIHandler handler, + String actionLabel, + Callable<WizardState> target) { + AdminActionWorker adminActionWorker = new AdminActionWorker(handler, actionLabel); + adminActionWorker.setTarget(target); + return adminActionWorker; + } + + public AdminTabUIHandler getHandler() { + return handler; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminStep.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminStep.java new file mode 100644 index 0000000..70d26f4 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminStep.java @@ -0,0 +1,451 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin; + +import fr.ird.observe.application.swing.db.constants.DbMode; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.admin.config.ConfigUI; +import fr.ird.observe.application.swing.ui.admin.config.SelectDataUI; +import fr.ird.observe.application.swing.ui.admin.consolidate.ConsolidateModel; +import fr.ird.observe.application.swing.ui.admin.consolidate.ConsolidateUI; +import fr.ird.observe.application.swing.ui.admin.synchronize.data.DataSynchroModel; +import fr.ird.observe.application.swing.ui.admin.synchronize.data.DataSynchroUI; +import fr.ird.observe.application.swing.ui.admin.export.ExportModel; +import fr.ird.observe.application.swing.ui.admin.export.ExportUI; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchroModel; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchroUI; +import fr.ird.observe.application.swing.ui.admin.report.ReportModel; +import fr.ird.observe.application.swing.ui.admin.report.ReportUI; +import fr.ird.observe.application.swing.ui.admin.resume.ShowResumeUI; +import fr.ird.observe.application.swing.ui.admin.save.SaveLocalModel; +import fr.ird.observe.application.swing.ui.admin.save.SaveLocalUI; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.legacy.SynchronizeModel; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.legacy.SynchronizeUI; +import fr.ird.observe.application.swing.ui.admin.validate.ValidateModel; +import fr.ird.observe.application.swing.ui.admin.validate.ValidateUI; +import jaxx.runtime.swing.wizard.ext.WizardExtStep; +import jaxx.runtime.swing.wizard.ext.WizardExtUI; + +import javax.swing.ImageIcon; +import java.lang.reflect.Constructor; +import java.util.EnumSet; + +import static org.nuiton.i18n.I18n.n; + +/** + * Pour caractériser les étapes (correspond aux onglets de l'ui). + * + * Chaque constante représente un onglet de l'ui et est responsable de + * l'instanciation des différents objets associés à un onglet, à savoir : + * <ul> + * <li>le model {@link #newModel()}</li> + * <li>l'ui {@link #newUI(WizardExtUI)} </li> + * </ul> + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public enum AdminStep implements WizardExtStep { + + /** pour configurer les actions à réaliser et voir la progression */ + CONFIG( + n("observe.actions.config.step"), + n("observe.actions.config.step.description"), + null, + ConfigUI.class, + true + ), + + /** pour selectionner les donnes */ + SELECT_DATA( + n("observe.actions.selectData.step"), + n("observe.actions.selectData.step.description"), + null, + SelectDataUI.class, + true + ), + + /** pour résoudre les entités obosolètes */ + SYNCHRONIZE( + n("observe.actions.synchro.referential.legacy.step"), + n("observe.actions.synchro.referential.legacy.step.description"), + n("observe.actions.synchro.referential.legacy"), + n("observe.actions.synchro.referential.legacy.tip"), + "synchronizeReferentiel", + n("observe.actions.synchro.referential.legacy"), + n("observe.actions.synchro.referential.legacy.description"), + SynchronizeModel.class, + SynchronizeUI.class, + true, + false, + true, + false, + DbMode.USE_LOCAL, + DbMode.USE_REMOTE + ), + + DATA_SYNCHRONIZE( + n("observe.actions.synchro.data.step"), + n("observe.actions.synchro.data.step.description"), + n("observe.actions.synchro.data.title"), + n("observe.actions.synchro.data.title.tip"), + "dataSynchronize", + n("observe.actions.synchro.data"), + n("observe.actions.synchro.data.description"), + DataSynchroModel.class, + DataSynchroUI.class, + true, + false, + false, + false, + DbMode.USE_LOCAL, + DbMode.USE_REMOTE, + DbMode.USE_SERVER + ), + + REFERENTIAL_SYNCHRONIZE( + n("observe.actions.synchro.referential.step"), + n("observe.actions.synchro.referential.step.description"), + n("observe.actions.synchro.referential.title"), + n("observe.actions.synchro.referential.title.tip"), + "referentialSynchronize", + n("observe.actions.synchro.referential"), + n("observe.actions.synchro.referential.description"), + ReferentialSynchroModel.class, + ReferentialSynchroUI.class, + true, + false, + false, + false, + DbMode.USE_LOCAL, + DbMode.USE_REMOTE, + DbMode.USE_SERVER + ), + + /** pour lancer la validation des donnees */ + VALIDATE( + n("observe.actions.validate.step"), + n("observe.actions.validate.step.description"), + n("observe.actions.validate.title"), + n("observe.actions.validate.title.tip"), + "validate", + n("observe.actions.validate"), + n("observe.actions.validate.description"), + ValidateModel.class, + ValidateUI.class, + false, + true, + false, + false, + DbMode.USE_LOCAL, + DbMode.USE_REMOTE, + DbMode.USE_SERVER + ), + + /** pour lancer la consolidation des données (mesure taille-poids...) */ + CONSOLIDATE( + n("observe.actions.consolidate.step"), + n("observe.actions.consolidate.step.description"), + n("observe.actions.consolidate.title"), + n("observe.actions.consolidate.title.tip"), + "consolidate", + n("observe.actions.consolidate"), + n("observe.actions.consolidate.description"), + ConsolidateModel.class, + ConsolidateUI.class, + false, + true, + false, + false, + DbMode.USE_LOCAL, + DbMode.USE_REMOTE, + DbMode.USE_SERVER + ), + + /** pour lancer la generation des rapports */ + REPORT( + n("observe.actions.report.step"), + n("observe.actions.report.step.description"), + n("observe.actions.report.title"), + n("observe.actions.report.title.tip"), + "report", + n("observe.actions.report"), + n("observe.actions.report.description"), + ReportModel.class, + ReportUI.class, + false, + true, + false, + false, + DbMode.USE_LOCAL, + DbMode.USE_REMOTE, + DbMode.USE_SERVER + ), + + /** pour effectuer les modifications vers la base locale */ + SAVE_LOCAL( + n("observe.actions.saveLocal.step"), + n("observe.actions.saveLocal.step.description"), + null, + null, + "save", + n("observe.actions.saveLocal"), + n("observe.actions.saveLocal.description"), + SaveLocalModel.class, + SaveLocalUI.class, + false, + false, + false, + false + ), + + /** pour effectuer les modifications vers la base distante */ + EXPORT_DATA( + n("observe.actions.exportData.step"), + n("observe.actions.exportData.step.description"), + n("observe.actions.exportData.title"), + n("observe.actions.exportData.title.tip"), + "remote-export", + n("observe.actions.exportData"), + n("observe.actions.exportData.description"), + ExportModel.class, + ExportUI.class, + true, + true, + false, + false, + DbMode.USE_LOCAL, + DbMode.USE_REMOTE, + DbMode.USE_SERVER + ), + + /** pour afficher après les opération un ecran de résumé */ + SHOW_RESUME( + n("observe.actions.showResume.step"), + n("observe.actions.showResume.step.description"), + null, + ShowResumeUI.class, + false + ); + + private final String iconName; + + private final String title; + + private final String titleTip; + + private final String label; + + private final String description; + + private final String operationLabel; + + private final String operationDescription; + + private final Class<? extends AdminActionModel> modelClass; + + private final Class<? extends AdminTabUI> uiClass; + + private final DbMode[] incomingModes; + + private final boolean needReferentiel; + + private final boolean needSave; + + private final boolean needSelect; + + private final boolean config; + + private transient ImageIcon icon; + + AdminStep(String label, + String description, + Class<? extends AdminActionModel> modelClass, + Class<? extends AdminTabUI> uiClass, + boolean config) { + this(label, + description, + null, + null, + null, + null, + null, + modelClass, + uiClass, + false, + false, + false, + config + ); + } + + AdminStep(String label, + String description, + String title, + String titleTip, + String iconName, + String operationLabel, + String operationDescription, + Class<? extends AdminActionModel> modelClass, + Class<? extends AdminTabUI> uiClass, + boolean needReferentiel, + boolean needSelect, + boolean needSave, + boolean config, + DbMode... incomingModes) { + this.label = label; + this.description = description; + this.title = title; + this.titleTip = titleTip; + this.iconName = iconName; + this.operationDescription = operationDescription; + this.operationLabel = operationLabel; + this.needReferentiel = needReferentiel; + this.needSave = needSave; + this.needSelect = needSelect; + this.modelClass = modelClass; + this.uiClass = uiClass; + this.config = config; + this.incomingModes = incomingModes; + } + + public static EnumSet<AdminStep> getOperations() { + EnumSet<AdminStep> operations = EnumSet.noneOf(AdminStep.class); + for (AdminStep step : AdminStep.values()) { + if (step.isOperation()) { + operations.add(step); + } + } + return operations; + } + + public static AdminStep valueOfIgnoreCase(String value) { + for (AdminStep step : AdminStep.values()) { + if (step.name().equalsIgnoreCase(value)) { + return step; + } + } + return null; + } + + public String getTitle() { + return title; + } + + public String getTitleTip() { + return titleTip; + } + + public String getIconName() { + return iconName; + } + + public ImageIcon getIcon() { + if (iconName != null && icon == null) { + icon = (ImageIcon) UIHelper.getUIManagerActionIcon(iconName); + } + return icon; + } + + @Override + public String getLabel() { + return label; + } + + @Override + public String getDescription() { + return description; + } + + @Override + public String getOperationDescription() { + return operationDescription; + } + + @Override + public String getOperationLabel() { + return operationLabel; + } + + @Override + public boolean isOperation() { + return operationLabel != null; + } + + @Override + public boolean isConfig() { + return config; + } + + public boolean isNeedSelect() { + return needSelect; + } + + @Override + public Class<? extends AdminActionModel> getModelClass() { + return modelClass; + } + + @Override + public Class<? extends AdminTabUI> getUiClass() { + return uiClass; + } + + @Override + public AdminActionModel newModel() { + if (!isOperation()) { + throw new IllegalStateException("The current step [" + this + "] is not an operation."); + } + try { + return getModelClass().newInstance(); + } catch (Exception e) { + throw new IllegalStateException("Could not init model : " + getModelClass(), e); + } + } + + @Override + public AdminTabUI newUI(WizardExtUI<?, ?> ui) { + try { + Constructor<?> constructor = uiClass.getConstructor(AdminUI.class); + Object tabPanelUI = constructor.newInstance(ui); + return (AdminTabUI) tabPanelUI; + } catch (Exception e) { + throw new IllegalStateException("Could not init ui " + this, e); + } + } + + public boolean isNeedReferentiel() { + return needReferentiel; + } + + public boolean isNeedSave() { + return needSave; + } + + public DbMode[] getIncomingModes() { + return incomingModes; + } + + public boolean hasIncomingModes() { + return incomingModes.length > 0; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminTabUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminTabUI.jaxx new file mode 100644 index 0000000..12ef308 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminTabUI.jaxx @@ -0,0 +1,208 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<!-- **************************** --> +<!-- La base des contenu d'onglet --> +<!-- **************************** --> + +<JPanel id="mainPanel" abstract='true' + implements='jaxx.runtime.swing.wizard.WizardStepUI<AdminStep, AdminUIModel>, java.beans.PropertyChangeListener'> + + <import> + fr.ird.observe.application.swing.ObserveSwingApplicationContext + fr.ird.observe.application.swing.ui.UIHelper + fr.ird.observe.application.swing.ui.admin.* + fr.ird.observe.application.swing.ui.storage.StorageUIModel + + jaxx.runtime.swing.wizard.ext.WizardState + jaxx.runtime.swing.CardLayout2 + + java.awt.Color + java.awt.Dimension + java.beans.PropertyChangeEvent + javax.swing.border.LineBorder + </import> + + <AdminUIModel id='model' initializer='getContextValue(AdminUIModel.class)'/> + + <AdminActionModel id='stepModel' initializer='model.getStepModel(getStep())'/> + + <StorageUIModel id='localSourceModel' initializer='getModel().getLocalSourceModel()'/> + + <StorageUIModel id='centralSourceModel' initializer='getModel().getCentralSourceModel()'/> + + <AdminTabUIHandler id='handler' initializer='null'/> + + <AdminStep id='step' initializer='null'/> + + <script><![CDATA[ + +public abstract void initUI(AdminUI ui); + +protected AdminTabUI(AdminStep step, AdminUI parentContext) { + this.step = step; + UIHelper.checkJAXXContextEntry(parentContext, UIHelper.newContextEntryDef(AdminUIModel.class)); + UIHelper.initContext(this, parentContext); + $initialize(); + // pour etre sur que step est positionne (la methode d'init supprime la reference... + this.step = step; +} + +public void destroy() { + description.setText(""); + localSourceModel = null; + centralSourceModel = null; + UIHelper.destroy(this); +} + +@Override +protected void finalize() throws Throwable { + super.finalize(); + destroy(); +} + +@Override +public void propertyChange(PropertyChangeEvent evt) { + //propertyChange.super(evt); +} + +public void addMessage(AdminStep step, String text) { + getHandler().addMessage(step, text); +} + +public void updateState(WizardState newState) { + getHandler().updateState(this, newState); +} + +]]> + </script> + + <CardLayout2 id='contentLayout'/> + + <!-- titre --> + <JPanel layout='{new BorderLayout()}' constraints='BorderLayout.NORTH'> + <JProgressBar id='progress' constraints='BorderLayout.CENTER'/> + </JPanel> + + <!-- content --> + <JPanel id='content' decorator='boxed' constraints='BorderLayout.CENTER'> + + <JPanel id='PENDING_content' + constraints='WizardState.PENDING.name()'/> + + + <Table id="NEED_FIX_panel" fill='both' + constraints='WizardState.NEED_FIX.name()'> + <row> + <cell fill='both'> + <JPanel id="NEED_FIX_labelPanel"> + <JLabel id='NEED_FIX_label'/> + </JPanel> + + </cell> + </row> + <row> + <cell fill='both' weighty='1' weightx='1'> + <JPanel id='NEED_FIX_content'/> + </cell> + </row> + + </Table> + + <Table id="FAILED_panel" fill='both' + constraints='WizardState.FAILED.name()'> + <row> + <cell fill='both'> + <JLabel id='FAILED_label'/> + </cell> + </row> + <row> + <cell fill='both' weighty='1' weightx='1'> + <JScrollPane id='FAILED_progressionPane'/> + </cell> + </row> + + </Table> + + <Table id="RUNNING_panel" fill='both' + constraints='WizardState.RUNNING.name()'> + <row> + <cell fill='both' weighty='0.3'> + <JPanel id="RUNNING_top"> + <JLabel id='RUNNING_label' constraints='BorderLayout.CENTER'/> + </JPanel> + </cell> + </row> + <row> + <cell fill='both' weighty='0.7' weightx='1'> + <JScrollPane id='RUNNING_progressionPane'/> + </cell> + </row> + </Table> + + <Table id="SUCCESSED_panel" fill='both' + constraints='WizardState.SUCCESSED.name()'> + <row> + <cell fill='both' weighty='0.3'> + <JLabel id='SUCCESSED_label'/> + </cell> + </row> + <row> + <cell fill='both' weighty='0.7' weightx='1'> + <JScrollPane id='SUCCESSED_progressionPane'/> + </cell> + </row> + </Table> + + <Table fill='both' constraints='WizardState.CANCELED.name()'> + <row> + <cell fill='both' weighty='0.3'> + <JLabel id='CANCELED_label'/> + </cell> + </row> + <row> + <cell fill='both' weighty='0.7' weightx='1'> + <JScrollPane id='CANCELED_progressionPane'/> + </cell> + </row> + </Table> + + <JTextArea id='progression' constraints='"PROGRESSION"'/> + <JToolBar id='progressionTop' constraints='"PROGRESSION_TOP"'> + <JLabel id='progressionTopLabel'/> + <javax.swing.Box.Filler + constructorParams='UIHelper.newMinDimension(), UIHelper.newMinDimension(), UIHelper.newMaxXDimension()'/> + <JButton id="progressionTopCopyCliptBoard" + onActionPerformed='UIHelper.copyToClipBoard(progression.getText())'/> + </JToolBar> + </JPanel> + + <!-- description --> + <JScrollPane id="descriptionPane" constraints='BorderLayout.SOUTH'> + <JTextArea id='description'/> + </JScrollPane> + + <JPanel id='invisiblePanel' visible="false" constraints='BorderLayout.EAST'> + + </JPanel> + +</JPanel> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminTabUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminTabUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminTabUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminTabUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminTabUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminTabUIHandler.java new file mode 100644 index 0000000..7660132 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminTabUIHandler.java @@ -0,0 +1,242 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin; + +import fr.ird.observe.application.swing.ObserveRunner; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.service.BabModelVersionException; +import fr.ird.observe.services.service.DatabaseConnexionNotAuthorizedException; +import fr.ird.observe.services.service.DatabaseNotFoundException; +import fr.ird.observe.application.swing.ui.admin.config.SelectDataUI; +import fr.ird.observe.application.swing.ui.admin.resume.ShowResumeUI; +import fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel; +import fr.ird.observe.application.swing.ui.tree.DataSelectionTreeSelectionModel; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import jaxx.runtime.swing.wizard.ext.WizardState; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JTree; +import javax.swing.tree.TreeModel; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.util.concurrent.Callable; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Le controleur des onglets. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class AdminTabUIHandler { + + /** Logger */ + private static final Log log = LogFactory.getLog(AdminTabUIHandler.class); + + protected final AdminTabUI ui; + + protected final AdminUIModel model; + + protected AdminUI parentUI; + + /** Service de decoration. */ + private DecoratorService decoratorService; + + public AdminTabUIHandler(AdminTabUI ui) { + this.ui = ui; + model = ui.getModel(); + } + + public AdminTabUI getUi() { + return ui; + } + + public AdminUIModel getModel() { + return model; + } + + public final DecoratorService getDecoratorService() { + if (decoratorService == null) { + decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); + } + return decoratorService; + } + + public final WizardState onCancel(Exception e) { + if (log.isDebugEnabled()) { + log.debug(this, e); + } + sendMessage(t("observe.actions.operation.message.canceled")); + return WizardState.CANCELED; + } + + public final WizardState onError(Exception e) { + model.getStepModel(model.getOperation()).setError(e); + if (log.isErrorEnabled()) { + log.error(e.getMessage(), e); + } + sendMessage(t("observe.actions.operation.message.failed")); + return WizardState.FAILED; + } + + public void initTabUI(AdminUI ui, AdminTabUI tabUI) { + + parentUI = ui; + AdminStep step = tabUI.getStep(); + + tabUI.addPropertyChangeListener(tabUI); + + if (log.isDebugEnabled()) { + log.debug("common for [" + step + "] for main ui " + ui.getClass().getName() + "@" + System.identityHashCode(ui)); + } + + String stepLabel = t(step.getLabel()); + tabUI.getRUNNING_label().setText(t("observe.actions.operation.message.running", stepLabel)); + tabUI.SUCCESSED_label.setText(t("observe.actions.operation.message.successed", stepLabel)); + tabUI.NEED_FIX_label.setText(t("observe.actions.operation.message.needFix", stepLabel)); + tabUI.CANCELED_label.setText(t("observe.actions.operation.message.canceled", stepLabel)); + tabUI.FAILED_label.setText(t("observe.actions.operation.message.failed", stepLabel)); + tabUI.progression.setVisible(true); + tabUI.progressionTop.setVisible(true); + } + + public void updateState(AdminTabUI ui, WizardState newState) { + if (newState == null) { + newState = WizardState.PENDING; + } + ui.getContentLayout().show(ui.content, newState.name()); + switch (newState) { + case PENDING: + ui.description.setText(t(ui.getStep().getDescription())); + return; + case RUNNING: + ui.RUNNING_progressionPane.getViewport().setView(ui.progression); + ui.RUNNING_progressionPane.setColumnHeaderView(ui.progressionTop); + break; + case SUCCESSED: + ui.SUCCESSED_progressionPane.getViewport().setView(ui.progression); + ui.SUCCESSED_progressionPane.setColumnHeaderView(ui.progressionTop); + break; + case FAILED: + Exception e = ui.getStepModel().getError(); + StringWriter w = new StringWriter(); + e.printStackTrace(new PrintWriter(w)); + ui.addMessage(ui.getStep(), w.toString()); + ui.FAILED_progressionPane.getViewport().setView(ui.progression); + ui.FAILED_progressionPane.setColumnHeaderView(ui.progressionTop); + break; + case NEED_FIX: + break; + case CANCELED: + ui.CANCELED_progressionPane.getViewport().setView(ui.progression); + ui.CANCELED_progressionPane.setColumnHeaderView(ui.progressionTop); + break; + } + } + + public void sendMessage(String message) { + + AdminStep step = ui.getStep(); + ui.addMessage(step, message); + ShowResumeUI resumeUI = (ShowResumeUI) parentUI.getStepUI(AdminStep.SHOW_RESUME); + if (resumeUI != null) { + resumeUI.addMessage(step, message); + } + } + + public String getProgressString(int currentStep, int nbStep) { + String txt = ""; + AdminStep step = ui.getStep(); + if (step != null) { + txt = n("observe.storage.step.label"); + txt = t(txt, currentStep + 1, nbStep, t(step.getLabel())); + } + return txt; + } + + public void updateSelectionModel(SelectDataUI tabUI) { + + JTree selectTree = tabUI.getSelectTree(); + DataSelectionModel selectDataModel = tabUI.getSelectDataModel(); + DataSelectionTreeSelectionModel selectionModel = tabUI.getSelectionModel(); + ObserveTreeHelper helper = tabUI.getTreeHelper(); + ObserveSwingDataSource source = tabUI.getModel().getSafeLocalSource(true); + + updateSelectionModel(tabUI, helper, selectTree, source, selectDataModel, selectionModel); + + } + + protected void checkStepIsOperation(AdminTabUI ui) { + if (!ui.getStep().isOperation()) { + throw new IllegalStateException("can not launch objectOperation on none operation step " + ui.getStep()); + } + } + + protected void openSource(ObserveSwingDataSource service) throws DatabaseConnexionNotAuthorizedException, DatabaseNotFoundException, BabModelVersionException { + if (!service.isOpen()) { + service.open(); + } + } + + public void addAdminWorker(String label, Callable<WizardState> callable) { + AdminActionWorker worker = AdminActionWorker.newWorker(this, label, callable); + ObserveRunner.getActionExecutor().addAction(worker); + } + + protected void updateSelectionModel(AdminTabUI tabUI, + ObserveTreeHelper helper, + JTree selectTree, + ObserveSwingDataSource source, + DataSelectionModel selectDataModel, + DataSelectionTreeSelectionModel selectionModel) { + + + if (log.isDebugEnabled()) { + log.debug("reload model " + selectDataModel); + } + + selectionModel.clearSelection(); + + if (log.isDebugEnabled()) { + log.debug("Will treeHelper : " + helper); + log.debug("selection model : " + selectDataModel); + log.debug("use referentiel : " + selectDataModel.isUseReferentiel()); + log.debug("use data : " + selectDataModel.isUseData()); + } + + helper.setUI(selectTree, false); + + TreeModel model = helper.createModel(tabUI, selectDataModel, source); + selectTree.setModel(model); + + selectionModel.initUI(selectTree); + } + + public void addMessage(AdminStep step, String text) { + ui.getProgression().append(text + "\n"); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminUI.jaxx new file mode 100644 index 0000000..edfb5d7 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminUI.jaxx @@ -0,0 +1,203 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<JPanel id='synchroPanel' implements='jaxx.runtime.swing.wizard.ext.WizardExtUI<AdminStep, AdminUIModel>'> + + <import> + fr.ird.observe.application.swing.ui.UIHelper + + jaxx.runtime.JAXXContext + jaxx.runtime.swing.BlockingLayerUI + jaxx.runtime.swing.wizard.ext.WizardExtUI + jaxx.runtime.swing.wizard.ext.WizardExtUtil + jaxx.runtime.swing.wizard.ext.WizardState + + javax.swing.ImageIcon + javax.swing.UIManager + </import> + + <!-- le modèle du wizard --> + <AdminUIModel id='model' initializer='getContextValue(AdminUIModel.class)'/> + + <!-- le controleur d'ui --> + <AdminUIHandler id='handler' + initializer='getContextValue(AdminUIHandler.class)'/> + + <!-- le bloqueur d'ui utilisé par l'assistant --> + <BlockingLayerUI id='tabBusyBlockLayerUI'/> + + <!-- le bloqueur d'ui lorsqu'une action est en cours ou annulée --> + <BlockingLayerUI id='busyBlockLayerUI'/> + + <!-- le bloqueur de changement d'opérations --> + <BlockingLayerUI id='operationBlockLayerUI'/> + + <!-- le bloqueur de changement de configuration --> + <BlockingLayerUI id='configBlockLayerUI'/> + + <script><![CDATA[ + +private boolean contextInitialized; + +public AdminUI(JAXXContext parentContext, String title, String tip, ImageIcon icon) { + putClientProperty("title", title); + putClientProperty("tip", tip); + putClientProperty("imageIcon", icon); + + // verification du context parent + UIHelper.checkJAXXContextEntry(parentContext, UIHelper.newContextEntryDef(AdminUIModel.class)); + UIHelper.checkJAXXContextEntry(parentContext, UIHelper.newContextEntryDef(AdminUIHandler.class)); + UIHelper.initContext(this, parentContext); + + contextInitialized = true; +} + +public void destroy() { + getHandler().destroy(this); +} + +@Override +protected void finalize() throws Throwable { + super.finalize(); + destroy(); +} + +@Override +public void start() { + getHandler().start(this); +} + +public void cancel() { + getHandler().cancel(this); +} + +public void dispose() { + getHandler().dispose(this); +} + +@Override +public AdminStep getSelectedStep() { + return getHandler().getSelectedStep(this); +} + +@Override +public AdminTabUI getStepUI(AdminStep step) { + return getHandler().getStepUI(this, step); +} + +@Override +public AdminTabUI getStepUI(int stepIndex) { + return getHandler().getStepUI(this, stepIndex); +} + +@Override +public AdminTabUI getSelectedStepUI() { + return getHandler().getSelectedStepUI(this); +} + +public void blockOperations() { + getHandler().blockOperations(this); +} + +@Override +public void onWasInit() { + getHandler().onWasInit(this); +} + +@Override +public void onWasStarted() { + getHandler().onWasStarted(this); +} + +@Override +public void onModelStateChanged(WizardState newState) { + getHandler().onModelStateChanged(this, newState); +} + +@Override +public void onOperationStateChanged(AdminStep step, WizardState newState) { + getHandler().onOperationStateChanged(this, step, newState); +} + +@Override +public void onStepChanged(AdminStep oldStep, AdminStep newStep) { + getHandler().onStepChanged(this, oldStep, newStep); +} + +@Override +public void onStepsChanged(AdminStep[] steps) { + getHandler().onStepsChanged(this, steps); +} + +void $afterCompleteSetup() { + if (!allComponentsCreated || !contextInitialized) { + // pour partir quand l'ui n'est pas complementement initialise + // par example dans l'init de la classe parent + return; + } + + // installation du dispatcher de modifications du modele + WizardExtUtil.installWizardUIListeners(this); + WizardExtUtil.addTraceLogListener(log, getModel()); +} +]]> + </script> + + <!-- les onglets --> + <JTabbedPane id='tabs' decorator='boxed' + constraints='BorderLayout.CENTER' + onStateChanged='if (!model.isValueAdjusting()) { model.gotoStep(getSelectedStep()); }'/> + + <!-- les actions --> + <Table id='actions' constraints='BorderLayout.SOUTH'> + <row> + <cell weightx='0.5' fill="both"> + + <!-- pour annuler --> + <JButton id='cancelAction' onActionPerformed='getModel().cancel()'/> + </cell> + <cell weightx='0.5' fill="both"> + + <!-- quitter apres une annulation ou une erreur --> + <JButton id='closeOnCanceledOrFailedAction' + onActionPerformed='getHandler().cancel(this)'/> + </cell> + <cell weightx='0.5' fill="both"> + + <!-- pour aller sur l'onglet précédent --> + <JButton id="previousAction" + onActionPerformed='model.gotoPreviousStep()'/> + </cell> + <cell weightx='0.5' fill="both"> + + <!-- pour aller sur l'onglet suivant --> + <JButton id="nextAction" onActionPerformed='model.gotoNextStep()'/> + </cell> + <cell weightx='0.5' fill="both"> + + <!-- quitter quand les opérations sont exécutées correctement --> + <JButton id="closeAction" onActionPerformed='getHandler().close(this)'/> + </cell> + </row> + </Table> + +</JPanel> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminUIHandler.java new file mode 100644 index 0000000..e25c21d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminUIHandler.java @@ -0,0 +1,381 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin; + +import fr.ird.observe.application.swing.ObserveActionExecutor; +import fr.ird.observe.application.swing.ObserveRunner; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.admin.config.ConfigUI; +import fr.ird.observe.application.swing.ui.admin.resume.ShowResumeUI; +import fr.ird.observe.application.swing.ui.admin.save.SaveLocalUI; +import jaxx.runtime.swing.wizard.WizardUILancher; +import jaxx.runtime.swing.wizard.ext.WizardExtUtil; +import jaxx.runtime.swing.wizard.ext.WizardState; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.Icon; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.border.TitledBorder; +import java.awt.Component; +import java.util.Arrays; +import java.util.Date; + +import static org.nuiton.i18n.I18n.t; + +/** + * Le controleur de l'ui des actions d'administration. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class AdminUIHandler { + + /** Logger */ + private static final Log log = LogFactory.getLog(AdminUIHandler.class); + + public AdminStep getSelectedStep(AdminUI ui) { + int index = ui.getTabs().getSelectedIndex(); + AdminTabUI c = null; + if (index > -1) { + c = (AdminTabUI) ui.getTabs().getComponentAt(index); + } + AdminStep result = c == null ? null : c.getStep(); + return result; + } + + public AdminTabUI getStepUI(AdminUI ui, AdminStep step) { + if (step != null) { + return (AdminTabUI) ui.getObjectById(step.name()); + } + return null; + } + + public AdminTabUI getStepUI(AdminUI ui, int stepIndex) { + if (stepIndex > ui.getTabs().getTabCount()) { + return null; + } + return (AdminTabUI) ui.getTabs().getComponentAt(stepIndex); + } + + public AdminTabUI getSelectedStepUI(AdminUI ui) { + AdminStep step = getSelectedStep(ui); + AdminTabUI tabUI = getStepUI(ui, step); + return tabUI; + } + + public void blockOperations(AdminUI ui) { + + ui.getModel().setValueAdjusting(true); + for (AdminStep op : AdminStep.values()) { + ConfigUI configUI = (ConfigUI) + ui.getStepUI(AdminStep.CONFIG); + JCheckBox comp = (JCheckBox) configUI.getObjectById(op.name()); + if (comp == null) { + continue; + } + if (!ui.getModel().getOperations().contains(op)) { + comp.setVisible(false); + } + } + ui.operationBlockLayerUI.setBlock(true); + ui.getModel().setValueAdjusting(false); + } + + public void onWasInit(AdminUI ui) { + if (log.isDebugEnabled()) { + log.debug(ui.getName() + " model was init at " + new Date()); + } + } + + public void onWasStarted(AdminUI ui) { + if (log.isDebugEnabled()) { + log.debug(ui.getName() + " model was started at " + new Date()); + } + } + + public void onStepsChanged(AdminUI ui, AdminStep[] steps) { + + if (log.isDebugEnabled()) { + log.debug("Will use these steps : " + Arrays.toString(steps)); + } + + ui.getModel().setValueAdjusting(true); + + + // on supprime tous les onglets + while (ui.tabs.getTabCount() > 1) { + + int index = ui.tabs.getTabCount() - 1; + if (log.isDebugEnabled()) { + log.debug("remove step : " + index); + } + + ui.tabs.remove(index); + } + + // on recree les onglets + for (int i = 0, max = steps.length; i < max; i++) { + AdminStep step = steps[i]; + AdminTabUI c = ui.getStepUI(step); + if (log.isDebugEnabled()) { + log.debug("StepUI [" + step + "] : " + c); + } + if (c == null) { + + if (log.isDebugEnabled()) { + log.debug("Will init step [" + step + "]"); + } + + c = step.newUI(ui); + + if (log.isDebugEnabled()) { + log.debug("Created tabUI [" + c.getName() + "]"); + } + + ui.get$objectMap().put(step.name(), c); + + if (log.isDebugEnabled()) { + log.debug("Will init tabUI [" + c.getName() + "]"); + } + c.initUI(ui); + + JComponent content = c.getContent(); + UIHelper.setLayerUI(content, ui.getBusyBlockLayerUI()); + } + + String title = t(step.getLabel()); + String tip = t(step.getDescription()); + ui.tabs.addTab(title, null, c, tip); + c.setEnabled(i == 0); + } + + ui.getModel().setValueAdjusting(false); + } + + public void onStepChanged(AdminUI ui, AdminStep oldStep, AdminStep newStep) { + if (log.isTraceEnabled()) { + log.trace(newStep); + } + AdminTabUI c = ui.getStepUI(newStep); + + AdminUIModel model = ui.getModel(); + + if (oldStep == null + && newStep == AdminStep.CONFIG + && (model.containsOperation(AdminStep.REFERENTIAL_SYNCHRONIZE) || model.containsOperation(AdminStep.DATA_SYNCHRONIZE))) { + + ConfigUI configUI = (ConfigUI) ui.getStepUI(AdminStep.CONFIG); + + model.setLocalSourceLabel(t("observe.storage.config.left.storage")); + model.setCentralSourceLabel(t("observe.storage.config.right.storage")); + + configUI.getLocalSourceConfig().setBorder(new TitledBorder(model.getLocalSourceLabel())); + configUI.getCentralSourceConfig().setBorder(new TitledBorder(model.getCentralSourceLabel())); + + } + + if (c != null && c.getStep() == AdminStep.SAVE_LOCAL) { + + // on met a jour le descriptif + SaveLocalUI saveUI = (SaveLocalUI) ui.getStepUI(AdminStep.SAVE_LOCAL); + saveUI.getHandler().updateText(); + } + if (c != null && c.getStep() == AdminStep.SHOW_RESUME) { + + // on met a jour le resumé des opérations + ShowResumeUI showResumeUI = (ShowResumeUI) ui.getStepUI(AdminStep.SHOW_RESUME); + showResumeUI.getHandler().updateText(); + } + + // selection du nouvel onglet + int index = ui.tabs.indexOfComponent(c); + if (index > -1 && ui.tabs.getSelectedIndex() != index) { + ui.tabs.setSelectedIndex(index); + } + } + + /** + * Call back lorsque l'état du modèle a changé. + * + * Ici, on va rendre accessible (ou pas) les onglets selon l'état du modèle. + * + * @param ui l'ui concernée + * @param newState le nouvel état. + */ + public void onModelStateChanged(AdminUI ui, WizardState newState) { + if (log.isDebugEnabled()) { + log.debug(newState); + } + + AdminTabUI selected = ui.getSelectedStepUI(); + boolean busy = WizardExtUtil.acceptStates(newState, WizardState.RUNNING); + UIHelper.TabbedPaneIterator<Component> itr = UIHelper.newTabbedPaneIterator(ui.getTabs()); + if (busy) { + if (log.isDebugEnabled()) { + log.debug("Busy state, can only access selected step : " + selected); + } + // seul l'onglet courant est accessible + for (; itr.hasNext(); ) { + Component tab = itr.next(); + ui.tabs.setEnabledAt(itr.getIndex() - 1, tab.equals(selected)); + } + return; + } + + if (selected != null && selected.getStep().isConfig()) { + + if (log.isDebugEnabled()) { + log.debug("Selected step is config : " + selected.getStep()); + } + for (; itr.hasNext(); ) { + int index = itr.getIndex(); + Component tab = itr.next(); + AdminTabUI tabUI = (AdminTabUI) tab; + AdminStep synchroStep = tabUI.getStep(); + if (synchroStep.isConfig()) { + if (log.isDebugEnabled()) { + log.debug("Test config panel : " + synchroStep); + } + boolean valid = ui.getModel().validate(synchroStep); + if (valid) { + if (log.isDebugEnabled()) { + log.debug("step " + synchroStep + " is valid"); + } + ui.tabs.setIconAt(index, getTabIcon(WizardState.SUCCESSED)); + } else { + if (log.isDebugEnabled()) { + log.debug("step " + synchroStep + " is not valid!"); + } + ui.tabs.setIconAt(index, getTabIcon(WizardState.FAILED)); + } + } + } + itr = UIHelper.newTabbedPaneIterator(ui.getTabs()); + } + + if (selected != null && selected.getStep() == AdminStep.SHOW_RESUME) { + + // rien a faire sur le dernier onglet + if (log.isDebugEnabled()) { + log.debug("We are on last step (resume), nothing to do."); + } + return; + } + boolean[] accessibleSteps = ui.getModel().getAccessibleSteps(); + if (log.isDebugEnabled()) { + log.debug("Accessibles step : " + Arrays.toString(accessibleSteps)); + } + for (; itr.hasNext(); itr.next()) { + int index = itr.getIndex(); + ui.tabs.setEnabledAt(index, accessibleSteps[index]); + } + if (!ui.getModel().containsOperation(AdminStep.REPORT)) { + + // le dernier onglet est accessible uniquement si c'est un resume + // actuellement seul l'action de report n'a pas de resume + //TODO chemit 20190 09 29 Il faudrait avoir la propriete needResume pour faire ça de manière générique + ui.tabs.setEnabledAt(accessibleSteps.length - 1, true); + } + } + + public void onOperationStateChanged(AdminUI ui, AdminStep step, WizardState newState) { + if (log.isDebugEnabled()) { + log.debug(step + " - " + newState); + } + + // mettre a jour l'onglet + AdminTabUI selected = ui.getStepUI(step); + int index = ui.tabs.indexOfComponent(selected); + if (index > -1 && !selected.getStep().isConfig()) { + ui.tabs.setIconAt(index, getTabIcon(newState)); + } + if (selected != null && step == selected.getStep()) { + selected.updateState(newState); + } + } + + public void start(AdminUI ui) { + + try { + // on demarre le modele + ui.getModel().start(ui); + + // affichage ui + ui.setVisible(true); + + } finally { + + ui.getModel().setBusy(false); + } + } + + public void close(AdminUI ui) { + + Runnable action = WizardUILancher.APPLY_DEF.getContextValue(ui); + + ObserveActionExecutor executor = ObserveRunner.getActionExecutor(); + + executor.addAction(t("observe.action.admin.close"), action); + } + + public void cancel(AdminUI ui) { + + Runnable action = WizardUILancher.CANCEL_DEF.getContextValue(ui); + + ObserveActionExecutor executor = ObserveRunner.getActionExecutor(); + + executor.addAction(t("observe.action.admin.cancel"), action); + } + + public void destroy(AdminUI ui) { + ui.getModel().destroy(); + if (log.isDebugEnabled()) { + log.debug("destroy ui " + ui.getName()); + } + UIHelper.TabbedPaneIterator<Component> itr = UIHelper.newTabbedPaneIterator(ui.getTabs()); + for (; itr.hasNext(); ) { + AdminTabUI tab = (AdminTabUI) itr.next(); + if (log.isDebugEnabled()) { + log.debug("destroy ui " + tab.getName()); + } + tab.destroy(); + } + UIHelper.destroy(ui); + } + + public void dispose(AdminUI ui) { + destroy(ui); + } + + public Icon getTabIcon(WizardState state) { + Icon i = null; + if (state != null) { + String key = "wizard-state-" + state.name().toLowerCase(); + i = UIHelper.getUIManagerActionIcon(key); + } + return i; + } + + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminUILauncher.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminUILauncher.java new file mode 100644 index 0000000..e48a879 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminUILauncher.java @@ -0,0 +1,275 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.ObserveUIMode; +import fr.ird.observe.application.swing.ui.UIHelper; +import jaxx.runtime.JAXXContext; +import jaxx.runtime.swing.wizard.BusyChangeListener; +import jaxx.runtime.swing.wizard.WizardUILancher; +import jaxx.runtime.swing.wizard.ext.WizardState; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.jdesktop.swingx.JXTitledPanel; + +import javax.swing.ImageIcon; +import javax.swing.JDialog; +import javax.swing.SwingUtilities; +import java.awt.Component; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; + +import static org.nuiton.i18n.I18n.t; + +/** + * Le wizard de base pour les opérations complexes. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class AdminUILauncher extends WizardUILancher<AdminStep, AdminUIModel, AdminUI> { + + /** Logger */ + private static final Log log = LogFactory.getLog(AdminUILauncher.class); + + protected final AdminStep uniqueAction; + + protected Component parent; + + protected AdminUILauncher(JAXXContext context, AdminStep uniqueAction) { + super(context, + AdminUI.class, + AdminUIModel.class, + t(uniqueAction.getTitle()), + t(uniqueAction.getTitleTip()), + uniqueAction.getIcon() + ); + this.uniqueAction = uniqueAction; + } + + public static AdminUILauncher newLauncher(JAXXContext context, AdminStep action) { + + AdminUIHandler handler = context.getContextValue(AdminUIHandler.class); + if (handler == null) { + + handler = new AdminUIHandler(); + context.setContextValue(handler); + + if (log.isDebugEnabled()) { + log.debug("Register in context an admin handler : " + handler); + } + } + return new AdminUILauncher(context, action); + } + + @Override + protected void init(AdminUI ui) { + + parent = getParent(ui); + + AdminUIModel model = ui.getModel(); + + model.addOperation(uniqueAction); + + model.updateUniverse(); + + if (uniqueAction != null) { + // on a juste besoin de faire une action + + ui.blockOperations(); + } + + BusyChangeListener listener = new BusyChangeListener(parent) { + + @Override + protected void setBusy(Component ui) { + if (log.isDebugEnabled()) { + log.debug("Busy for component " + ui); + } + if (parent instanceof ObserveMainUI) { + ((ObserveMainUI) parent).setBusy(true); + super.setBusy(parent); + } + super.setBusy(ui); + } + + @Override + protected void setUnBusy(Component ui) { + if (log.isDebugEnabled()) { + log.debug("UnBusy for component " + ui); + } + if (parent instanceof ObserveMainUI) { + ((ObserveMainUI) parent).setBusy(false); + super.setUnBusy(parent); + } + super.setUnBusy(ui); + } + }; + UIHelper.setLayerUI(ui.getTabs(), ui.getTabBusyBlockLayerUI()); + listener.setBlockingUI(ui.getTabBusyBlockLayerUI()); + model.addPropertyChangeListener(AdminUIModel.BUSY_PROPERTY_NAME, listener); + } + + + protected Component getParent(AdminUI ui) { + ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); + ImageIcon icon = (ImageIcon) ui.getClientProperty("icon"); + if (mainUI == null) { + // pas de fenetre detectee + // on encapsule l'ui dans un dialog + + JDialog dialog = new JDialog(); + dialog.setSize(1024, 780); + + if (icon != null) { + dialog.setIconImage(icon.getImage()); + } + dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); + dialog.setAlwaysOnTop(true); + dialog.setModal(true); + dialog.addWindowListener(new WindowAdapter() { + + @Override + public void windowClosed(WindowEvent e) { + if (log.isInfoEnabled()) { + log.info("closing dialog " + e.getWindow().getName()); + } + if (AdminUILauncher.this.ui.getModel().getModelState() + != WizardState.CANCELED) { + if (log.isInfoEnabled()) { + log.info("cancel panel from dialog !" + + e.getWindow().getName()); + } + AdminUILauncher.this.ui.cancel(); + } + } + }); + return dialog; + } else { + return mainUI; + } + } + + @Override + protected void start(final AdminUI ui) { + super.start(ui); + + ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); + + String title = (String) ui.getClientProperty("title"); + + if (mainUI == null) { + + // pas de fenetre detectee + // on encapsule l'ui dans un dialog + + JDialog dialog = (JDialog) parent; + dialog.setTitle(t(title)); + dialog.setContentPane(ui); +// dialog.pack(); + dialog.setVisible(true); + if (log.isDebugEnabled()) { + log.debug("After dispay dialog"); + } + } else { + + // on attache dans la fenetre principale + String tip = (String) ui.getClientProperty("tip"); + + JXTitledPanel panel = mainUI.getSynchroWizard(); + panel.setTitle(t(title)); + panel.setToolTipText(t(tip)); + panel.setContentContainer(ui); + mainUI.setContextValue(ui.getModel()); + mainUI.setMode(ObserveUIMode.SYNCHRO); + + // refresh selected tab (otherwise it does NOT display (white screen...) + SwingUtilities.invokeLater(() -> ui.getTabs().getSelectedComponent().validate()); + } + } + + @Override + protected void doClose(AdminUI ui, boolean wasCanceled) { + if (log.isInfoEnabled()) { + log.info(this + ", was canceled ? " + wasCanceled); + } + + ObserveMainUI mainUI = null; + + AdminUIModel model = ui.getModel(); + + try { + + + model.doCloseSource(model.getCentralSource(), false); + model.doCloseSource(model.getLocalSource(), false); + + if (!(parent instanceof ObserveMainUI)) { + JDialog dialog = (JDialog) parent; + if (log.isInfoEnabled()) { + log.info("dispose ui!"); + } + ui.dispose(); + dialog.setVisible(false); + dialog.dispose(); + if (log.isInfoEnabled()) { + log.info("After dispose."); + } + ObserveSwingApplicationContext.get().releaseLock(); + return; + } + + mainUI = (ObserveMainUI) parent; + mainUI.getSynchroWizard().remove(ui); + mainUI.removeContextValue(model.getClass()); + + + ObserveSwingDataSource source = model.getPreviousSource(); + + if (source == null) { + + // pas de service auparavant + mainUI.setMode(ObserveUIMode.NO_DB); + return; + } + + model.doCloseSource(source, false); + + // on attache la source a l'ui + ObserveSwingApplicationContext.get().prepareMainStorage(source, false); + + source.open(); + + } catch (Exception e) { + + // on a pas reussit a reouvrir la base precedente + UIHelper.handlingError("Could not close", e); + + if (mainUI != null) { + mainUI.setMode(ObserveUIMode.NO_DB); + } + } + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminUIModel.java new file mode 100644 index 0000000..0dc865d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/AdminUIModel.java @@ -0,0 +1,1493 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin; + +import com.google.common.collect.Lists; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.db.constants.DbMode; +import fr.ird.observe.services.configuration.ObserveDataSourceConfiguration; +import fr.ird.observe.services.configuration.ObserveDataSourceInformation; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.DataReferenceSet; +import fr.ird.observe.services.dto.IdDtos; +import fr.ird.observe.services.dto.actions.report.Report; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.services.service.BabModelVersionException; +import fr.ird.observe.services.service.DatabaseConnexionNotAuthorizedException; +import fr.ird.observe.services.service.DatabaseDestroyNotAuthorizedException; +import fr.ird.observe.services.service.DatabaseNotFoundException; +import fr.ird.observe.services.service.actions.synchro.referential.ReferentialSynchronizeMode; +import fr.ird.observe.services.service.actions.validate.ValidateService; +import fr.ird.observe.services.service.longline.TripLonglineService; +import fr.ird.observe.services.service.seine.TripSeineService; +import fr.ird.observe.application.swing.ui.admin.config.ConfigUI; +import fr.ird.observe.application.swing.ui.admin.consolidate.ConsolidateModel; +import fr.ird.observe.application.swing.ui.admin.export.ExportModel; +import fr.ird.observe.application.swing.ui.admin.report.ReportModel; +import fr.ird.observe.application.swing.ui.admin.save.SaveLocalModel; +import fr.ird.observe.application.swing.ui.admin.synchronize.data.DataSynchroModel; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.legacy.SynchronizeModel; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchroModel; +import fr.ird.observe.application.swing.ui.admin.validate.ValidateModel; +import fr.ird.observe.application.swing.ui.storage.StorageUIHandler; +import fr.ird.observe.application.swing.ui.storage.StorageUIModel; +import fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel; +import fr.ird.observe.application.swing.validation.ValidationModelMode; +import jaxx.runtime.swing.wizard.ext.WizardExtModel; +import jaxx.runtime.swing.wizard.ext.WizardState; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.border.TitledBorder; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.io.File; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.EnumSet; +import java.util.List; +import java.util.Set; + +import static fr.ird.observe.application.swing.ObserveResourceManager.Resource; +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Le modele de l'ui pour effectuer des opérations de synchro et validation. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class AdminUIModel extends WizardExtModel<AdminStep> { + + public static final String SELECTION_MODEL_CHANGED_PROPERTY_NAME = "selectionModelChanged"; + + public static final String SELECTED_TRIP_PROPERTY_NAME = "selectedTrip"; + + /** Logger */ + private static final Log log = LogFactory.getLog(AdminUIModel.class); + + public static final PropertyChangeListener LOG_PROPERTY_CHANGE_LISTENER = new LogPropertyChanged(); + + public static final String PROPERTY_LOCAL_SOURCE_LABEL = "localSourceLabel"; + public static final String PROPERTY_CENTRAL_SOURCE_LABEL = "centralSourceLabel"; + + /** la source de données en cours d'utilisation par l'application */ + protected ObserveSwingDataSource previousSource; + + /** la source de données sur laquel on veut travailler */ + protected ObserveSwingDataSource localSource; + + /** la source de données sur laquel on veut travailler */ + protected ObserveDataSourceInformation localSourceInformation; + + /** la source de données dite central (contenant le référentiel valide) */ + protected ObserveSwingDataSource centralSource; + + /** la configuration de la base source */ + protected final StorageUIModel localSourceModel; + + /** la configuration de la base central */ + protected final StorageUIModel centralSourceModel; + + /** le controleur pour configurer les sources */ + protected StorageUIHandler storageHandler; + + /** selection des donnees a valider */ + protected final DataSelectionModel selectionDataModel; + + /** la liste des modes disponibles en entrée */ + protected final EnumSet<DbMode> availableIncomingModes; + + private final PropertyChangeListener listenStepChanged; + + private final PropertyChangeListener listenSelectModified; + + private final PropertyChangeListener listenValidationModified; + + private final PropertyChangeListener listenReportModified; + + private final PropertyChangeListener listenerSelectedDataForReport; + + private final PropertyChangeListener listenConsolidateModified; + + private final PropertyChangeListener listenSaveLocalChanged; + private final PropertyChangeListener listenReferentialConfigChanged; + + private String localSourceLabel = t("observe.storage.config.source.storage"); + private String centralSourceLabel = t("observe.storage.config.referentiel.storage"); + + public String getLocalSourceLabel() { + return localSourceLabel; + } + + public void setLocalSourceLabel(String localSourceLabel) { + Object oldValue = getLocalSourceLabel(); + this.localSourceLabel = localSourceLabel; + firePropertyChange(PROPERTY_LOCAL_SOURCE_LABEL, oldValue, localSourceLabel); + } + + public String getCentralSourceLabel() { + return centralSourceLabel; + } + + public void setCentralSourceLabel(String centralSourceLabel) { + Object oldValue = getCentralSourceLabel(); + this.centralSourceLabel = centralSourceLabel; + firePropertyChange(PROPERTY_CENTRAL_SOURCE_LABEL, oldValue, centralSourceLabel); + } + + public AdminUIModel() { + super(AdminStep.class); + + localSourceModel = new StorageUIModel() { + + @Override + public String getLabel() { + String txt; + if (containsOperation(AdminStep.REFERENTIAL_SYNCHRONIZE) || containsOperation(AdminStep.DATA_SYNCHRONIZE)) { + txt = n("observe.storage.label.synchro.leftSource"); + } else { + txt = n("observe.storage.label.synchro.incoming"); + } + String params; + + if (getDbMode() == DbMode.USE_SERVER) { + params = t("observe.storage.server.db") + " " + getRemoteUrl(); + } else if (getDbMode() == DbMode.USE_REMOTE) { + params = t("observe.storage.remote.db") + " " + getRemoteUrl(); + } else { + params = t("observe.storage.locale.db") + " " + getH2Config().getDirectory().getAbsolutePath(); + } + txt = t(txt, params); + return txt; + } + + @Override + public void validate() { + super.validate(); + + // on declanche la revalidation du modèle + firePropertyChange(VALID_PROPERTY_NAME, isValid()); + } + + }; + + centralSourceModel = new StorageUIModel() { + + @Override + public String getLabel() { + String txt; + if (containsOperation(AdminStep.REFERENTIAL_SYNCHRONIZE) || containsOperation(AdminStep.DATA_SYNCHRONIZE)) { + txt = n("observe.storage.label.synchro.rightSource"); + } else { + txt = n("observe.storage.label.synchro.referentiel"); + } + String params; + + if (getDbMode() == DbMode.USE_SERVER) { + params = t("observe.storage.server.db") + " " + getRemoteUrl(); + } else if (getDbMode() == DbMode.USE_REMOTE) { + params = t("observe.storage.remote.db") + " " + getRemoteUrl(); + } else { + params = t("observe.storage.locale.db") + " " + getH2Config().getDirectory().getAbsolutePath(); + } + txt = t(txt, params); + return txt; + } + + @Override + public void validate() { + super.validate(); + + // on declanche la revalidation du modèle + firePropertyChange(VALID_PROPERTY_NAME, isValid()); + } + }; + + selectionDataModel = new DataSelectionModel(); + + availableIncomingModes = EnumSet.noneOf(DbMode.class); + + if (log.isDebugEnabled()) { + log.debug("model [" + this + "] is instanciate."); + } + + listenReferentialConfigChanged = evt -> { + + + if (isWasStarted()) { + + // on ne propage plus rien (il n'y a plus de configuration possible...) + if (log.isDebugEnabled()) { + log.debug("Stop propagation, was started... " + evt.getPropertyName()); + } + return; + } + + if (ReferentialSynchroModel.SYNCHRONIZE_MODE_PROPERTY_NAME.equals(evt.getPropertyName())) { + + validate(); + + } + + }; + + listenStepChanged = evt -> { + + if (isWasStarted()) { + + // on ne propage plus rien (il n'y a plus de configuration possible...) + if (log.isDebugEnabled()) { + log.debug("Stop propagation, was started... " + evt.getPropertyName()); + } + return; + } + + AdminStep oldStep = (AdminStep) evt.getOldValue(); + AdminStep newStep = (AdminStep) evt.getNewValue(); + + if (AdminStep.REPORT == newStep) { + + if (oldStep != null && oldStep.ordinal() < newStep.ordinal()) { + + int oldIndex = getStepIndex(oldStep); + int newIndex = getStepIndex(newStep); + + if (oldIndex < newIndex) { + + // on reinitialise le report sélectionné + getReportModel().setSelectedReport(null); + } + } + } + + if (AdminStep.CONFIG == newStep) { + + // on repasse sur l'écran de configuration + + if (containsOperation(AdminStep.REFERENTIAL_SYNCHRONIZE) || containsOperation(AdminStep.DATA_SYNCHRONIZE)) { + + setLocalSourceLabel(t("observe.storage.config.left.storage")); + setCentralSourceLabel(t("observe.storage.config.right.storage")); + + } + + return; + } + + if (oldStep != null && oldStep != AdminStep.CONFIG) { + + // on fait rien si on ne vient pas de la configuration + return; + } + + // on était sur l'écran de configuration + + // mise à jour des modèles de sélection si on arrive sur une étape + // qui le requière + + boolean needSelect = needSelect(); + + if (!needSelect) { + + // pas besoin d'agir sur le model de sélection de données + return; + } + + DataSelectionModel selectModel = getSelectionDataModel(); + + if (containsOperation(AdminStep.EXPORT_DATA)) { + + // on doit aussi calculer les ids des marées distantes + computeExistingTrips(getSafeCentralSource(true)); + + } + + // on remplit le modèle de sélection + if (log.isDebugEnabled()) { + log.debug("Will refill selectionModel [" + newStep + "] : " + selectModel); + } + ObserveSwingDataSource dataSource = getSafeLocalSource(true); + populateSelectionModel(dataSource); + }; + listenSelectModified = evt -> { + DataSelectionModel source = (DataSelectionModel) evt.getSource(); + if (log.isDebugEnabled()) { + log.debug("selection data model [" + source + "] changed on " + + evt.getPropertyName() + ", new value = " + + evt.getNewValue()); + } + validate(); + if (log.isDebugEnabled()) { + log.debug("nb selected export datas = " + + source.getSelectedData().size()); + } + + // on declanche la revalidation du modèle + firePropertyChange(VALID_STEP_PROPERTY_NAME, validStep); + }; + listenValidationModified = evt -> { + ValidateModel source = (ValidateModel) evt.getSource(); + if (log.isDebugEnabled()) { + log.debug("validation model [" + source + "] changed on " + + evt.getPropertyName() + ", new value = " + + evt.getNewValue()); + } + validate(); + if (log.isDebugEnabled()) { + log.debug("nb validators = " + + source.getValidators().size() + ); + } + firePropertyChange(VALID_STEP_PROPERTY_NAME, validStep); + }; + listenReportModified = evt -> { + ReportModel source = (ReportModel) evt.getSource(); + if (log.isDebugEnabled()) { + log.debug("report model [" + source + "] changed on " + + evt.getPropertyName() + ", new value = " + + evt.getNewValue()); + } + validate(); + firePropertyChange(VALID_STEP_PROPERTY_NAME, validStep); + }; + listenerSelectedDataForReport = evt -> { + + // la modification de la sélection entraine la suppression d'un report sélectionné + getReportModel().setSelectedReport(null); + + // cela entraine aussi la modification de la marée sélectionnée + firePropertyChange(SELECTED_TRIP_PROPERTY_NAME, getSelectedTrip()); + + }; + listenConsolidateModified = evt -> { + ConsolidateModel source = (ConsolidateModel) evt.getSource(); + if (log.isDebugEnabled()) { + log.debug("consolidate model [" + source + "] changed on " + + evt.getPropertyName() + ", new value = " + + evt.getNewValue()); + } + validate(); + firePropertyChange(VALID_STEP_PROPERTY_NAME, validStep); + }; + listenSaveLocalChanged = evt -> { + + String propertyName = evt.getPropertyName(); + + if (SaveLocalModel.BACKUP_FILE_PROPERTY_NAME.equals(propertyName)) { + + validate(); + return; + } + + if (SaveLocalModel.LOCAL_SOURCE_NEED_SAVE_PROPERTY_NAME.equals(propertyName)) { + boolean localSourceNeedSave = (Boolean) evt.getNewValue(); + if (localSourceNeedSave) { + // l'opération de sauvegarde est obligatoire + setStepState(AdminStep.SAVE_LOCAL, WizardState.PENDING); + } + validate(); + return; + } + + if (log.isDebugEnabled()) { + log.debug("Skip property " + propertyName); + } + }; + } + + public DataSelectionModel getSelectionDataModel() { + return selectionDataModel; + } + + public boolean needSelect() { + if (WizardState.CANCELED == getModelState()) { + return false; + } + Set<AdminStep> operations = getOperations(); + for (AdminStep operation : operations) { + if (operation.isNeedSelect()) { + return true; + } + } + return false; + } + + public DataReference getSelectedTrip() { + Set<DataReference> data = getSelectionDataModel().getSelectedData(); + if (data.isEmpty()) { + + // pas de Trip selectionne + return null; + } + DataReference dto = data.iterator().next(); + if (IdDtos.isTrip(dto)) { + return dto; + } + + // la donnée n'est pas une marée + return null; + } + + @Override + public AdminActionModel getStepModel(AdminStep operation) { + return (AdminActionModel) super.getStepModel(operation); + } + + /** + * Pour savoir si on a besoin d'une base source pour l'opération. + * + * Actuellement, seul l'opération d'import acces n'a pas besoin d'une telle + * base. + * + * @return {@code true} si au moins une des opérations a besoin d'une source + * d'entrée, {@code false} autrement. + * @since 2.0 + */ + public boolean isNeedIncomingDataSource() { + for (AdminStep op : getOperations()) { + if (op.hasIncomingModes()) { + + // l'operation requiere une base en entree + return true; + } + } + + // aucune operation ne requiere pas de base en entree + return false; + } + + /** + * Pour savoir si on a besoin d'une base de référence pour l'opération. + * + * @return {@code true} si au moins une des opérations a besoin d'une source + * de référence, {@code false} autrement. + * @since 2.0 + */ + public boolean isNeedReferentielDataSource() { + for (AdminStep op : getOperations()) { + if (op.isNeedReferentiel()) { + + // l'operation requiere une base de référence + return true; + } + } + + // aucune operation ne requiere pas de base de référence + return false; + } + + /** + * Construit l'ensemble des modes disponibles pour la base en entrée. + * + * @return l'ensemble des modes disponibles. + */ + public EnumSet<DbMode> getIncomingDataSourceMode() { + + EnumSet<DbMode> result = EnumSet.noneOf(DbMode.class); + getOperations().stream().filter(AdminStep::hasIncomingModes).forEach(op -> result.addAll(Arrays.asList(op.getIncomingModes()))); + return result; + } + + public void start(AdminUI ui) { + + availableIncomingModes.clear(); + + storageHandler = ui.getContextValue(StorageUIHandler.class); + + ObserveSwingApplicationConfig config = ObserveSwingApplicationContext.get().getConfig(); + + // demarrage du modèle : on fixe ici une fois pour toute les liste + // des onglets visibles + start(); + + // preparation de l'ui (création des onglets visibles) + ui.blockOperations(); + + if (log.isInfoEnabled()) { + log.info("enables steps = " + steps); + log.info("enables operations = " + operations); + } + + // on positionne la source courante de l'application comme service + // entrant (on se sert de la configuration de ce service s'il existe + // pour la source locale). + ObserveSwingDataSource previousSource = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); + setPreviousSource(previousSource); + + startIncomingSourceModel(ui); + + startCentralSourceModel(ui); + + startSelectModel(); + + // avant le demarrage du wizard, on ferme toujours la source + // en cours d'utilisation + + if (previousSource != null && previousSource.isOpen()) { + + if (log.isDebugEnabled()) { + log.debug("Close previous source " + + previousSource.getLabel()); + } + doCloseSource(previousSource, false); + } + + if (containsOperation(AdminStep.SAVE_LOCAL)) { + + File backupfile = new File(config.getBackupDirectory(), storageHandler.getDefaultBackupFilename()); + + getSaveLocalModel().setBackupFile(backupfile); + getSaveLocalModel().setDoBackup(true); + getSaveLocalModel().removePropertyChangeListener(listenSaveLocalChanged); + getSaveLocalModel().addPropertyChangeListener(listenSaveLocalChanged); + } + + if (containsOperation(AdminStep.VALIDATE)) { + + getValidateModel().removePropertyChangeListener(listenValidationModified); + getValidateModel().addPropertyChangeListener(listenValidationModified); + getValidateModel().addScope(NuitonValidatorScope.ERROR); + getValidateModel().setModelMode(ValidationModelMode.DATA); + getValidateModel().setContextName(ValidateService.SERVICE_VALIDATION_CONTEXT); + getValidateModel().setGenerateReport(true); + if (!config.getValidationReportDirectory().exists()) { + boolean b = config.getValidationReportDirectory().mkdirs(); + if (!b) { + throw new RuntimeException("Could not create directory " + config.getValidationReportDirectory()); + } + } + File reportFile = new File(config.getValidationReportDirectory(), + getValidateModel().getDefaultReportFilename()); + getValidateModel().setReportFile(reportFile); + } + + if (containsOperation(AdminStep.REPORT)) { + + File reportFile = Resource.report.getFile(config.getReportDirectory()); + + if (reportFile.exists()) { + if (log.isInfoEnabled()) { + log.info("Will use report file : " + reportFile); + } + + getReportModel().setReportFile(reportFile); + } else { + if (log.isWarnEnabled()) + log.warn("Default report file " + reportFile + " does not exists."); + } + // on charge la liste des reports disponilbes + List<Report> reports = getReportModel().getReports(); + + // on ecoute la modification du modèle + getReportModel().removePropertyChangeListener(listenReportModified); + getReportModel().addPropertyChangeListener(listenReportModified); + + // on ecoute la modification de la sélection + getSelectionDataModel().removePropertyChangeListener(DataSelectionModel.PROPERTY_SELECTED_DATA, listenerSelectedDataForReport); + getSelectionDataModel().addPropertyChangeListener(DataSelectionModel.PROPERTY_SELECTED_DATA, listenerSelectedDataForReport); + + if (log.isInfoEnabled()) { + log.info("Detects " + reports.size() + " report(s)."); + } + } + + if (containsOperation(AdminStep.CONSOLIDATE)) { + + // Anything to init ? + getConsolidateModel().removePropertyChangeListener(listenConsolidateModified); + getConsolidateModel().addPropertyChangeListener(listenConsolidateModified); + } + + if (containsOperation(AdminStep.DATA_SYNCHRONIZE)) { + + ConfigUI configUI = (ConfigUI) ui.getStepUI(AdminStep.CONFIG); + + configUI.getLocalSourceConfig().setBorder(new TitledBorder(getLocalSourceLabel())); + configUI.getCentralSourceConfig().setBorder(new TitledBorder(getCentralSourceLabel())); + + } + if (containsOperation(AdminStep.REFERENTIAL_SYNCHRONIZE)) { + + getReferentialSynchroModel().removePropertyChangeListener(listenReferentialConfigChanged); + getReferentialSynchroModel().addPropertyChangeListener(listenReferentialConfigChanged); + + getReferentialSynchroModel().addPropertyChangeListener(ReferentialSynchroModel.SYNCHRONIZE_MODE_PROPERTY_NAME, evt -> { + + ReferentialSynchronizeMode newValue = (ReferentialSynchronizeMode) evt.getNewValue(); + + if (ui.getTabs().getComponentCount() > 1 && newValue != null) { + ui.getTabs().setTitleAt(1, t("observe.actions.synchro.referential.withMode", newValue.getLabel())); + } + + }); + + getReferentialSynchroModel().setSynchronizeMode(ReferentialSynchronizeMode.FROM_LEFT_TO_RIGHT); + + } + + // on ecoute les modifications d'étapes pour remplir les modèles de sélection + // si nécessaire + + removePropertyChangeListener(STEP_PROPERTY_NAME, listenStepChanged); + addPropertyChangeListener(STEP_PROPERTY_NAME, listenStepChanged); + + if (log.isInfoEnabled()) { + log.info("End of start..."); + } + + // on revalide le modèle (tout est prêt) + validate(); + } + + protected void startCentralSourceModel(AdminUI ui) { + + if (!isNeedReferentielDataSource()) { + + // pas besoin de la base distante + return; + } + + // par default, on tente d'utiliser la base distance + centralSourceModel.init(ui, null); + centralSourceModel.setCanCreateLocalService(false); + boolean canUseLocalSource = getOperations().contains(AdminStep.DATA_SYNCHRONIZE) || getOperations().contains(AdminStep.REFERENTIAL_SYNCHRONIZE); + centralSourceModel.setCanUseLocalService(canUseLocalSource); + centralSourceModel.setCanUseRemoteService(true); + centralSourceModel.setCanUseServerService(true); + centralSourceModel.start(DbMode.USE_REMOTE); + + if (log.isDebugEnabled()) { + centralSourceModel.removePropertyChangeListener(LOG_PROPERTY_CHANGE_LISTENER); + centralSourceModel.addPropertyChangeListener(LOG_PROPERTY_CHANGE_LISTENER); + } + + // on teste si la connexion distante existe + if (centralSourceModel.isValid()) { + centralSourceModel.testRemote(); + } + } + + protected void startIncomingSourceModel(AdminUI ui) { + + if (!isNeedIncomingDataSource()) { + + // pas besoin de la base locale + return; + } + + ObserveSwingDataSource previousSource = getPreviousSource(); + + ObserveDataSourceConfiguration previousSourceConfig = null; + ObserveDataSourceInformation previousSourceInfo = null; + + EnumSet<DbMode> authorizedModes = getIncomingDataSourceMode(); + EnumSet<DbMode> modes = EnumSet.noneOf(DbMode.class); + + if (authorizedModes.contains(DbMode.USE_LOCAL)) { + + // ce mode est disponible uniquement si une base locale existe + if (ObserveSwingApplicationContext.get().getConfig().isLocalStorageExist()) { + modes.add(DbMode.USE_LOCAL); + } + } + + if (authorizedModes.contains(DbMode.USE_REMOTE)) { + + modes.add(DbMode.USE_REMOTE); + } + + if (authorizedModes.contains(DbMode.USE_SERVER)) { + + modes.add(DbMode.USE_SERVER); + } + + if (authorizedModes.contains(DbMode.CREATE_LOCAL)) { + + modes.add(DbMode.CREATE_LOCAL); + } + + if (previousSource != null) { + + try { + previousSourceConfig = previousSource.getConfiguration().clone(); + previousSourceInfo = previousSource.getInformation(); + } catch (CloneNotSupportedException e) { + if (log.isErrorEnabled()) { + log.error("con not clone previous data configuration", e); + } + } + + if (previousSource.isRemote()) { + + if (!modes.contains(DbMode.USE_REMOTE)) { + + // pas autorise a utiliser cette source en entree + previousSource = null; + } + } + + if (previousSource != null && previousSource.isServer()) { + + if (!modes.contains(DbMode.USE_SERVER)) { + + // pas autorise a utiliser cette source en entree + previousSource = null; + } + } + + if (previousSource != null && previousSource.isLocal()) { + + if (!modes.contains(DbMode.USE_LOCAL)) { + + // pas autorise a utiliser cette source en entree + previousSource = null; + } + } + } + + availableIncomingModes.addAll(modes); + + localSourceModel.setCanCreateLocalService(modes.contains(DbMode.CREATE_LOCAL)); + localSourceModel.setCanUseLocalService(modes.contains(DbMode.USE_LOCAL)); + localSourceModel.setCanUseRemoteService(modes.contains(DbMode.USE_REMOTE)); + localSourceModel.setCanUseServerService(modes.contains(DbMode.USE_SERVER)); + + if (previousSource == null) { + + // on intialize le modèle de la source locale à partir du service entrant (s'il existe) + localSourceModel.init(ui, null); + + } else { + + // on intialize le modèle de la source locale à partir du service entrant (s'il existe) + localSourceModel.initFromPreviousConfig(ui, previousSourceConfig, previousSourceInfo); + } + + DbMode dbMode = localSourceModel.getDbMode(); + localSourceModel.start(dbMode); + + if (log.isDebugEnabled()) { + localSourceModel.removePropertyChangeListener(LOG_PROPERTY_CHANGE_LISTENER); + localSourceModel.addPropertyChangeListener(LOG_PROPERTY_CHANGE_LISTENER); + } + } + + protected void startSelectModel() { + + if (!needSelect()) { + + // pas d'opération avec une sélection de données, rien a faire ici + return; + } + + DataSelectionModel selectionModel = getSelectionDataModel(); + + if (containsOperation(AdminStep.EXPORT_DATA)) { + + selectionModel.setUseData(true); + selectionModel.setUseOpenData(false); + selectionModel.setUseReferentiel(false); + } + + if (containsOperation(AdminStep.REPORT)) { + + selectionModel.setUseData(true); + selectionModel.setUseOpenData(true); + selectionModel.setUseReferentiel(false); + } + + if (containsOperation(AdminStep.VALIDATE)) { + + selectionModel.setUseOpenData(true); + } + + if (containsOperation(AdminStep.CONSOLIDATE)) { + + selectionModel.setUseOpenData(true); + selectionModel.setUseData(true); + selectionModel.setUseReferentiel(false); + } + + selectionModel.addPropertyChangeListener(listenSelectModified); + } + + @Override + public void destroy() { + localSourceModel.destroy(); + centralSourceModel.destroy(); + selectionDataModel.destroy(); + super.destroy(); + } + + public ObserveSwingDataSource getPreviousSource() { + return previousSource; + } + + public void setPreviousSource(ObserveSwingDataSource previousSource) { + this.previousSource = previousSource; + } + + public ObserveSwingDataSource getLocalSource() { + return localSource; + } + + public ObserveDataSourceInformation getLocalSourceInformation() { + if (localSourceInformation == null) { + + ObserveSwingDataSource localSource = getSafeLocalSource(false); + + try { + + localSourceInformation = localSource.checkCanConnect(); + + } catch (Exception e) { + //FIXME ! il faut faire quelque chose dans ce cas précis, au moins avertir l'utilisateur + if (log.isErrorEnabled()) { + log.error("unable to find local source information", e); + } + } + + } + + return localSourceInformation; + } + + public ObserveSwingDataSource getCentralSource() { + return centralSource; + } + + public ObserveSwingDataSource getSafeLocalSource(boolean open) { + if (localSource == null || open && !localSource.isOpen()) { + + localSource = createDataSource(getLocalSourceModel()); + } + if (open) { + + doOpenSource(localSource); + } + return localSource; + } + + public ObserveSwingDataSource getSafeCentralSource(boolean open) { + if (centralSource == null || open && !centralSource.isOpen()) { + + centralSource = createDataSource(getCentralSourceModel()); + } + if (open) { + doOpenSource(centralSource); + } + return centralSource; + } + + public StorageUIModel getLocalSourceModel() { + return localSourceModel; + } + + public StorageUIModel getCentralSourceModel() { + return centralSourceModel; + } + + public ValidateModel getValidateModel() { + return (ValidateModel) getStepModel(AdminStep.VALIDATE); + } + + public SynchronizeModel getSynchronizeReferentielModel() { + return (SynchronizeModel) getStepModel(AdminStep.SYNCHRONIZE); + } + + public ExportModel getExportModel() { + return (ExportModel) getStepModel(AdminStep.EXPORT_DATA); + } + + public ReportModel getReportModel() { + return (ReportModel) getStepModel(AdminStep.REPORT); + } + + public ConsolidateModel getConsolidateModel() { + return (ConsolidateModel) getStepModel(AdminStep.CONSOLIDATE); + } + + public SaveLocalModel getSaveLocalModel() { + return (SaveLocalModel) getStepModel(AdminStep.SAVE_LOCAL); + } + + public DataSynchroModel getDataSynchroModel() { + return (DataSynchroModel) getStepModel(AdminStep.DATA_SYNCHRONIZE); + } + + public ReferentialSynchroModel getReferentialSynchroModel() { + return (ReferentialSynchroModel) getStepModel(AdminStep.REFERENTIAL_SYNCHRONIZE); + } + + @Override + public void cancel() { + super.cancel(); + // on affiche l'onglet de resume si requis + AdminStep newStep = getSteps().get(getSteps().size() - 1); + if (log.isDebugEnabled()) { + log.debug("Operation canceled, will go to final step " + newStep); + } + gotoStep(newStep); + } + + @Override + public AdminUIModel addOperation(AdminStep step) { + if (AdminStep.EXPORT_DATA == step) { + + // pour exporter les données utilisateurs + // l'opération de synchronisation de référentiel est nécessaire + getOperations().add(AdminStep.SYNCHRONIZE); + + // l'opération de calcul des données est aussi obligatoire + getOperations().add(AdminStep.CONSOLIDATE); + } + + if (AdminStep.REPORT == step) { + + // l'opération de calcul des données est obligatoire + getOperations().add(AdminStep.CONSOLIDATE); + } + return (AdminUIModel) super.addOperation(step); + } + + @Override + public void removeOperation(AdminStep step) { + if (AdminStep.SYNCHRONIZE == step) { + + // pour exporter les données utilisateurs + // l'objectOperation de synchronisation de référentiel est nécessaire + getOperations().remove(AdminStep.EXPORT_DATA); + } + + if (AdminStep.CONSOLIDATE == step) { + + // pour exporter les données utilisateurs ou effectuer des reports + // l'objectOperation de calcul des données est nécessaire + getOperations().remove(AdminStep.EXPORT_DATA); + getOperations().remove(AdminStep.REPORT); + } + + super.removeOperation(step); + } + + @Override + public boolean validate(AdminStep step) { + + boolean validate = super.validate(step) && !getOperations().isEmpty(); + if (!validate) { + if (log.isDebugEnabled()) { + log.debug("not valid from generic states..."); + } + return false; + } + + DataSelectionModel selectionModel = getSelectionDataModel(); + + switch (step) { + case CONFIG: + if (isNeedIncomingDataSource()) { + if (!localSourceModel.isValid()) { + if (log.isDebugEnabled()) { + log.debug("incoming service is not valid"); + } + validate = false; + } + } + if (isNeedReferentielDataSource()) { + if (!centralSourceModel.isValid()) { + if (log.isDebugEnabled()) { + log.debug("referentiel service is not valid"); + } + validate = false; + } + } + + if (containsOperation(AdminStep.VALIDATE)) { + + // il faut avoir selectionner un context + // il faut avoir au moins selectionner un scope + if (StringUtils.isEmpty(getValidateModel().getContextName())) { + if (log.isDebugEnabled()) { + log.debug("no validation context name"); + } + return false; + } + if (getValidateModel().getScopes().isEmpty()) { + if (log.isDebugEnabled()) { + log.debug("no validation scopes"); + } + return false; + } + if (getValidateModel().getModelMode() == null) { + if (log.isDebugEnabled()) { + log.debug("no validation model mode"); + } + return false; + } + if (getValidateModel().isGenerateReport()) { + + // le fichier de rapport ne doit pas exister + File file = getValidateModel().getReportFile(); + + if (file.exists()) { + if (log.isDebugEnabled()) { + log.debug("report file already exists"); + } + return false; + } + + // le repertoire du rapport doit exister + File parentFile = file.getParentFile(); + if (parentFile == null || !parentFile.exists()) { + return false; + } + } + if (getValidateModel().getValidators().isEmpty()) { + if (log.isDebugEnabled()) { + log.debug("no validators detected"); + } + return false; + } + + // la base precedente doit etre ouverte + ObserveDataSourceInformation dataSourceInformation = getLocalSourceInformation(); + + // si le test de connection a echoue + if (dataSourceInformation == null) { + if (log.isDebugEnabled()) { + log.debug("can not connect to data source "); + } + return false; + } + + + // pour valider une base il faut les droits + if (selectionModel.isUseData()) { + + // il faut les droits en Lecture sur les donnes + if (!(dataSourceInformation.canReadData() && dataSourceInformation.canWriteData())) { + if (log.isDebugEnabled()) { + log.debug("can not read and write data"); + } + return false; + } + } + if (selectionModel.isUseReferentiel()) { + + // il faut les droits en L/E sur le referentiel + if (!(dataSourceInformation.canReadReferential() && dataSourceInformation.canWriteReferential())) { + if (log.isDebugEnabled()) { + log.debug("can not read and write referentiel"); + } + return false; + } + } + } + if (validate && containsOperation(AdminStep.DATA_SYNCHRONIZE)) { + + // les deux bases (source et referentiel) doivent etre different + DbMode dbMode = localSourceModel.getDbMode(); + if (dbMode == centralSourceModel.getDbMode()) { + switch (dbMode) { + case USE_LOCAL: + validate = false; + break; + case USE_REMOTE: + validate = !localSourceModel.getPgConfig().getJdbcUrl().equals(centralSourceModel.getPgConfig().getJdbcUrl()); + break; + case USE_SERVER: + validate = !localSourceModel.getRestConfig().getServerUrl().equals(centralSourceModel.getRestConfig().getServerUrl()); + break; + } + } + + ObserveDataSourceInformation leftDataSourceInformation = getLocalSourceInformation(); + if (!(leftDataSourceInformation.canReadData() && leftDataSourceInformation.canWriteData())) { + if (log.isDebugEnabled()) { + log.debug("can not read and write data on left data source"); + } + return false; + } + + if (centralSourceModel.getDataSourceInformation() != null) { + + ObserveDataSourceInformation rightDataSourceInformation = centralSourceModel.getDataSourceInformation(); + if (!(rightDataSourceInformation.canReadData() && rightDataSourceInformation.canWriteData())) { + if (log.isDebugEnabled()) { + log.debug("can not read and write data on right data source"); + } + return false; + } + + } + + } + + if (validate && containsOperation(AdminStep.REFERENTIAL_SYNCHRONIZE)) { + + // les deux bases (source et referentiel) doivent etre different + DbMode dbMode = localSourceModel.getDbMode(); + if (dbMode == centralSourceModel.getDbMode()) { + switch (dbMode) { + case USE_LOCAL: + validate = false; + break; + case USE_REMOTE: + validate = !localSourceModel.getPgConfig().getJdbcUrl().equals(centralSourceModel.getPgConfig().getJdbcUrl()); + break; + case USE_SERVER: + validate = !localSourceModel.getRestConfig().getServerUrl().equals(centralSourceModel.getRestConfig().getServerUrl()); + break; + } + } + + ObserveDataSourceInformation leftDataSourceInformation = getLocalSourceInformation(); + if (!(leftDataSourceInformation.canReadReferential())) { + if (log.isDebugEnabled()) { + log.debug("can not read and write referential on left data source"); + } + return false; + } + + if (centralSourceModel.getDataSourceInformation() != null) { + + ObserveDataSourceInformation rightDataSourceInformation = centralSourceModel.getDataSourceInformation(); + if (!(rightDataSourceInformation.canReadReferential())) { + if (log.isDebugEnabled()) { + log.debug("can not read and write referential on right data source"); + } + return false; + } + + } + + if (getReferentialSynchroModel().getSynchronizeMode() == null) { + return false; + } + + } + + if (containsOperation(AdminStep.SYNCHRONIZE)) { + + // les deux bases (source et referentiel) doivent etre different + DbMode dbMode = localSourceModel.getDbMode(); + if (dbMode == centralSourceModel.getDbMode()) { + if (dbMode == DbMode.USE_REMOTE) { + validate &= !localSourceModel.getPgConfig().getJdbcUrl().equals(centralSourceModel.getPgConfig().getJdbcUrl()); + } + } +// validate &= centralSourceModel.isValid(); + } + if (containsOperation(AdminStep.EXPORT_DATA)) { + + // il faut une base locale et une connexion distante + // avec des droits d'écriture de données + validate &= centralSourceModel.getDataSourceInformation() != null + && centralSourceModel.getDataSourceInformation().canWriteData(); + + } + + if (containsOperation(AdminStep.REPORT)) { + + // il faut le fichier di'mport existe + File reportFile = getReportModel().getReportFile(); + validate &= reportFile != null && + reportFile.exists(); + } + break; + case SELECT_DATA: + + if (containsOperation(AdminStep.VALIDATE)) { + + // la config doit etre ok + validate = validate(AdminStep.CONFIG); + if (validate) { + + // il faut au moins une donnee de selectionnee + boolean empty = selectionModel.isEmpty(); + validate = !empty; + } + } + if (containsOperation(AdminStep.EXPORT_DATA)) { + + // la config doit etre ok + validate &= validate(AdminStep.CONFIG); + if (validate) { + + // il faut au moins une donnee de selectionnee + boolean empty = selectionModel.isDataEmpty(); + validate = !empty; + } + } + if (containsOperation(AdminStep.CONSOLIDATE)) { + + // la config doit etre ok + validate &= validate(AdminStep.CONFIG); + if (validate) { + + // il faut au moins une donnee de selectionnee + boolean empty = selectionModel.isDataEmpty(); + validate = !empty; + } + } + if (containsOperation(AdminStep.REPORT)) { + + // la config doit etre ok + validate &= validate(AdminStep.CONFIG); + if (validate) { + + // il faut exactement une Trip de selectionnee + boolean empty = selectionModel.isDataEmpty(); + validate = !empty && + selectionModel.getSelectedData().size() == 1; + } + } + break; + case VALIDATE: + validate = validate(AdminStep.SELECT_DATA) && + getStepState(step) == WizardState.SUCCESSED; + break; + case EXPORT_DATA: + validate = validate(AdminStep.SELECT_DATA) && + getStepState(step) == WizardState.SUCCESSED; + break; + case CONSOLIDATE: + validate = validate(AdminStep.SELECT_DATA) && + getStepState(step) == WizardState.SUCCESSED; + break; + case REPORT: + + // pour acceder a l'onglet des report, il faut que + // l'onglet de sélection des données soit ok + validate = validate(AdminStep.SELECT_DATA); + break; + case SYNCHRONIZE: + validate = getStepState(step) == WizardState.SUCCESSED; + break; + case SAVE_LOCAL: + // valide si l'action a ete executee avec success + validate = !getSaveLocalModel().isDoBackup() || + getStepState(step) == WizardState.SUCCESSED; + break; + case SHOW_RESUME: + validate = true; + } + return validate; + } + + @Override + protected AdminStep[] updateStepUniverse() { + + List<AdminStep> universe = new ArrayList<>(); + + // toujours l'onglet de configuration des opérations + universe.add(AdminStep.CONFIG); + + // pour savoir si on doit ajouter l'onglet de résumé (cas par défaut) + boolean needResume = true; + if (!operations.isEmpty()) { + + if (needSelect()) { + + // ajout de l'onglet de selection des donnees + universe.add(AdminStep.SELECT_DATA); + } + + if (containsOperation(AdminStep.DATA_SYNCHRONIZE)) { + + universe.add(AdminStep.DATA_SYNCHRONIZE); + } + + if (containsOperation(AdminStep.REFERENTIAL_SYNCHRONIZE)) { + + universe.add(AdminStep.REFERENTIAL_SYNCHRONIZE); + } + + if (containsOperation(AdminStep.SYNCHRONIZE)) { + + // ajout de l'onglet de resolution des entites obsoletes + universe.add(AdminStep.SYNCHRONIZE); + } + + if (containsOperation(AdminStep.VALIDATE)) { + + // ajout de l'onglet de validation + universe.add(AdminStep.VALIDATE); + } + + if (containsOperation(AdminStep.CONSOLIDATE)) { + + // ajout de l'onglet de consolidation + universe.add(AdminStep.CONSOLIDATE); + } + + if (containsOperation(AdminStep.REPORT)) { + + universe.add(AdminStep.REPORT); + + // pas de page de resume + needResume = false; + } + + updateSaveLocalOperation(); + + if (containsOperation(AdminStep.SAVE_LOCAL)) { + + // ajout de l'onglet de sauvegarde de la base locale + universe.add(AdminStep.SAVE_LOCAL); + } + + if (containsOperation(AdminStep.EXPORT_DATA)) { + + // ajout de l'onglet de sauvegarde de la base distante + universe.add(AdminStep.EXPORT_DATA); + } + + if (needResume) { + + // ajout d'un onglet de resume + universe.add(AdminStep.SHOW_RESUME); + } + } + return universe.toArray(new AdminStep[universe.size()]); + } + + public void removeLocalSource() { + if (localSource != null) { + doCloseSource(localSource, false); + localSource = null; + localSourceInformation = null; + } + } + + public void removeCentralSource() { + if (centralSource != null) { + doCloseSource(centralSource, false); + centralSource = null; + } + } + + public void populateSelectionModel(ObserveSwingDataSource source) { + try { + DataSelectionModel.populate(getSelectionDataModel(), source); + + } catch (Exception e) { + if (log.isErrorEnabled()) { + log.error("could not populate selected model", e); + } + } finally { + + // on notifie que le modèle de sélection a changé + // (il faut donc recalculé l'arbre de sélection) + firePropertyChange(SELECTION_MODEL_CHANGED_PROPERTY_NAME, getSelectionDataModel()); + } + } + + protected void computeExistingTrips(ObserveSwingDataSource source) { + + List<DataReference<?>> existingTrip = Lists.newArrayList(); + + TripSeineService tripSeineService = source.newTripSeineService(); + DataReferenceSet<TripSeineDto> tripSeineSet = tripSeineService.getAllTripSeine(); + existingTrip.addAll(tripSeineSet.getReferences()); + + TripLonglineService tripLonglineService = source.newTripLonglineService(); + DataReferenceSet<TripLonglineDto> tripLonglineSet = tripLonglineService.getAllTripLongline(); + existingTrip.addAll(tripLonglineSet.getReferences()); + + + getExportModel().setExistingTripIds(existingTrip); + + } + + protected void updateSaveLocalOperation() { + boolean shouldAdd = false; + for (AdminStep s : operations) { + if (s.isNeedSave()) { + shouldAdd = true; + } + } + if (shouldAdd) { + + // ajout de l'operations + operations.add(AdminStep.SAVE_LOCAL); + } else { + + // on doit supprimer l'operations + operations.remove(AdminStep.SAVE_LOCAL); + } + } + + protected ObserveSwingDataSource createDataSource(StorageUIModel model) { + + ObserveSwingDataSource dataSource = storageHandler.newDataSourceFromModel(model); + return dataSource; + } + + protected void doOpenSource(ObserveSwingDataSource source) { + + if (source != null && !source.isOpen()) { + try { + source.open(); + } catch (DatabaseConnexionNotAuthorizedException | DatabaseNotFoundException | BabModelVersionException e) { + throw new IllegalStateException("Could not open " + source, e); + } + } + + } + + protected void doCloseSource(ObserveSwingDataSource source, boolean destroy) { + + if (source != null && source.isOpen()) { + if (destroy) { + try { + source.destroy(); + } catch (DatabaseDestroyNotAuthorizedException e) { + throw new IllegalStateException("Could not destroy " + source, e); + } + } else { + source.close(); + } + } + + } + + private static class LogPropertyChanged implements PropertyChangeListener { + @Override + public void propertyChange(PropertyChangeEvent evt) { + String name = evt.getPropertyName(); + Object oldValue = evt.getOldValue(); + Object newValue = evt.getNewValue(); + if (log.isDebugEnabled()) { + log.debug(evt.getSource() + " - Property [" + name + "] has changed from " + oldValue + " to " + newValue); + } + + } + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/config/ConfigUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/config/ConfigUI.jaxx new file mode 100644 index 0000000..29e34aa --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/config/ConfigUI.jaxx @@ -0,0 +1,199 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<!-- ************************************************************* --> +<!-- L'écran de configuration des opérations de syncro a realiser --> +<!-- ************************************************************* --> + +<fr.ird.observe.application.swing.ui.admin.AdminTabUI _successIcon='SwingUtil.getUIManagerActionIcon("connect_ok")' + _failedIcon='SwingUtil.getUIManagerActionIcon("connect_no")' + > + + <import> + fr.ird.observe.application.swing.ui.admin.AdminUI + fr.ird.observe.application.swing.ui.admin.AdminStep + fr.ird.observe.application.swing.ui.admin.AdminTabUI + + jaxx.runtime.SwingUtil + java.awt.Color + + javax.swing.Icon + static org.nuiton.i18n.I18n.n + </import> + + + <fr.ird.observe.application.swing.ui.admin.AdminActionModel id='stepModel' initializer='null'/> + + <fr.ird.observe.application.swing.ui.storage.StorageUIModel id='localSourceModel'/> + + <fr.ird.observe.application.swing.ui.storage.StorageUIModel id='centralSourceModel'/> + + <ConfigUIHandler id='handler' constructorParams='this'/> + + <script><![CDATA[ + +public ConfigUI(AdminUI parentContext) { + super(AdminStep.CONFIG, parentContext); +} + +@Override +public void initUI(AdminUI ui) { + getHandler().initTabUI(ui, this); +} + +@Override +public void addMessage(AdminStep step, String text) { + // on enregistre pas les messages pour cette étape +} +]]> + </script> + + <JPanel id='PENDING_content'> + <JPanel id='config' constraints='BorderLayout.CENTER' decorator='boxed'> + <JPanel id="configLabelPanel" constraints='BorderLayout.NORTH'> + <JLabel id="configLabel"/> + </JPanel> + <Table fill='both' + weightx='1' + insets='0' + constraints='BorderLayout.CENTER'> + <row> + <cell> + <Table id='operations' decorator='boxed' fill='both' weightx='1'> + <row> + <cell> + <JCheckBox id='SYNCHRONIZE' + onItemStateChanged='getHandler().updateOperationState((JCheckBox)event.getSource())'/> + </cell> + </row> + <row> + <cell> + <JCheckBox id='DATA_SYNCHRONIZE' + onItemStateChanged='getHandler().updateOperationState((JCheckBox)event.getSource())'/> + </cell> + </row> + <row> + <cell> + <JCheckBox id='REFERENTIAL_SYNCHRONIZE' + onItemStateChanged='getHandler().updateOperationState((JCheckBox)event.getSource())'/> + </cell> + </row> + <row> + <cell> + <JCheckBox id='VALIDATE' + onItemStateChanged='getHandler().updateOperationState((JCheckBox)event.getSource())'/> + </cell> + </row> + <row> + <cell> + <JCheckBox id='EXPORT_DATA' + onItemStateChanged='getHandler().updateOperationState((JCheckBox)event.getSource())'/> + </cell> + </row> + <row> + <cell> + <JCheckBox id='CONSOLIDATE' + onItemStateChanged='getHandler().updateOperationState((JCheckBox)event.getSource())'/> + </cell> + </row> + <row> + <cell> + <JCheckBox id='REPORT' + onItemStateChanged='getHandler().updateOperationState((JCheckBox)event.getSource())'/> + </cell> + </row> + </Table> + </cell> + </row> + + <!-- configuration de la source en entree --> + <row> + <cell fill='both'> + <Table id="localSourceConfig" insets="1"> + <row> + <cell weightx='1' fill='both'> + <JLabel id='localSourceLabel'/> + </cell> + <cell> + <JButton id='configureLocalSource' + onActionPerformed='getHandler().obtainIncomingConnexion()'/> + </cell> + <cell anchor='east'> + <JLabel id='localSourceStatus'/> + </cell> + </row> + <row> + <cell fill='both' columns="2"> + <JLabel id='localSourcePolicy'/> + </cell> + </row> + <!--row> + <cell fill='both' columns="2"> + <JLabel id='localSourceInfoLabel'/> + </cell> + </row--> + </Table> + </cell> + </row> + + <!-- configuration de la source de référence --> + <row> + <cell fill='both'> + <Table id="centralSourceConfig" insets="1"> + <row> + <cell weightx='1' fill='both'> + <JLabel id='centralSourceLabel'/> + </cell> + <cell> + <JButton id='configureCentralSource' + onActionPerformed='getHandler().obtainRemoteConnexion()'/> + </cell> + <cell anchor='east'> + <JLabel id='centralSourceStatus'/> + </cell> + </row> + <row> + <cell fill='both' columns="2"> + <JLabel id='centralSourcePolicy'/> + </cell> + </row> + <row> + <cell fill='both' columns="2"> + <JLabel id='centralSourceInfoLabel'/> + </cell> + </row> + </Table> + </cell> + </row> + + <!-- configuration supplémentaire (fournit par les opérations) --> + <row> + <cell fill='both' weightx='1' weighty='1'> + <JPanel id="extraConfig"/> + </cell> + + </row> + </Table> + </JPanel> + </JPanel> + +</fr.ird.observe.application.swing.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/config/ConfigUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/config/ConfigUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/admin/config/ConfigUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/config/ConfigUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/config/ConfigUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/config/ConfigUIHandler.java new file mode 100644 index 0000000..7d03ea1 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/config/ConfigUIHandler.java @@ -0,0 +1,186 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin.config; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.ObserveTextGenerator; +import fr.ird.observe.services.configuration.ObserveDataSourceInformation; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.admin.AdminStep; +import fr.ird.observe.application.swing.ui.admin.AdminTabUI; +import fr.ird.observe.application.swing.ui.admin.AdminTabUIHandler; +import fr.ird.observe.application.swing.ui.admin.AdminUI; +import fr.ird.observe.application.swing.ui.storage.StorageStep; +import fr.ird.observe.application.swing.ui.storage.StorageUIHandler; +import fr.ird.observe.application.swing.ui.storage.StorageUILauncher; +import fr.ird.observe.application.swing.ui.storage.StorageUIModel; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JCheckBox; +import javax.swing.JLabel; +import javax.swing.JTree; +import java.awt.Window; +import java.util.Set; + +import static org.nuiton.i18n.I18n.t; + +/** + * Le controleur des onglets. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ConfigUIHandler extends AdminTabUIHandler { + + /** Logger */ + private static final Log log = LogFactory.getLog(ConfigUIHandler.class); + + public ConfigUIHandler(AdminTabUI ui) { + super(ui); + } + + public void initTabUI(AdminUI ui, ConfigUI tabUI) { + + super.initTabUI(ui, tabUI); + + if (log.isDebugEnabled()) { + log.debug("specialized for [" + tabUI.getStep() + "] for main ui " + ui.getClass().getName() + "@" + System.identityHashCode(ui)); + } + + UIHelper.setLayerUI(tabUI.getOperations(), ui.getOperationBlockLayerUI()); + UIHelper.setLayerUI(tabUI.getConfig(), ui.getConfigBlockLayerUI()); + UIHelper.setLayerUI(tabUI.getContent(), null); + } + + + public void initTabUI(AdminUI ui, SelectDataUI tabUI) { + + super.initTabUI(ui, tabUI); + + if (log.isDebugEnabled()) { + log.debug(" specialized for [" + tabUI.getStep() + "] for main ui " + ui.getClass().getName() + "@" + System.identityHashCode(ui)); + } + + UIHelper.setLayerUI(tabUI.getContent(), null); + UIHelper.setLayerUI(tabUI.getSelectTreePane(), ui.getConfigBlockLayerUI()); + + JTree tree = tabUI.getSelectTree(); + tabUI.getTreeHelper().setUI(tree, false, null); + + // customize tree selection colors + UIHelper.initUI(tabUI.getSelectTreePane(), tree); + } + + public void updateOperationState(JCheckBox checkBox) { + AdminStep op = getOperation(checkBox); + if (log.isDebugEnabled()) { + log.debug("Operation " + op + " selection has changed : selected:" + checkBox.isSelected()); + } + if (checkBox.isSelected()) { + // ajout de l'operation + getModel().addOperation(op); + } else { + // supprime cette opération + getModel().removeOperation(op); + } + } + + public String updateStorageLabel(StorageUIModel service, + boolean serviceValid, + JLabel label) { + String text; + if (serviceValid) { + + // on recupere le label du service + text = service.getLabel(); + } else { + + // aucun service configuré + text = t((String) label.getClientProperty("no")); + } + return text; + } + + public AdminStep getOperation(JCheckBox checkBox) { + return AdminStep.valueOf(checkBox.getName()); + } + + public boolean isOperationSelected(Set<AdminStep> operations, + JCheckBox checkBox) { + AdminStep scope = getOperation(checkBox); + return operations.contains(scope); + } + + public StorageUIHandler getStorageHandler() { + return ui.getContextValue(StorageUIHandler.class); + } + + public void obtainIncomingConnexion() { + StorageUIModel sourceModel = ui.getLocalSourceModel(); + StorageUILauncher.obtainConnexion(ui, ui.getParentContainer(Window.class), sourceModel); + if (log.isDebugEnabled()) { + log.debug("After modifiy source model isValid : " + sourceModel.isValid() + " / " + sourceModel.isValidStep()); + } + model.removeLocalSource(); + model.getLocalSourceModel().validate(); + model.validate(); + } + + public void obtainRemoteConnexion() { + if (log.isInfoEnabled()) { + log.info("start obtain remote connexion"); + } + StorageUIModel sourceModel = ui.getCentralSourceModel(); + StorageUILauncher.obtainConnexion(ui, ui.getParentContainer(Window.class), sourceModel); + model.removeCentralSource(); + model.getCentralSourceModel().validate(StorageStep.CONFIG); + model.validate(); + } + + protected String updateDataSourcePolicy(StorageUIModel sourceModel, boolean valid) { + String text = null; + if (valid) { + ObserveDataSourceInformation dataSourceInformation = sourceModel.getDataSourceInformation(); + + if (dataSourceInformation != null) { + + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ObserveTextGenerator textGenerator = applicationContext.getTextGenerator(); + text = textGenerator.getDataSourcePolicy(dataSourceInformation); + } + + } else { + + text = t("observe.common.storage.not.valid"); + + } + + return text; + } + + protected boolean canShowLocalStorage(Set<AdminStep> operations, + boolean needLocalStorage) { + return !operations.isEmpty() && needLocalStorage; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/config/SelectDataUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/config/SelectDataUI.jaxx new file mode 100644 index 0000000..7b64aee --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/config/SelectDataUI.jaxx @@ -0,0 +1,87 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<!-- ************************************************************* --> +<!-- L'écran de configuration des opérations de syncro a realiser --> +<!-- ************************************************************* --> + +<fr.ird.observe.application.swing.ui.admin.AdminTabUI> + + <import> + fr.ird.observe.application.swing.ui.UIHelper + fr.ird.observe.application.swing.ui.admin.AdminUI + fr.ird.observe.application.swing.ui.admin.AdminStep + fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper + fr.ird.observe.application.swing.ui.tree.DataSelectionTreeCellRenderer + fr.ird.observe.application.swing.ui.tree.DataSelectionTreeSelectionModel + fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel + + jaxx.runtime.SwingUtil + + javax.swing.tree.TreeSelectionModel + + </import> + + <ObserveTreeHelper id='treeHelper'/> + + <ConfigUIHandler id='handler' constructorParams='this'/> + + <fr.ird.observe.application.swing.ui.admin.AdminActionModel id='stepModel' initializer='null'/> + + <DataSelectionModel id='selectDataModel' + initializer='getModel().getSelectionDataModel()'/> + + <DataSelectionTreeSelectionModel id='selectionModel'/> + + <DataSelectionTreeCellRenderer id='selectionRenderer' + constraints='BorderLayout.EAST'/> + + <script><![CDATA[ +public SelectDataUI(AdminUI parentContext) { + super(AdminStep.SELECT_DATA, parentContext); +} + +public void initUI(AdminUI ui) { + getHandler().initTabUI(ui, this); +} + +@Override +public void destroy() { + selectionModel.clearSelection(); + //selectDataModel = null; + super.destroy(); +} +]]> + </script> + + <JPanel id='PENDING_content'> + + <JScrollPane id='selectTreePane' constraints='BorderLayout.CENTER' + decorator='boxed'> + + <!-- arbre de selection des exports --> + <JTree id='selectTree'/> + </JScrollPane> + </JPanel> + + +</fr.ird.observe.application.swing.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/config/SelectDataUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/config/SelectDataUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/admin/config/SelectDataUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/config/SelectDataUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/consolidate/ConsolidateModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/consolidate/ConsolidateModel.java new file mode 100644 index 0000000..98b58f4 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/consolidate/ConsolidateModel.java @@ -0,0 +1,56 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin.consolidate; + +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.ui.admin.AdminActionModel; +import fr.ird.observe.application.swing.ui.admin.AdminStep; + +/** + * Modele pour preparer une validation de donnees d'une base. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.5 + */ +public class ConsolidateModel extends AdminActionModel { + + /** la source de données où effectuer la consolidation des données */ + private ObserveSwingDataSource source; + + public ConsolidateModel() { + super(AdminStep.CONSOLIDATE); + } + + public ObserveSwingDataSource getSource() { + return source; + } + + public void setSource(ObserveSwingDataSource source) { + this.source = source; + } + + @Override + public void destroy() { + super.destroy(); + source = null; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/consolidate/ConsolidateUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/consolidate/ConsolidateUI.jaxx new file mode 100644 index 0000000..6b96fcc --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/consolidate/ConsolidateUI.jaxx @@ -0,0 +1,65 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<!-- ********************************************** --> +<!-- L'écran de validation des données observers --> +<!-- ********************************************** --> + +<fr.ird.observe.application.swing.ui.admin.AdminTabUI> + + <import> + fr.ird.observe.application.swing.ui.admin.AdminStep + fr.ird.observe.application.swing.ui.admin.AdminTabUI + fr.ird.observe.application.swing.ui.admin.AdminUI + </import> + + <ConsolidateUIHandler id='handler' constructorParams='this'/> + + <ConsolidateModel id='stepModel' + initializer='getModel().getConsolidateModel()'/> + + <script><![CDATA[ +public ConsolidateUI(AdminUI parentContext) { + super(AdminStep.CONSOLIDATE, parentContext); +} + +@Override +public void initUI(AdminUI ui) { + log.info("for [" + getStep() + "]"); + getHandler().initTabUI(ui, this); +} + +]]> + </script> + + <JPanel id='PENDING_content'> + <Table constraints='BorderLayout.CENTER' fill='both' weightx='1' + weighty='1'> + <row> + <cell> + <JButton id='startButton' + onActionPerformed="getHandler().startAction()"/> + </cell> + </row> + </Table> + </JPanel> +</fr.ird.observe.application.swing.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/consolidate/ConsolidateUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/consolidate/ConsolidateUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/admin/consolidate/ConsolidateUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/consolidate/ConsolidateUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/consolidate/ConsolidateUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/consolidate/ConsolidateUIHandler.java new file mode 100644 index 0000000..a7c1b04 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/consolidate/ConsolidateUIHandler.java @@ -0,0 +1,186 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin.consolidate; + +import com.google.common.collect.ImmutableSet; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.service.actions.consolidate.ConsolidateActivitySeineDataResult; +import fr.ird.observe.services.service.actions.consolidate.ConsolidateDataService; +import fr.ird.observe.services.service.actions.consolidate.ConsolidateTripSeineDataRequest; +import fr.ird.observe.services.service.actions.consolidate.ConsolidateTripSeineDataResult; +import fr.ird.observe.application.swing.ui.admin.AdminStep; +import fr.ird.observe.application.swing.ui.admin.AdminTabUI; +import fr.ird.observe.application.swing.ui.admin.AdminTabUIHandler; +import fr.ird.observe.application.swing.ui.admin.AdminUI; +import fr.ird.observe.application.swing.ui.admin.AdminUIModel; +import fr.ird.observe.application.swing.ui.admin.config.SelectDataUI; +import fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel; +import jaxx.runtime.swing.wizard.ext.WizardState; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.beans.PropertyChangeListener; +import java.util.Date; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.nuiton.i18n.I18n.t; + +/** + * Le controleur des onglets. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.5 + */ +public class ConsolidateUIHandler extends AdminTabUIHandler { + + /** Logger */ + private static final Log log = LogFactory.getLog(ConsolidateUIHandler.class); + + public ConsolidateUIHandler(AdminTabUI ui) { + super(ui); + } + + public ConsolidateModel getStepModel() { + return model.getConsolidateModel(); + } + + public void initTabUI(AdminUI ui, ConsolidateUI tabUI) { + + super.initTabUI(ui, tabUI); + + if (log.isDebugEnabled()) { + log.debug(" specialized for [" + tabUI.getStep() + + "] for main ui " + ui.getClass().getName() + "@" + + System.identityHashCode(ui)); + } + + tabUI.getStartButton().setText( + t("observe.actions.synchro.launch.operation", + t(tabUI.getStep().getOperationLabel()))); + + final SelectDataUI selectTabUI = (SelectDataUI) + ui.getStepUI(AdminStep.SELECT_DATA); + + PropertyChangeListener listener = evt -> { + AdminUIModel model1 = (AdminUIModel) evt.getSource(); + if (!model1.containsStep(selectTabUI.getStep())) { + // avoid multi-cast + return; + } + DataSelectionModel value = (DataSelectionModel) evt.getNewValue(); + if (log.isDebugEnabled()) { + log.debug("selection model changed to " + value); + } + updateSelectionModel(selectTabUI); + }; + tabUI.getModel().addPropertyChangeListener( + AdminUIModel.SELECTION_MODEL_CHANGED_PROPERTY_NAME, + listener + ); + } + + public void startAction() { + + addAdminWorker(((ConsolidateUI) ui).getStartButton().getToolTipText(), this::doAction); + } + + public WizardState doAction() throws Exception { + if (log.isDebugEnabled()) { + log.debug(this); + } + + WizardState init = initDB(); + + if (init != null) { + + // une erreur ou une annulation + return init; + } + Set<DataReference> trips = model.getSelectionDataModel().getSelectedData(); + ImmutableSet<String> tripIds = ImmutableSet.copyOf(trips.stream() + .filter(DataReference.newTripSeinePredicate()) + .map(DataReference.ID_FUNCTION) + .collect(Collectors.toSet())); + + ObserveSwingDataSource dataSource = getStepModel().getSource(); + + try { + + ConsolidateDataService consolidateDataService = dataSource.newConsolidateDataService(); + + ConsolidateTripSeineDataRequest request = new ConsolidateTripSeineDataRequest(); + request.setTripSeineIds(tripIds); + request.setFailIfLenghtWeightParameterNotFound(false); + + ImmutableSet<ConsolidateTripSeineDataResult> results = consolidateDataService.consolidateTripSeines(request); + + if (results.isEmpty()) { + + sendMessage(t("observe.actions.consolidate.message.noChanges")); + + } else { + + for (ConsolidateTripSeineDataResult tripSeineDataResult : results) { + + String tripSeineLabel = tripSeineDataResult.getTripSeineLabel(); + + sendMessage(t("observe.actions.consolidate.message.trip", tripSeineLabel)); + + for (ConsolidateActivitySeineDataResult activitySeineDataResult : tripSeineDataResult.getConsolidateActivitySeineDataResults()) { + + sendMessage(t("observe.actions.consolidate.message.activity", activitySeineDataResult.getActivitySeineLabel())); + + } + + } + + sendMessage(t("observe.actions.consolidate.message.save.changes", results.size())); + } + + sendMessage(t("observe.actions.consolidate.message.operation.done", + new Date())); + + } finally { + + dataSource.close(); + + } + + + return WizardState.SUCCESSED; + } + + + protected WizardState initDB() throws Exception { + + // on recupere la source de données + ObserveSwingDataSource source = model.getSafeLocalSource(false); + getStepModel().setSource(source); + + openSource(source); + + return null; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/export/ExportModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/export/ExportModel.java new file mode 100644 index 0000000..2b798cb --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/export/ExportModel.java @@ -0,0 +1,179 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin.export; + +import com.google.common.collect.ImmutableList; +import com.google.common.collect.Lists; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.AbstractReference; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.application.swing.ui.admin.AdminActionModel; +import fr.ird.observe.application.swing.ui.admin.AdminStep; +import fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel; +import fr.ird.observe.application.swing.decoration.decorators.DataReferenceDecorator; +import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * Le modèle d'une opération d'export de données observers. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ExportModel extends AdminActionModel { + + /** les index des marées à exporter. */ + protected int[] exportDataSelectedIndex; + + /** les ids des marées déjà existante sur la base distante lors d'un export */ + protected List<DataReference<?>> existingTrips; + + /** les données exportables */ + protected List<TripEntry> data; + + protected ReferentialReferenceDecorator<ProgramDto> programDecorator; + + protected DataReferenceDecorator<TripSeineDto> tripSeineDecorator; + + protected DataReferenceDecorator<TripLonglineDto> tripLonglineDecorator; + + protected ObserveSwingDataSource source; + + protected ObserveSwingDataSource centralSource; + + public ExportModel() { + super(AdminStep.EXPORT_DATA); + } + + public void setExportDataSelectedIndex(int... exportDataSelectedIndex) { + this.exportDataSelectedIndex = exportDataSelectedIndex; + } + + public List<DataReference<?>> getExistingTrips() { + return existingTrips; + } + + public void setExistingTripIds(List<DataReference<?>> existingTrips) { + this.existingTrips = existingTrips; + } + + @Override + public void destroy() { + super.destroy(); + if (existingTrips != null) { + existingTrips.clear(); + existingTrips = null; + } + exportDataSelectedIndex = null; + tripSeineDecorator = null; + data = null; + centralSource = null; + source = null; + } + + public List<TripEntry> getData() { + return data; + } + + public void setData(DataSelectionModel selectionModel) { + + List<TripEntry> tripEntries = Lists.newArrayList(); + + for (Map.Entry<ReferentialReference<ProgramDto>, List<DataReference>> entry : selectionModel.getSelectedDataByProgram().entrySet()) { + + ReferentialReference<ProgramDto> program = entry.getKey(); + + for (DataReference trip : entry.getValue()) { + + boolean exists = existingTrips.contains(trip); + + TripEntry tripEntry = new TripEntry(program, trip, exists); + + tripEntries.add(tripEntry); + } + } + + this.data = ImmutableList.copyOf(tripEntries); + + } + + public ObserveSwingDataSource getSource() { + return source; + } + + public void setSource(ObserveSwingDataSource source) { + this.source = source; + } + + public ObserveSwingDataSource getCentralSource() { + return centralSource; + } + + public void setCentralSource(ObserveSwingDataSource centralSource) { + this.centralSource = centralSource; + } + + public void setProgramDecorator(ReferentialReferenceDecorator<ProgramDto> programDecorator) { + this.programDecorator = programDecorator; + } + + public void setTripSeineDecorator(DataReferenceDecorator<TripSeineDto> mareeDecorator) { + this.tripSeineDecorator = mareeDecorator; + } + + public void setTripLonglineDecorator(DataReferenceDecorator<TripLonglineDto> tripLonglineDecorator) { + this.tripLonglineDecorator = tripLonglineDecorator; + } + + public String decorate(AbstractReference referenceDto) { + String decor = null; + + if (ProgramDto.class.isAssignableFrom(referenceDto.getType())) { + decor = programDecorator.toString(referenceDto); + } else if (TripSeineDto.class.isAssignableFrom(referenceDto.getType())) { + decor = tripSeineDecorator.toString(referenceDto); + } else if (TripLonglineDto.class.isAssignableFrom(referenceDto.getType())) { + decor = tripLonglineDecorator.toString(referenceDto); + } + + return decor; + } + + public List<TripEntry> getSelectedTrips() { + + List<TripEntry> entries = new ArrayList<>(); + + for (int index : exportDataSelectedIndex) { + entries.add(data.get(index)); + } + return entries; + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/export/ExportUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/export/ExportUI.jaxx new file mode 100644 index 0000000..42121b2 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/export/ExportUI.jaxx @@ -0,0 +1,89 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<!-- ***************************************** --> +<!-- L'écran d'export des données observers --> +<!-- ***************************************** --> + +<fr.ird.observe.application.swing.ui.admin.AdminTabUI> + <import> + fr.ird.observe.application.swing.ui.admin.AdminUI + fr.ird.observe.application.swing.ui.admin.AdminStep + + jaxx.runtime.swing.wizard.ext.WizardState + </import> + + + <ExportModel id='stepModel' initializer='getModel().getExportModel()'/> + + <ExportUIHandler id='handler' constructorParams='this'/> + + <!-- le modèles des activités dont on a pu calculé un point gps --> + <TripToExportTableModel id='tripsModel' onTableChanged='startAction.setEnabled(tripsModel.hasSelection())'/> + + <script><![CDATA[ +public ExportUI(AdminUI parentContext) { + super(AdminStep.EXPORT_DATA, parentContext); +} + +@Override +public void initUI(AdminUI ui) { + log.info("for [" + getStep() + "]"); + getHandler().initTabUI(ui, this); +} + +@Override +public void destroy() { + super.destroy(); + tripsModel.clear(); +} + +@Override +public void updateState(WizardState newState) { + getHandler().updateState(this, newState); +} +]]> + </script> + + <JPanel id='PENDING_content'> + <Table constraints='BorderLayout.CENTER' fill='both' weightx='1' weighty='1'> + <row> + <cell> + <JButton id="prepareAction" onActionPerformed="getHandler().doPrepareAction()"/> + </cell> + </row> + </Table> + </JPanel> + + <JPanel id='NEED_FIX_content'> + + <!-- la liste des trips --> + <JScrollPane id='tripPane' constraints='BorderLayout.CENTER'> + <JTable id='trips'/> + </JScrollPane> + + <JPanel constraints='BorderLayout.SOUTH' layout='{new BorderLayout()}'> + <JButton id='startAction' constraints='BorderLayout.CENTER' onActionPerformed="getHandler().doStartAction()"/> + </JPanel> + </JPanel> + +</fr.ird.observe.application.swing.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/export/ExportUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/export/ExportUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/admin/export/ExportUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/export/ExportUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/export/ExportUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/export/ExportUIHandler.java new file mode 100644 index 0000000..59f11b9 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/export/ExportUIHandler.java @@ -0,0 +1,334 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin.export; + +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Maps; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.services.service.BabModelVersionException; +import fr.ird.observe.services.service.DatabaseConnexionNotAuthorizedException; +import fr.ird.observe.services.service.DatabaseNotFoundException; +import fr.ird.observe.services.service.actions.export.ReplicateTripService; +import fr.ird.observe.services.service.actions.export.ReplicateTripsExportRequest; +import fr.ird.observe.services.service.actions.export.ReplicateTripsExportResult; +import fr.ird.observe.services.service.actions.export.ReplicateTripsImportResult; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.admin.AdminStep; +import fr.ird.observe.application.swing.ui.admin.AdminTabUI; +import fr.ird.observe.application.swing.ui.admin.AdminTabUIHandler; +import fr.ird.observe.application.swing.ui.admin.AdminUI; +import fr.ird.observe.application.swing.ui.admin.AdminUIModel; +import fr.ird.observe.application.swing.ui.admin.config.SelectDataUI; +import fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel; +import fr.ird.observe.application.swing.decoration.decorators.DataReferenceDecorator; +import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; +import jaxx.runtime.swing.editor.MyDefaultCellEditor; +import jaxx.runtime.swing.wizard.ext.WizardState; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.Date; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Le controleur des onglets. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ExportUIHandler extends AdminTabUIHandler { + + /** Logger */ + private static final Log log = LogFactory.getLog(ExportUIHandler.class); + + public ExportUIHandler(AdminTabUI ui) { + super(ui); + } + + public void initTabUI(AdminUI ui, ExportUI tabUI) { + + super.initTabUI(ui, tabUI); + + if (log.isDebugEnabled()) { + log.debug(" specialized for [" + tabUI.getStep() + "] for main ui " + ui.getClass().getName() + "@" + System.identityHashCode(ui)); + } + + tabUI.getPrepareAction().setText(t("observe.actions.synchro.prepare.operation", t(tabUI.getStep().getOperationLabel()))); + tabUI.getStartAction().setText(t("observe.actions.synchro.launch.operation", t(tabUI.getStep().getOperationLabel()))); + + final SelectDataUI selectTabUI = (SelectDataUI) ui.getStepUI(AdminStep.SELECT_DATA); + + tabUI.getModel().addPropertyChangeListener(AdminUIModel.SELECTION_MODEL_CHANGED_PROPERTY_NAME, evt -> { + AdminUIModel model1 = (AdminUIModel) evt.getSource(); +// if (!getModel().containsStep(tabUI.getStep())) { +// // avoid multi-cast +// return; +// } + + DataSelectionModel value = (DataSelectionModel) evt.getNewValue(); + if (log.isInfoEnabled()) { + log.info("selection model changed to " + value); + } + + selectTabUI.getSelectionModel().clearSelection(); + selectTabUI.getSelectionRenderer().setExistingTrips(model1.getExportModel().getExistingTrips()); + updateSelectionModel(selectTabUI); + }); + + // tableau de l'export de données + + final JTable table4 = tabUI.getTrips(); + table4.setRowHeight(24); + + UIHelper.fixTableColumnWidth(table4, 0, 20); + UIHelper.fixTableColumnWidth(table4, 3, 20); + + DefaultTableCellRenderer renderer5 = new DefaultTableCellRenderer(); + + UIHelper.setI18nTableHeaderRenderer( + table4, + n("observe.actions.exportData.table.selected"), + n("observe.actions.exportData.table.selected.tip"), + n("observe.actions.exportData.table.program.label"), + n("observe.actions.exportData.table.program.label.tip"), + n("observe.actions.exportData.table.trip.label"), + n("observe.actions.exportData.table.trip.label.tip"), + n("observe.actions.exportData.table.exist.label"), + n("observe.actions.exportData.table.exist.label.tip")); + + UIHelper.setTableColumnRenderer(table4, 0, UIHelper.newBooleanTableCellRenderer(renderer5)); + UIHelper.setTableColumnRenderer(table4, 1, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer5, ProgramDto.class)); + UIHelper.setTableColumnRenderer(table4, 2, UIHelper.newDecorateTableCellRenderer(renderer5, DataReference.class, DecoratorService.TRIP_CONTEXT)); + UIHelper.setTableColumnRenderer(table4, 3, UIHelper.newBooleanTableCellRenderer(renderer5)); + UIHelper.setTableColumnEditor(table4, 0, MyDefaultCellEditor.newBooleanEditor(false)); + + // pour tout selectionner - deselectionner dans l'entete du tableau + table4.getTableHeader().addMouseListener(new MouseAdapter() { + + @Override + public void mouseClicked(MouseEvent e) { + + int colIndex = table4.getTableHeader().columnAtPoint(e.getPoint()); + colIndex = table4.convertColumnIndexToModel(colIndex); + if (colIndex == 0) { + TripToExportTableModel model = (TripToExportTableModel) table4.getModel(); + boolean oldValue = model.isSelectAll(); + // toggle selectAll + model.setSelectAll(!oldValue); + } + } + }); + } + + public void updateState(ExportUI tabUI, WizardState newState) { + super.updateState(tabUI, newState); + if (newState == WizardState.NEED_FIX) { + // met a jour la liste des marées + tabUI.tripsModel.init(tabUI.getStepModel().getData()); + return; + } + if (newState == WizardState.RUNNING) { + + } + } + + public void doPrepareAction() { + + addAdminWorker( + ((ExportUI) ui).getPrepareAction().getToolTipText(), + this::prepareAction + ); + } + + public void doStartAction() { + + ExportUI tabUI = (ExportUI) ui; + + int[] rows = tabUI.getTripsModel().getSelected(); + tabUI.getModel().getExportModel().setExportDataSelectedIndex(rows); + + addAdminWorker( + tabUI.getStartAction().getToolTipText(), + this::doAction + ); + + } + + public WizardState prepareAction() throws Exception { + + DecoratorService decoratorProvider = getDecoratorService(); + ExportModel stepModel = model.getExportModel(); + + ReferentialReferenceDecorator<ProgramDto> pDecorator = decoratorProvider.getReferentialReferenceDecorator(ProgramDto.class); + DataReferenceDecorator<TripLonglineDto> tripLonglineDecorator = decoratorProvider.getDataReferenceDecorator(TripLonglineDto.class); + DataReferenceDecorator<TripSeineDto> tripSeineDecorator = decoratorProvider.getDataReferenceDecorator(TripSeineDto.class); + stepModel.setProgramDecorator(pDecorator); + stepModel.setTripSeineDecorator(tripSeineDecorator); + stepModel.setTripLonglineDecorator(tripLonglineDecorator); + + ObserveSwingDataSource centralSource = model.getSafeCentralSource(false); + + stepModel.setCentralSource(centralSource); + + if (!centralSource.canWriteData()) { + // l'utilisateur n'a pas le droit d'écrire sur la base distante + sendMessage(t("observe.message.can.not.write.data")); + return WizardState.FAILED; + } + + ObserveSwingDataSource source = model.getSafeLocalSource(false); + + stepModel.setSource(source); + + // ouverture de la base distante + openSource(centralSource); + + // ouverture base source + openSource(source); + + // il s'agit de la première passe : préparation des données + + sendMessage(t("observe.actions.exportData.message.prepare.data")); + + // récupération des couples (program, marees) sur la base temporaire + DataSelectionModel selectionModel = model.getSelectionDataModel(); + stepModel.setData(selectionModel); + + List<TripEntry> entries = stepModel.getData(); + + if (entries.isEmpty()) { + // pas de données possible à exporter + sendMessage(t("observe.actions.exportData.message.not.possible")); + sendMessage(t("observe.actions.operation.message.done", new Date())); + return WizardState.CANCELED; + } + + sendMessage(t("observe.actions.exportData.message.operation.needFix", new Date())); + + // on rend la main à l'ui pour que l'utilisateur selectionne les marees a exporter + return WizardState.NEED_FIX; + } + + public WizardState doAction() throws Exception { + + ExportModel stepModel = model.getExportModel(); + + // on filtre les marées sélectionnées pour export + List<TripEntry> selectedTripEntries = stepModel.getSelectedTrips(); + + ReplicateTripsImportResult results = replicateData(stepModel.getSource(), stepModel.getCentralSource(), selectedTripEntries); + + ImmutableMap<String, TripEntry> tripEntriesById = Maps.uniqueIndex(selectedTripEntries, tripEntry -> tripEntry.getTrip().getId()); + + for (ReplicateTripsImportResult.ReplicateTripImportResult result : results) { + + String tripId = result.getTripId(); + + TripEntry tripEntry = tripEntriesById.get(tripId); + + String tripDecorated = stepModel.decorate(tripEntry.getTrip()); + String programDecorated = stepModel.decorate(tripEntry.getProgram()); + + if (result.isDeleted()) { + + if (log.isInfoEnabled()) { + log.info(tripId + " → " + t("observe.actions.exportData.message.delete.remote.maree", tripDecorated, programDecorated)); + } + sendMessage(t("observe.actions.exportData.message.delete.remote.maree", tripDecorated, programDecorated)); + } + + if (log.isInfoEnabled()) { + log.info(tripId + " → " + t("observe.actions.exportData.message.replicate.maree", tripDecorated, programDecorated)); + } + sendMessage(t("observe.actions.exportData.message.replicate.maree", tripDecorated, programDecorated)); + + } + + sendMessage(t("observe.actions.operation.message.done", new Date())); + + return WizardState.SUCCESSED; + } + + private ReplicateTripsImportResult replicateData(ObserveSwingDataSource source, + ObserveSwingDataSource target, + List<TripEntry> tripEntries) throws DatabaseNotFoundException, BabModelVersionException, DatabaseConnexionNotAuthorizedException { + + Preconditions.checkState(CollectionUtils.isNotEmpty(tripEntries)); + + ReplicateTripsExportRequest.ExportTripsRequestBuilder requestBuilder = ReplicateTripsExportRequest.builder(); + + for (TripEntry tripEntry : tripEntries) { + + requestBuilder.addTripToReplicate(tripEntry.getTrip().getId(), tripEntry.isExist()); + + } + + ReplicateTripsExportRequest request = requestBuilder.build(); + + ReplicateTripsExportResult tripExportResults; + + try { + + openSource(source); + ReplicateTripService sourceReplicateService = source.newReplicateTripService(); + tripExportResults = sourceReplicateService.exportTrips(request); + + } finally { + + source.close(); + + } + + ReplicateTripsImportResult result; + + try { + + openSource(target); + ReplicateTripService targetReplicateService = target.newReplicateTripService(); + result = targetReplicateService.importTrips(tripExportResults); + + } finally { + + target.close(); + + } + + return result; + + } + + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/export/TripEntry.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/export/TripEntry.java new file mode 100644 index 0000000..cb2a634 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/export/TripEntry.java @@ -0,0 +1,59 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin.export; + +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; + +import java.io.Serializable; + +/** Une classe qui représente une entrée dans le modèle (sans la sélection) */ +public class TripEntry implements Serializable { + + private static final long serialVersionUID = 1L; + + protected final ReferentialReference<ProgramDto> program; + + protected final DataReference trip; + + protected final boolean exist; + + public TripEntry(ReferentialReference<ProgramDto> program, DataReference trip, boolean exist) { + this.program = program; + this.trip = trip; + this.exist = exist; + } + + public ReferentialReference<ProgramDto> getProgram() { + return program; + } + + public DataReference getTrip() { + return trip; + } + + public boolean isExist() { + return exist; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/export/TripToExportTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/export/TripToExportTableModel.java new file mode 100644 index 0000000..f3cad83 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/export/TripToExportTableModel.java @@ -0,0 +1,170 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin.export; + +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.referential.ReferentialReference; + +import javax.swing.table.AbstractTableModel; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Le modèle pour la tableau dans l'export GPS qui contient les activités et les + * points gps calculés via le fichier gps importé. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class TripToExportTableModel extends AbstractTableModel { + + protected static final Class<?>[] COLUMN_CLASSES = { + Boolean.class, + ReferentialReference.class, //program + DataReference.class, // trip + Boolean.class + }; + + private static final long serialVersionUID = 1L; + + protected TripEntry[] data; + + protected final Set<Integer> selected; + + protected boolean selectAll; + + public TripToExportTableModel() { + selected = new HashSet<>(); + } + + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + // seule la première colonne est éditable (selection des marées à + // exporter) + return columnIndex == 0; + } + + public int[] getSelected() { + int[] result = new int[selected.size()]; + int i = 0; + for (Integer index : selected) { + result[i++] = index; + } + return result; + } + + public boolean hasSelection() { + return !selected.isEmpty(); + } + + /** + * Initialise le modèle. + * + * @param data les entrées du modèles (program-maree-existe à distance) + */ + public void init(List<TripEntry> data) { + + this.data = data.toArray(new TripEntry[data.size()]); + + selected.clear(); + // par defaut, on selectionne toutes les references + setSelectAll(true); + } + + public void clear() { + data = null; + } + + @Override + public int getRowCount() { + return data == null ? 0 : data.length; + } + + @Override + public int getColumnCount() { + return COLUMN_CLASSES.length; + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + Object value = null; + TripEntry tripEntry = data == null ? null : data[rowIndex]; + if (tripEntry != null) { + switch (columnIndex) { + case 0: + value = selected.contains(rowIndex); + break; + case 1: + value = tripEntry.getProgram(); + break; + case 2: + value = tripEntry.getTrip(); + break; + case 3: + value = tripEntry.isExist(); + break; + default: + throw new IllegalStateException("can not get value for row " + rowIndex + ", col " + columnIndex); + } + } + return value; + } + + public boolean isSelectAll() { + return selectAll; + } + + public void setSelectAll(boolean selectAll) { + this.selectAll = selectAll; + if (selectAll) { + for (int i = 0, max = getRowCount(); i < max; i++) { + selected.add(i); + } + } else { + selected.clear(); + } + fireTableDataChanged(); + } + + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + if (columnIndex == 0) { + Boolean value = (Boolean) aValue; + if (value) { + selected.add(rowIndex); + if (selected.size() == getRowCount()) { + selectAll = true; + } + } else { + selected.remove(rowIndex); + if (selected.isEmpty()) { + selectAll = false; + } + } + fireTableCellUpdated(rowIndex, columnIndex); + } + + // no edit for others columns + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/report/ReportConfigUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/report/ReportConfigUI.jaxx new file mode 100644 index 0000000..c3f0e37 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/report/ReportConfigUI.jaxx @@ -0,0 +1,70 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<!-- ************************************************************* --> +<!-- La configuration de l'import GPS --> +<!-- ************************************************************* --> + +<Table id="reportConfig"> + + <import> + fr.ird.observe.application.swing.ui.admin.AdminUIModel + + java.io.File + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + </import> + + <ReportUIHandler id='handler' + initializer='getContextValue(ReportUIHandler.class)'/> + + <AdminUIModel id='model' initializer='getContextValue(AdminUIModel.class)'/> + + <ReportModel id='stepModel' initializer='model.getReportModel()'/> + + <script><![CDATA[ +public void destroy() { + model = null; + stepModel = null; +} + +@Override +protected void finalize() throws Throwable { + super.finalize(); + destroy(); +} +]]> + </script> + + <row> + <cell anchor="west"> + <JLabel id='reportFileLabel'/> + </cell> + <cell weightx='1' fill="horizontal"> + <JTextField id="reportFile" + onKeyReleased='stepModel.setReportFile(new File(((JTextField)event.getSource()).getText()))'/> + </cell> + <cell anchor="east"> + <JButton id="reportFileChooserAction" + onActionPerformed="getHandler().chooseReportFile()"/> + </cell> + </row> +</Table> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/report/ReportConfigUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/report/ReportConfigUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/admin/report/ReportConfigUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/report/ReportConfigUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/report/ReportModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/report/ReportModel.java new file mode 100644 index 0000000..f16294d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/report/ReportModel.java @@ -0,0 +1,248 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin.report; + +import fr.ird.observe.services.dto.actions.report.Report; +import fr.ird.observe.services.service.actions.report.ReportBuilder; +import fr.ird.observe.application.swing.ui.admin.AdminActionModel; +import fr.ird.observe.application.swing.ui.admin.AdminStep; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.File; +import java.io.IOException; +import java.net.URL; +import java.util.List; +import java.util.Map; +import java.util.TreeMap; +import java.util.regex.Pattern; + +/** + * Le modèle utilisé pour la fonctionnalité de génération de rapport. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.3 + */ +public class ReportModel extends AdminActionModel { + + public static final String SELECTED_MAREE_PROPERTY_NAME = "selectedTrip"; + + public static final String SELECTED_REPORT_PROPERTY_NAME = "selectedReport"; + + public static final String REPORTS_PROPERTY_NAME = "reports"; + + public static final String REPORT_FILE_PROPERTY_NAME = "reportFile"; + + public static final String COPY_ROW_HEADERS_PROPERTY_NAME = "copyRowHeaders"; + + public static final String COPY_COLUMN_HEADERS_PROPERTY_NAME = "copyColumnHeaders"; + + public static final String AUTO_COPY_TO_CLIPBOARD_PROPERTY_NAME = "autoCopyToClipboard"; + + public static final String VARIABLES_PROPERTY_NAME = "variables"; + + public static final String VALID_PROPERTY_NAME = "valid"; + + public static final Pattern REPORT_DEFINITION_PATTERN = Pattern.compile("report.(\\w+).name"); + + /** Logger. */ + private static final Log log = LogFactory.getLog(ReportModel.class); + + /** la fichier contenant la définition des reports. */ + protected File reportFile; + + /** la liste des reports connus. */ + protected List<Report> reports; + + /** le report actuellement sélectionné. */ + protected Report selectedReport; + + /** les variables utilisées pour le report. */ + protected final Map<String, Object> variables; + + /** le résultat du report actuellement sélectionné */ + protected ResultTableModel resultModel; + + /** + * Un drapeau pour automatiquement copier dans le presse papier le + * tableau des résultats. + */ + protected boolean autoCopyToClipboard; + + /** Un drapeau pour savoir si la requete est executable. */ + protected Boolean valid; + + /** Pour copier les entêtes de lignes */ + protected boolean copyRowHeaders = true; + + /** Pour copier les entêtes de colonnes */ + protected boolean copyColumnHeaders = true; + + public ReportModel() { + super(AdminStep.REPORT); + variables = new TreeMap<>(); + } + + public List<Report> loadReports(URL resource) throws IOException { + + ReportBuilder builder = new ReportBuilder(); + try { + + List<Report> result = builder.load(resource); + return result; + } finally { + builder.clear(); + } + } + + public File getReportFile() { + return reportFile; + } + + public void setReportFile(File reportFile) { + Object old = this.reportFile; + this.reportFile = reportFile; + firePropertyChange(REPORT_FILE_PROPERTY_NAME, old, reportFile); + reports = null; + getReports(); + } + + public boolean isAutoCopyToClipboard() { + return autoCopyToClipboard; + } + + public void setAutoCopyToClipboard(boolean autoCopyToClipboard) { + boolean oldValue = this.autoCopyToClipboard; + this.autoCopyToClipboard = autoCopyToClipboard; + firePropertyChange(AUTO_COPY_TO_CLIPBOARD_PROPERTY_NAME, + oldValue, + autoCopyToClipboard + ); + } + + public boolean isCopyRowHeaders() { + return copyRowHeaders; + } + + public void setCopyRowHeaders(boolean copyRowHeaders) { + boolean oldValue = this.copyRowHeaders; + this.copyRowHeaders = copyRowHeaders; + firePropertyChange(COPY_ROW_HEADERS_PROPERTY_NAME, + oldValue, + copyRowHeaders + ); + } + + public boolean isCopyColumnHeaders() { + return copyColumnHeaders; + } + + public void setCopyColumnHeaders(boolean copyColumnHeaders) { + boolean oldValue = this.copyColumnHeaders; + this.copyColumnHeaders = copyColumnHeaders; + firePropertyChange(COPY_COLUMN_HEADERS_PROPERTY_NAME, + oldValue, + copyColumnHeaders + ); + } + + public ResultTableModel getResultModel() { + if (resultModel == null) { + resultModel = new ResultTableModel(); + } + return resultModel; + } + + public boolean isInit() { + return reports != null; + } + + public List<Report> getReports() { + if (reports == null && reportFile.exists()) { + + + try { + URL resource = reportFile.toURI().toURL(); + List<Report> reports = loadReports(resource); + if (log.isDebugEnabled()) { + log.debug("Add loaded " + reports.size() + " report(s)."); + } + setReports(reports); + } catch (IOException e) { + throw new IllegalStateException( + "Could not load reports definition file (" + reportFile + ").", e); + } + } + return reports; + } + + public void setReports(List<Report> reports) { + this.reports = reports; + firePropertyChange(REPORTS_PROPERTY_NAME, reports); + } + + public Report getSelectedReport() { + return selectedReport; + } + + public void setSelectedReport(Report selectedReport) { + + // suppression des variables + variables.clear(); + + // invalidation du modèle (sans déclanchement d'évènement) + valid = null; + + // changement de report + Object old = this.selectedReport; + this.selectedReport = selectedReport; + firePropertyChange(SELECTED_REPORT_PROPERTY_NAME, old, selectedReport); + } + + public Map<String, Object> getVariables() { + return variables; + } + + public boolean isValid() { + return valid != null && valid; + } + + public void setValid(boolean valid) { + Boolean old = this.valid; + this.valid = valid; + firePropertyChange(VALID_PROPERTY_NAME, old, valid); + } + + public void addVariable(String name, Object value) { + variables.put(name, value); + + // invalidation du modèle (sans déclanchement d'évènement) + valid = null; + + firePropertyChange(VARIABLES_PROPERTY_NAME, null, variables); + } + + public void resetVariables() { + variables.clear(); + firePropertyChange(VARIABLES_PROPERTY_NAME, null, variables); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/report/ReportUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/report/ReportUI.jaxx new file mode 100644 index 0000000..cc4f5c2 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/report/ReportUI.jaxx @@ -0,0 +1,122 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<!-- ********************************************** --> +<!-- L'écran d'import GPS --> +<!-- ********************************************** --> + +<fr.ird.observe.application.swing.ui.admin.AdminTabUI> + <import> + fr.ird.observe.application.swing.ui.UIHelper + fr.ird.observe.application.swing.ui.admin.AdminStep + fr.ird.observe.application.swing.ui.admin.AdminTabUI + fr.ird.observe.application.swing.ui.admin.AdminUI + fr.ird.observe.services.dto.actions.report.Report + + java.awt.Dimension + + javax.swing.DefaultComboBoxModel + javax.swing.JComboBox + </import> + + <ReportUIHandler id='handler' constructorParams='this'/> + + <ReportModel id='stepModel' javaBean='getModel().getReportModel()'/> + + <ResultTableModel id='resultModel' + javaBean='getStepModel().getResultModel()'/> + + <script><![CDATA[ +public ReportUI(AdminUI parentContext) { + super(AdminStep.REPORT, parentContext); +} + +@Override +public void initUI(AdminUI ui) { + getHandler().initTabUI(ui, this); +} + +public void destroy() { + getHandler().destroy(); +} +]]> + </script> + + <JPanel id='PENDING_content'> + + <!-- le paneau du haut qui contient le sélecteur et les actions --> + <JPanel id='northPanel' constraints='BorderLayout.NORTH'> + + <JPanel id='requestSelectorPane' constraints='BorderLayout.NORTH'> + + <JToolBar id='toolbar' constraints='BorderLayout.WEST'> + + <!-- suppression de la sélection du report --> + <JButton id="resetSelectedReport" + onActionPerformed="getHandler().updateSelectedReport(null)"/> + + </JToolBar> + + <!-- selecteur de report --> + <JComboBox id='reportSelector' constraints='BorderLayout.CENTER' + onItemStateChanged='getHandler().updateSelectedReportFromEvent(event)'/> + <!--onItemStateChanged='if (event.getStateChange() == ItemEvent.SELECTED) getHandler().updateSelectedReport((Report) ((JComboBox)event.getSource()).getSelectedItem());'/>--> + + <JScrollPane id='reportDescriptionPane' + constraints='BorderLayout.SOUTH'> + <JTextArea id='reportDescription'/> + </JScrollPane> + + </JPanel> + + <!-- selecteur de variables --> + <JScrollPane id='reportVariableSelectorPane' + constraints='BorderLayout.CENTER'> + <JPanel id='reportVariableSelectorPanel'> + </JPanel> + </JScrollPane> + </JPanel> + + <!-- le tableau des résultats --> + <JScrollPane id='resultPane' constraints='BorderLayout.CENTER'> + <JTable id='resultTable'/> + </JScrollPane> + + <JPanel id="copyPane" constraints='BorderLayout.SOUTH'> + <JPanel id='copyOptions' constraints='BorderLayout.NORTH'> + <JCheckBox id='autoCopyToClipboard' + onStateChanged='getStepModel().setAutoCopyToClipboard(((JCheckBox)event.getSource()).isSelected())'/> + <JCheckBox id='copyRowHeaders' + onStateChanged='getStepModel().setCopyRowHeaders(((JCheckBox)event.getSource()).isSelected())'/> + <JCheckBox id='copyColumnHeaders' + onStateChanged='getStepModel().setCopyColumnHeaders(((JCheckBox)event.getSource()).isSelected())'/> + </JPanel> + <JButton id="copy" constraints='BorderLayout.CENTER' + onActionPerformed='getHandler().copyReportToClipBoard(getStepModel().getSelectedReport(), getResultModel(), getStepModel().isCopyRowHeaders(), + getStepModel().isCopyColumnHeaders())'/> + + </JPanel> + + </JPanel> + + +</fr.ird.observe.application.swing.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/report/ReportUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/report/ReportUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/admin/report/ReportUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/report/ReportUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/report/ReportUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/report/ReportUIHandler.java new file mode 100644 index 0000000..6e90def --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/report/ReportUIHandler.java @@ -0,0 +1,504 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin.report; + +import com.google.common.collect.Lists; +import fr.ird.observe.application.swing.ObserveSwingTechnicalException; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.DataDto; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.actions.report.DataMatrix; +import fr.ird.observe.services.dto.actions.report.Report; +import fr.ird.observe.services.dto.actions.report.ReportVariable; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.service.actions.report.ReportService; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.admin.AdminStep; +import fr.ird.observe.application.swing.ui.admin.AdminTabUI; +import fr.ird.observe.application.swing.ui.admin.AdminTabUIHandler; +import fr.ird.observe.application.swing.ui.admin.AdminUI; +import fr.ird.observe.application.swing.ui.admin.AdminUIModel; +import fr.ird.observe.application.swing.ui.admin.config.ConfigUI; +import fr.ird.observe.application.swing.ui.admin.config.SelectDataUI; +import fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel; +import jaxx.runtime.context.JAXXInitialContext; +import jaxx.runtime.swing.editor.bean.BeanComboBox; +import jaxx.runtime.swing.wizard.ext.WizardState; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.decorator.Decorator; +import org.nuiton.decorator.JXPathDecorator; +import org.nuiton.util.TimeLog; + +import javax.swing.DefaultListCellRenderer; +import javax.swing.JComboBox; +import javax.swing.JList; +import javax.swing.JPanel; +import javax.swing.JTable; +import javax.swing.SwingUtilities; +import javax.swing.table.DefaultTableCellRenderer; +import java.awt.Component; +import java.awt.Font; +import java.awt.event.ItemEvent; +import java.io.File; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import static org.nuiton.i18n.I18n.t; + +/** + * Le controleur des onglets. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ReportUIHandler extends AdminTabUIHandler { + + public static final String VARIABLE_NAME = "variableName"; + + /** Logger */ + private static final Log log = LogFactory.getLog(ReportUIHandler.class); + + private static final TimeLog timeLog = new TimeLog(ReportUIHandler.class, 0, 1000); + + private final Runnable revalidateTabUI; + + public ReportUIHandler(AdminTabUI ui) { + super(ui); + revalidateTabUI = () -> getUi().revalidate(); + } + + public void initTabUI(AdminUI ui, final ReportUI tabUI) { + + super.initTabUI(ui, tabUI); + + if (log.isDebugEnabled()) { + log.debug(" specialized for [" + tabUI.getStep() + + "] for main ui " + ui.getClass().getName() + + "@" + System.identityHashCode(ui)); + } + + UIHelper.setLayerUI(tabUI.getContent(), ui.getConfigBlockLayerUI()); + + ReportModel stepModel = getStepModel(); + stepModel.addPropertyChangeListener(evt -> { + + if (getModel().getModelState() == WizardState.CANCELED) { + + // action annulée, on ne declanche plus rien + return; + } + String propertyName = evt.getPropertyName(); + Object newValue = evt.getNewValue(); + + ReportModel source = (ReportModel) evt.getSource(); + + if (ReportModel.REPORTS_PROPERTY_NAME.equals(propertyName)) { + List<?> reports = (List<?>) newValue; + onReportsChanged(tabUI, reports); + } else if (ReportModel.SELECTED_REPORT_PROPERTY_NAME.equals(propertyName)) { + Report report = (Report) newValue; + onSelectedReportChanged(tabUI, source, report); + } else if (ReportModel.VARIABLES_PROPERTY_NAME.equals(propertyName)) { + Map<String, Object> variables = (Map<String, Object>) newValue; + onVariablesChanges(source, variables); + } else if (ReportModel.VALID_PROPERTY_NAME.equals(propertyName)) { + final Boolean valid = (Boolean) newValue; + SwingUtilities.invokeLater(() -> onValidChanged(source, valid != null && valid)); + + + } + }); + + tabUI.getReportSelector().setRenderer(new DefaultListCellRenderer() { + private static final long serialVersionUID = 1L; + + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + if (value == null) { + + // on affiche une message de sélection de report + value = t("observe.message.select.report"); + } + return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + } + } + + ); + // ajout du renderer sur le tableau + + DefaultTableCellRenderer renderer = new DefaultTableCellRenderer() { + private static final long serialVersionUID = 1L; + Font defaultFont; + + Font headerFont; + + public Font getDefaultFont(JTable table) { + if (defaultFont == null) { + defaultFont = table.getFont(); + } + return defaultFont; + } + + public Font getHeaderFont(JTable table) { + if (headerFont == null) { + headerFont = getDefaultFont(table).deriveFont(Font.BOLD); + } + return headerFont; + } + + @Override + public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + Font font; + if (row == 0 || column == 0) { + + // on est sur une bordure + font = getHeaderFont(table); + } else { + font = getDefaultFont(table); + } + Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); + comp.setFont(font); + return comp; + } + }; + tabUI.getResultTable().setDefaultRenderer(Object.class, renderer); + tabUI.getResultTable().setDefaultRenderer(String.class, renderer); + + // initialisation de l'ui de configuration + if (log.isInfoEnabled()) { + log.info("Init extra configuration for " + tabUI.getName()); + } + + ConfigUI configUI = (ConfigUI) ui.getStepUI(AdminStep.CONFIG); + JAXXInitialContext tx = new JAXXInitialContext().add(configUI).add(this); + + ReportConfigUI extraConfig = new ReportConfigUI(tx); + + configUI.getExtraConfig().add(extraConfig); + + final SelectDataUI selectTabUI = (SelectDataUI) ui.getStepUI(AdminStep.SELECT_DATA); + ui.getModel().addPropertyChangeListener(AdminUIModel.SELECTION_MODEL_CHANGED_PROPERTY_NAME, evt -> { + AdminUIModel model1 = (AdminUIModel) evt.getSource(); + if (!model1.containsStep(selectTabUI.getStep())) { + + // avoid multi-cast + return; + } + + DataSelectionModel value = (DataSelectionModel) evt.getNewValue(); + if (log.isDebugEnabled()) { + log.debug("selection model changed to " + value.getDatas()); + log.debug("IS USE DATA ? : " + value.isUseData()); + } + updateSelectionModel(selectTabUI); + }); + } + + public void updateSelectedReportFromEvent(ItemEvent event) { + + if (event.getStateChange() == ItemEvent.SELECTED) { + if (log.isInfoEnabled()) { + log.info("Item selected!"); + } + JComboBox<Report> source = (JComboBox<Report>) event.getSource(); + updateSelectedReport((Report) source.getSelectedItem()); + } else if (getStepModel().getSelectedReport() != null) { + + Object item = event.getItem(); + if (log.isInfoEnabled()) { + log.info("Item not selected: " + item); + } + updateSelectedReport(null); + } + } + + public void updateSelectedReport(Report report) { + getModel().setBusy(true); + try { + if (log.isInfoEnabled()) { + log.info("New selected report : " + report); + } + getStepModel().setSelectedReport(report); + + } finally { + getModel().setBusy(false); + } + } + + public String updateSelectedReportDescrption(Report report) { + if (report == null) { + return t("observe.message.no.report.selected"); + } + return t(report.getDescription()); + } + + public void updateVariable(JComboBox combo, Object value) { + String variableName = (String) combo.getClientProperty(VARIABLE_NAME); + if (variableName == null) { + throw new IllegalStateException( + "No 'variableName' clientProperty on " + combo); + } + if (log.isInfoEnabled()) { + log.info("Set variable [" + variableName + "] to value " + value); + } + getStepModel().addVariable(variableName, value); + } + + public void chooseReportFile() { + ReportModel model = getModel().getReportModel(); + File f = UIHelper.chooseFile( + ui, + t("observe.title.choose.reportFile"), + t("observe.action.choose.reportFile"), + model.getReportFile(), + "^.+\\.properties$", + t("observe.action.choose.reportFile.description")); + model.setReportFile(f); + } + + public void copyReportToClipBoard(Report report, + ResultTableModel model, + boolean copyRowHeaders, + boolean copyColumnHeaders) { + if (report == null) { + + // pas de report sélectionné, rien à faire + return; + } + + if (log.isDebugEnabled()) { + log.debug("Will copy result of report " + report.getName()); + log.debug("Result dimension : [" + model.getRowCount() + "," + + model.getColumnCount() + "]"); + } + String content = model.getClipbordContent(copyRowHeaders, copyColumnHeaders); + UIHelper.copyToClipBoard(content); + } + + protected void onReportsChanged(ReportUI tabUI, List<?> newValue) { + + if (log.isDebugEnabled()) { + log.debug("New reports : " + newValue); + } + + // on ajoute toujours une premiere valeur null (pour ne rien selectionne) + newValue.add(0, null); + + // on charge le nouveau modèle dans la liste déroulante + UIHelper.fillComboBox(tabUI.getReportSelector(), newValue, null); + } + + @SuppressWarnings({"unchecked"}) + protected void onSelectedReportChanged(ReportUI tabUI, + ReportModel model, + Report report) { + + if (log.isInfoEnabled()) { + log.info("New selected report [" + report + "]"); + } + + getModel().setBusy(true); + + try { + // on regénère l'ui de configuration des variables + JPanel variablesPanel = tabUI.getReportVariableSelectorPanel(); + variablesPanel.removeAll(); + + // on utilise les variables uniquement si nécessaire + boolean useVariables = report != null && report.isVariableRequired(); + tabUI.getReportVariableSelectorPane().setVisible(useVariables); + + // calcul des données et contruction du tableau + model.getResultModel().clear(); + + if (report != null) { + + try { + + ObserveSwingDataSource dataSource = getModel().getSafeLocalSource(true); + + ReportService reportService = dataSource.newReportService(); + + report = reportService.populateVariables(report, getModel().getSelectedTrip().getId()); + + } catch (Exception e) { + throw new ObserveSwingTechnicalException("unable to populate report : " + report.getName(), e); + } + + if (useVariables) { + + // on construit les ui pour chaqsue variable + for (ReportVariable variable : report.getVariables()) { + String variableName = variable.getName(); + // String value = variables.get(variableName); + Set values = variable.getValues(); + List<Object> universe = Lists.newArrayList(values); + BeanComboBox<Object> combo = new BeanComboBox<>(); + + combo.setShowReset(true); + variablesPanel.add(combo); + Decorator decorator; + if (ReferentialDto.class.isAssignableFrom(variable.getType()) && !universe.isEmpty()) { + decorator = getDecoratorService().getReferentialReferenceDecorator(variable.getType()); + } else if (DataDto.class.isAssignableFrom(variable.getType()) && !universe.isEmpty()) { + decorator = getDecoratorService().getDataReferenceDecorator(variable.getType()); + } else { + decorator = getDecoratorService().getDecoratorByType(variable.getType()); + } + combo.init((JXPathDecorator<Object>) decorator, universe); + JComboBox jComboBox = combo.getCombobox(); + jComboBox.putClientProperty(VARIABLE_NAME, variableName); + jComboBox.addItemListener(e -> { + + JComboBox comboBox = (JComboBox) e.getSource(); + + if (e.getStateChange() == ItemEvent.DESELECTED) { + + // ne rien faire de l'évènement de déselection + // sauf si le modèle devient vide + + if (comboBox.getSelectedItem() == null) { + updateVariable(comboBox, null); + } + return; + } + + Object o = e.getItem(); + updateVariable(comboBox, o); + }); + } + } + + // on revalide la disposition de l'onglet + SwingUtilities.invokeLater(revalidateTabUI); + + Map<String, Object> variables = model.getVariables(); + updateValidState(report, variables); + } + } finally { + + getModel().setBusy(false); + + } + } + + protected void onVariablesChanges(ReportModel model, Map<String, Object> variables) { + + Report report = model.getSelectedReport(); + if (report != null) { + + updateValidState(report, variables); + } + } + + protected void onValidChanged(ReportModel model, boolean valid) { + + if (log.isInfoEnabled()) { + log.info("valid state changed to " + valid); + } + + if (!valid) { + // calcul des données et contruction du tableau + model.getResultModel().clear(); + return; + } + + getModel().setBusy(true); + + try { + + Report report = model.getSelectedReport(); + + DataReference trip = getModel().getSelectedTrip(); + + if (log.isDebugEnabled()) { + log.debug("Build result for report [" + report.getName() + "] on " + trip); + } + + Map<String, Object> variables = model.getVariables(); + + for (ReportVariable variable : report.getVariables()) { + Object value = variables.get(variable.getName()); + variable.setSelectedValue(value); + } + + long startTime = TimeLog.getTime(); + + ObserveSwingDataSource dataSource = getModel().getSafeLocalSource(true); + if (!dataSource.isOpen()) { + dataSource.open(); + } + + ReportService reportService = dataSource.newReportService(); + + DataMatrix data = reportService.executeReport(report, trip.getId()); + + timeLog.log(startTime, "execute", report.getName()); + + if (log.isInfoEnabled()) { + log.info("Result to dispaly:\n" + data.getClipbordContent(true, true)); + } + + // calcul des données et contruction du tableau + model.getResultModel().populate(report, data); + + // mise a jour du clipboard automatique si requis + if (model.isAutoCopyToClipboard()) { + copyReportToClipBoard(report, + model.getResultModel(), + model.isCopyRowHeaders(), + model.isCopyColumnHeaders()); + } + + } catch (Exception e) { + + UIHelper.handlingError("Could not obtain report data", e); + + model.getResultModel().clear(); + + } finally { + + getModel().setBusy(false); + + } + } + + protected ReportModel getStepModel() { + return model.getReportModel(); + } + + protected void updateValidState(Report report, Map<String, Object> variables) { + + boolean canExecute = report != null && report.canExecute(variables); + getStepModel().setValid(canExecute); + } + + public void destroy() { + ObserveSwingDataSource dataSource = model.getSafeLocalSource(false); + + if (dataSource.isOpen()) { + dataSource.close(); + } + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/report/ResultTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/report/ResultTableModel.java new file mode 100644 index 0000000..6f257a4 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/report/ResultTableModel.java @@ -0,0 +1,199 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin.report; + +import fr.ird.observe.services.dto.actions.report.DataMatrix; +import fr.ird.observe.services.dto.actions.report.Report; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.table.AbstractTableModel; +import java.io.Serializable; + +/** + * Le modèle de tableau de résultats d'un report. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ResultTableModel extends AbstractTableModel { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(ResultTableModel.class); + + /** les données du tableaux. */ + protected transient DataMatrix data; + + public void populate(Report report, DataMatrix data) { + + if (report == null) { + + // suppression du report + clear(); + return; + } + + if (log.isInfoEnabled()) { + log.info("from report : " + report); + } + + DataMatrix allData = new DataMatrix(); + + DataMatrix rowData = null; + DataMatrix columnData = null; + int nbRows = data.getHeight(); + int nbCols = data.getWidth(); + + String[] columnNames = report.getColumnHeaders(); + String[] rowNames = report.getRowHeaders(); + + boolean withColumnHeader = columnNames != null && columnNames.length > 0; + boolean withRowHeader = rowNames != null && rowNames.length > 0; + + if (withColumnHeader) { + + // on ajoute une première ligne aux données + + nbRows += 1; + nbCols = columnNames.length; + + // les données commencent à la ligne 1 + data.setY(1); + rowData = new DataMatrix(); + rowData.setWidth(nbCols); + rowData.setHeight(1); + rowData.createData(); + for (int i = 0; i < nbCols; i++) { + String columnName = columnNames[i]; + rowData.setValue(i, 0, columnName); + } + if (withRowHeader) { + rowData.setX(1); + } + } + + if (withRowHeader) { + + // on ajoute une première colonne aux données + nbCols += 1; + nbRows = rowNames.length; + + // les données commencent à la colonne 1 + data.setX(1); + + // la matrice colonne 0 + columnData = new DataMatrix(); + columnData.setWidth(1); + columnData.setHeight(nbRows); + + columnData.createData(); + for (int i = 0; i < nbRows; i++) { + String rowName = rowNames[i]; + columnData.setValue(0, i, rowName); + } + if (withColumnHeader) { + columnData.setY(1); + nbRows += 1; + } + } + + allData.setHeight(nbRows); + allData.setWidth(nbCols); + + if (log.isInfoEnabled()) { + log.info("final data dimension : " + + allData.getDimension() + " vs " + + data.getDimension() + ); + } + + // creation de la matrice finale + allData.createData(); + + if (withRowHeader) { + + // ajout de la colonne 0 + allData.copyData(columnData); + } + + if (withColumnHeader) { + + // ajout de la ligne 0 + allData.copyData(rowData); + } + + // ajout des données réelles + allData.copyData(data); + this.data = allData; + fireTableStructureChanged(); + } + + public void clear() { + data = null; + fireTableStructureChanged(); + } + + @Override + protected void finalize() throws Throwable { + super.finalize(); + clear(); + } + + @Override + public int getRowCount() { + return data == null ? 0 : data.getHeight(); + } + + @Override + public int getColumnCount() { + return data == null ? 0 : data.getWidth(); + } + + @Override + public String getColumnName(int columnIndex) { + + // on utilise pas les colonnes du modèle de tableau (on utilise + // directement les données du tableaux que l'on va distinguer en gras) + return null; + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + Serializable data = this.data == null ? null : this.data.getValue(columnIndex, rowIndex); + return data; + } + + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + // les données du tableau n'est pas modifiable + } + + public String getClipbordContent(boolean copyRowHeaders, + boolean copyColumnHeaders) { + + return data == null ? "" : data.getClipbordContent(copyRowHeaders, + copyColumnHeaders + ); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/resume/ShowResumeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/resume/ShowResumeUI.jaxx new file mode 100644 index 0000000..fd29bb5 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/resume/ShowResumeUI.jaxx @@ -0,0 +1,94 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<!-- **************************************** --> +<!-- L'écran de résumé des opérations passées --> +<!-- **************************************** --> + +<fr.ird.observe.application.swing.ui.admin.AdminTabUI> + + <import> + fr.ird.observe.application.swing.ui.UIHelper + fr.ird.observe.application.swing.ui.admin.AdminUI + fr.ird.observe.application.swing.ui.admin.AdminStep + fr.ird.observe.application.swing.ui.admin.AdminTabUI + + java.awt.Dimension + </import> + + <ShowResumeUIHandler id='handler' constructorParams='this'/> + + <fr.ird.observe.application.swing.ui.admin.AdminActionModel id='stepModel' initializer='null'/> + + <script><![CDATA[ +public ShowResumeUI(AdminUI parentContext) { + super(AdminStep.SHOW_RESUME, parentContext); +} + +@Override +public void initUI(AdminUI ui) { + getHandler().initTabUI(ui, this); +} + +@Override +public void destroy() { + super.destroy(); + globalProgression.setText(""); + resume.setText(""); +} + +@Override +public void addMessage(AdminStep step, String text) { + getHandler().addMessage(step, text); +} +]]> + </script> + + <JPanel id='PENDING_content'> + <Table constraints='BorderLayout.CENTER' fill='both' weightx='1' + weighty='1'> + <row> + <cell> + <JScrollPane id='resumePane'> + <JTextArea id='resume'/> + </JScrollPane> + </cell> + </row> + <row> + <cell> + <JScrollPane id='globalProgressionPane' + columnHeaderView='{globalProgressionTop}'> + <JTextArea id='globalProgression'/> + <JToolBar id='globalProgressionTop'> + <JLabel id='globalProgressionTopLabel'/> + <javax.swing.Box.Filler + constructorParams='UIHelper.newMinDimension(), UIHelper.newMinDimension(), UIHelper.newMaxXDimension()'/> + <JButton id="globalProgressionCopyToClipBoard" + onActionPerformed='UIHelper.copyToClipBoard(globalProgression.getText())'/> + </JToolBar> + </JScrollPane> + </cell> + </row> + </Table> + </JPanel> + +</fr.ird.observe.application.swing.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/resume/ShowResumeUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/resume/ShowResumeUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/admin/resume/ShowResumeUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/resume/ShowResumeUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/resume/ShowResumeUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/resume/ShowResumeUIHandler.java new file mode 100644 index 0000000..64abb56 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/resume/ShowResumeUIHandler.java @@ -0,0 +1,108 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin.resume; + +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.admin.AdminStep; +import fr.ird.observe.application.swing.ui.admin.AdminTabUIHandler; +import fr.ird.observe.application.swing.ui.admin.AdminUI; +import jaxx.runtime.swing.wizard.ext.WizardState; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import static org.nuiton.i18n.I18n.t; + +/** + * Le controleur des onglets. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ShowResumeUIHandler extends AdminTabUIHandler { + + /** Logger */ + private static final Log log = LogFactory.getLog(ShowResumeUIHandler.class); + + public ShowResumeUIHandler(ShowResumeUI ui) { + super(ui); + } + + @Override + public ShowResumeUI getUi() { + return (ShowResumeUI) super.getUi(); + } + + public void initTabUI(AdminUI ui, ShowResumeUI tabUI) { + + super.initTabUI(ui, tabUI); + + if (log.isDebugEnabled()) { + log.debug(" specialized for [" + tabUI.getStep() + "] for main ui " + ui.getClass().getName() + "@" + System.identityHashCode(ui)); + } + + UIHelper.setLayerUI(tabUI.getContent(), null); + } + + + public void updateText() { + StringBuilder buffer = new StringBuilder(); + if (!model.isWasStarted()) { + buffer.append(t("observe.admin.resume.no.operation.done")); + } else { + for (AdminStep s : model.getOperations()) { + WizardState state = model.getStepState(s); + String stateStr = ""; + switch (state) { + case CANCELED: + stateStr = t("observe.admin.resume.operation.canceled"); + break; + case FAILED: + stateStr = t("observe.admin.resume.operation.failed"); + break; + case NEED_FIX: + stateStr = t("observe.admin.resume.operation.need.fix"); + break; + case PENDING: + stateStr = t("observe.admin.resume.operation.not.started"); + break; + case RUNNING: + stateStr = t("observe.admin.resume.operation.running"); + break; + case SUCCESSED: + stateStr = t("observe.admin.resume.operation.done"); + break; + } + buffer.append("\n\n"); + buffer.append(t(s.getLabel())); + buffer.append(" : "); + buffer.append(stateStr); + buffer.append("."); + } + buffer.append("\n\n"); + } + getUi().getResume().setText(buffer.toString()); + } + + public void addMessage(AdminStep step, String text) { + getUi().getGlobalProgression().append(t(step.getLabel()) + " - " + text + "\n"); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/save/SaveLocalModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/save/SaveLocalModel.java new file mode 100644 index 0000000..df42194 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/save/SaveLocalModel.java @@ -0,0 +1,140 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin.save; + +import fr.ird.observe.application.swing.ui.admin.AdminActionModel; +import fr.ird.observe.application.swing.ui.admin.AdminStep; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.File; +import java.util.HashSet; +import java.util.Set; + +/** + * Le modèle d'une opération d'export de données observers. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class SaveLocalModel extends AdminActionModel { + + public static final String BACKUP_FILE_PROPERTY_NAME = "backupFile"; + + public static final String DO_BACKUP_PROPERTY_NAME = "doBackup"; + + public static final String CAN_SAVE_LOCAL_PROPERTY_NAME = "canSaveLocal"; + + public static final String LOCAL_SOURCE_NEED_SAVE_PROPERTY_NAME = "localSourceNeedSave"; + + /** Logger */ + private static final Log log = LogFactory.getLog(SaveLocalModel.class); + + /** le fichier de sauvegarde de la base locale */ + protected File backupFile = new File(""); + + /** + * un drapeau pour savoir si on doit effectuer une sauvegarde de la base + * locale + */ + protected boolean doBackup; + + /** un drapeau pour savoir si la source locale doit être sauvée */ + protected boolean localSourceNeedSave; + + /** la liste des etapes qui ont demande une sauvegarde */ + protected Set<AdminStep> stepsForSave; + + public SaveLocalModel() { + super(AdminStep.SAVE_LOCAL); + } + + public boolean isLocalSourceNeedSave() { + return localSourceNeedSave; + } + + public void setLocalSourceNeedSave(boolean localSourceNeedSave) { + this.localSourceNeedSave = localSourceNeedSave; + firePropertyChange(LOCAL_SOURCE_NEED_SAVE_PROPERTY_NAME, null, + localSourceNeedSave); + } + + public boolean isDoBackup() { + return doBackup; + } + + public void setDoBackup(boolean doBackup) { + boolean canSave = isCanSaveLocal(); + boolean oldValue = this.doBackup; + this.doBackup = doBackup; + firePropertyChange(DO_BACKUP_PROPERTY_NAME, oldValue, doBackup); + firePropertyChange(CAN_SAVE_LOCAL_PROPERTY_NAME, canSave, isCanSaveLocal()); + } + + public File getBackupFile() { + return backupFile; + } + + public void setBackupFile(File backupFile) { + boolean canSave = isCanSaveLocal(); + File oldValue = this.backupFile; + this.backupFile = backupFile; + firePropertyChange(BACKUP_FILE_PROPERTY_NAME, oldValue, backupFile); + firePropertyChange(CAN_SAVE_LOCAL_PROPERTY_NAME, canSave, isCanSaveLocal()); + } + + public Set<AdminStep> getStepsForSave() { + if (stepsForSave == null) { + stepsForSave = new HashSet<>(); + } + return stepsForSave; + } + + public boolean containsStepForsave(AdminStep step) { + return stepsForSave != null && stepsForSave.contains(step); + } + + /** + * @return {@code true} si l'on peut reporter les modifications vers la base + * locale. + */ + public boolean isCanSaveLocal() { + boolean validate = !doBackup || + backupFile != null && + !backupFile.exists() && + backupFile.getName().endsWith(".sql.gz") && + backupFile.getParentFile().exists(); + + if (log.isDebugEnabled()) { + log.debug("can save ? " + validate); + } + return validate; + } + + public void addStepForSave(AdminStep step) { + getStepsForSave().add(step); + + // la sauvegarde est obligatoire + setLocalSourceNeedSave(true); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/save/SaveLocalUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/save/SaveLocalUI.jaxx new file mode 100644 index 0000000..9931a68 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/save/SaveLocalUI.jaxx @@ -0,0 +1,122 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<!-- ****************************************************************** --> +<!-- L'écran pour sauevegarder la base locale depuis la base de syncho --> +<!-- ****************************************************************** --> + +<fr.ird.observe.application.swing.ui.admin.AdminTabUI> + + <import> + fr.ird.observe.application.swing.ui.admin.AdminStep + fr.ird.observe.application.swing.ui.admin.AdminUI + + jaxx.runtime.swing.CardLayout2Ext + + java.awt.Color + java.io.File + </import> + + <SaveLocalUIHandler id='handler' constructorParams='this'/> + + <SaveLocalModel id='stepModel' initializer='getModel().getSaveLocalModel()'/> + + <CardLayout2Ext id='pendingLayout' + constructorParams='this, "PENDING_content_panel"'/> + + <script><![CDATA[ +public SaveLocalUI(AdminUI parentContext) { + super(AdminStep.SAVE_LOCAL, parentContext); +} + +@Override +public void initUI(AdminUI ui) { + getHandler().initTabUI(ui, this); +} +]]> + </script> + + <JPanel id='PENDING_content'> + <Table constraints='BorderLayout.CENTER' fill='both'> + <row> + <cell fill='both'> + <JPanel background='{Color.WHITE}'> + <JLabel id="PENDING_content_label"/> + </JPanel> + </cell> + </row> + <row> + <cell fill='both' weighty='1' weightx='1'> + + <JPanel id='PENDING_content_panel'> + <JButton id="continueAction" constraints='"no"' + onActionPerformed='getHandler().skipOperation()'/> + + <JPanel layout='{new BorderLayout()}' constraints='"do"'> + + <JLabel id='needSaveText' constraints='BorderLayout.CENTER'/> + + <Table fill='both' constraints='BorderLayout.SOUTH'> + <row> + <cell columns='3'> + <JCheckBox id='doBackup' + onStateChanged='getStepModel().setDoBackup(((JCheckBox)event.getSource()).isSelected())'/> + </cell> + </row> + <row> + <cell> + <JLabel id="directoryLabel"/> + </cell> + <cell weightx='1' fill="horizontal"> + <JTextField id='directoryText' + onKeyReleased='getHandler().changeDirectory(new File(((JTextField)event.getSource()).getText()))'/> + </cell> + <cell anchor="east"> + <JButton id="backupFileChooseAction" + onActionPerformed="getHandler().chooseBackupFile()"/> + </cell> + </row> + <row> + <cell> + <JLabel id="fileLabel"/> + </cell> + <cell weightx='1' fill="horizontal" columns="2"> + <JTextField id='filenameText' + onKeyReleased='getHandler().changeFilename(((JTextField)event.getSource()).getText())'/> + </cell> + </row> + <row> + <cell fill='both' columns="3"> + <JButton id="startAction" + onActionPerformed="getHandler().doStartAction()"/> + </cell> + </row> + </Table> + </JPanel> + </JPanel> + + </cell> + </row> + </Table> + </JPanel> + +</fr.ird.observe.application.swing.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/save/SaveLocalUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/save/SaveLocalUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/admin/save/SaveLocalUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/save/SaveLocalUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/save/SaveLocalUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/save/SaveLocalUIHandler.java new file mode 100644 index 0000000..943c263 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/save/SaveLocalUIHandler.java @@ -0,0 +1,193 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin.save; + +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.service.AddSqlScriptProducerRequest; +import fr.ird.observe.services.service.SqlScriptProducerService; +import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeContext; +import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeEngine; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.admin.AdminStep; +import fr.ird.observe.application.swing.ui.admin.AdminTabUIHandler; +import fr.ird.observe.application.swing.ui.admin.AdminUI; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.legacy.SynchronizeModel; +import jaxx.runtime.swing.wizard.ext.WizardState; +import org.apache.commons.io.IOUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.io.File; +import java.io.FileOutputStream; +import java.util.Date; + +import static org.nuiton.i18n.I18n.t; + +/** + * Le controleur des onglets. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class SaveLocalUIHandler extends AdminTabUIHandler { + + /** Logger */ + private static final Log log = LogFactory.getLog(SaveLocalUIHandler.class); + + private static final String UPDATE_VERSION_PATTERN = + "UPDATE %1$s SET topiaversion = %2$d WHERE topiaid='%3$s';\n"; + + protected ObserveSwingDataSource source; + + public SaveLocalUIHandler(SaveLocalUI ui) { + super(ui); + } + + @Override + public SaveLocalUI getUi() { + return (SaveLocalUI) super.getUi(); + } + + public void initTabUI(AdminUI ui, SaveLocalUI tabUI) { + + super.initTabUI(ui, tabUI); + + if (log.isDebugEnabled()) { + log.debug(" specialized for [" + tabUI.getStep() + "] for main ui " + ui.getClass().getName() + "@" + System.identityHashCode(ui)); + } + + String message = t("observe.actions.synchro.launch.operation", t(tabUI.getStep().getOperationLabel())); + tabUI.getStartAction().setText(message); + + } + + public void updateText() { + String text = ""; + if (getUi().getStepModel().containsStepForsave(AdminStep.SYNCHRONIZE)) { + text = t("observe.actions.synchro.referential.message.need.save.for.synchro.operation"); + text += "\n\n"; + } + if (getUi().getStepModel().containsStepForsave(AdminStep.VALIDATE)) { + text = t("observe.actions.synchro.referential.message.need.save.for.validation.operation"); + text += "\n\n"; + } + getUi().needSaveText.setText(text); + } + + public String updateText(boolean localSourceNeedSave) { + return localSourceNeedSave ? t("observe.actions.synchro.referential.message.synchro.local.modification") : t("observe.actions.synchro.referential.message.no.local.modification"); + } + + public void skipOperation() { + sendMessage(t("observe.actions.synchro.referential.message.saveLocal.skip")); + getModel().setStepState(AdminStep.SAVE_LOCAL, WizardState.SUCCESSED); +// getUi().getProgression().setText(t("observe.synchro.message.saveLocal.skip")); + // on passe directement à l'opération suivante + if (model.getNextStep() != null) { + model.gotoNextStep(); + } + } + + public void chooseBackupFile() { + File f = UIHelper.chooseDirectory( + getUi(), + t("observe.title.choose.db.dump.directory"), + t("observe.action.choose.db.dump.directory"), + new File(getUi().directoryText.getText()) + ); + changeDirectory(f); + } + + public void changeDirectory(File f) { + getUi().getStepModel().setBackupFile(new File(f, getUi().filenameText.getText())); + } + + public void changeFilename(String filename) { + getUi().getStepModel().setBackupFile(new File(getUi().directoryText.getText(), filename)); + } + + public void doStartAction() { + + addAdminWorker(getUi().getStartAction().getToolTipText(), this::doAction); + + } + + public WizardState doAction() throws Exception { + if (log.isDebugEnabled()) { + log.debug(this); + } + + source = model.getSafeLocalSource(false); + + SaveLocalModel stepModel = model.getSaveLocalModel(); + if (!stepModel.isLocalSourceNeedSave()) { + sendMessage("Aucune modification sur la base locale, opération non requise."); + // pas de modification sur la base locale + return WizardState.SUCCESSED; + } + + openSource(source); + + if (stepModel.isDoBackup()) { + + sendMessage("Sauvegarde de la base locale vers " + stepModel.getBackupFile()); + + // on effectue une sauvegarde de la base locale + File backupFile = stepModel.getBackupFile(); + + SqlScriptProducerService dumpService = source.newSqlScriptProducerService(); + AddSqlScriptProducerRequest request = AddSqlScriptProducerRequest.forH2().addSchema().addReferential().addAllData(); + byte[] dump = dumpService.produceAddSqlScript(request); + + try (FileOutputStream outputStream = new FileOutputStream(backupFile)) { + IOUtils.write(dump, outputStream); + } + + } + + if (stepModel.containsStepForsave(AdminStep.SYNCHRONIZE)) { + + sendMessage("Sauvegarde du référentiel."); + saveUnidirectionalSynchronizeReferential(); + } + + sendMessage(t("observe.actions.operation.message.done", new Date())); + + return WizardState.SUCCESSED; + } + + public void saveUnidirectionalSynchronizeReferential() { + + SynchronizeModel stepModel = getModel().getSynchronizeReferentielModel(); + + UnidirectionalReferentialSynchronizeEngine engine = stepModel.getEngine(); + + UnidirectionalReferentialSynchronizeContext referentialSynchronizeContext = stepModel.getReferentialSynchronizeContext(); + + engine.finish(referentialSynchronizeContext); + + + sendMessage(t("observe.actions.synchro.referential.message.apply.done", new Date())); + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/DataSynchroModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/DataSynchroModel.java new file mode 100644 index 0000000..320a8a0 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/DataSynchroModel.java @@ -0,0 +1,119 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.data; + +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.ui.admin.AdminActionModel; +import fr.ird.observe.application.swing.ui.admin.AdminStep; +import fr.ird.observe.application.swing.ui.admin.synchronize.data.task.DataSynchronizeTaskSupport; +import fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.DefaultListModel; + +/** + * Created on 02/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class DataSynchroModel extends AdminActionModel { + + /** Logger. */ + private static final Log log = LogFactory.getLog(DataSynchroModel.class); + + public static final String LEFT_SOURCE_PROPERTY_NAME = "leftSource"; + public static final String RIGHT_SOURCE_PROPERTY_NAME = "rightSource"; + public static final String TASKS_PROPERTY_NAME = "tasks"; + + public static final String LEFT_SELECTION_MODEL_CHANGED_PROPERTY_NAME = "leftSelectionModelChanged"; + public static final String RIGHT_SELECTION_MODEL_CHANGED_PROPERTY_NAME = "rightSelectionModelChanged"; + + /** la source sur le panneau de gauche. */ + protected ObserveSwingDataSource leftSource; + + /** la source sur le panneau de droite. */ + protected ObserveSwingDataSource rightSource; + + /** les données sélectionnées sur le panneau de gauche. */ + protected final DataSelectionModel leftSelectionDataModel; + + /** les données sélectionnées sur le panneau de droite. */ + protected final DataSelectionModel rightSelectionDataModel; + + protected final DefaultListModel<DataSynchronizeTaskSupport> tasks; + + public DataSynchroModel() { + super(AdminStep.DATA_SYNCHRONIZE); + + leftSelectionDataModel = new DataSelectionModel(); + leftSelectionDataModel.setUseData(true); + + rightSelectionDataModel = new DataSelectionModel(); + rightSelectionDataModel.setUseData(true); + tasks = new DefaultListModel<>(); + + } + + public ObserveSwingDataSource getLeftSource() { + return leftSource; + } + + public void setLeftSource(ObserveSwingDataSource leftSource) { + this.leftSource = leftSource; + firePropertyChange(LEFT_SOURCE_PROPERTY_NAME, leftSource); + } + + public ObserveSwingDataSource getRightSource() { + return rightSource; + } + + public void setRightSource(ObserveSwingDataSource rightSource) { + this.rightSource = rightSource; + firePropertyChange(RIGHT_SOURCE_PROPERTY_NAME, rightSource); + } + + public DataSelectionModel getLeftSelectionDataModel() { + return leftSelectionDataModel; + } + + public DataSelectionModel getRightSelectionDataModel() { + return rightSelectionDataModel; + } + + public void populateLeftSelectionModel() { + populateSelectionModel(leftSource, leftSelectionDataModel, LEFT_SELECTION_MODEL_CHANGED_PROPERTY_NAME); + } + + public void populateRightSelectionModel() { + populateSelectionModel(rightSource, rightSelectionDataModel, RIGHT_SELECTION_MODEL_CHANGED_PROPERTY_NAME); + } + + public DefaultListModel<DataSynchronizeTaskSupport> getTasks() { + return tasks; + } + + public void addTask(DataSynchronizeTaskSupport task) { + tasks.addElement(task); + } + + private void populateSelectionModel(ObserveSwingDataSource dataSource, DataSelectionModel selectionDataModel, String propertyName) { + + try { + + DataSelectionModel.populate(selectionDataModel, dataSource); + + } catch (Exception e) { + + if (log.isErrorEnabled()) { + log.error("could not populate selected model", e); + } + + } finally { + + // on notifie que le modèle de sélection a changé + // (il faut donc recalculé l'arbre de sélection) + firePropertyChange(propertyName, selectionDataModel); + + } + } +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/DataSynchroUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/DataSynchroUI.jaxx new file mode 100644 index 0000000..833b4d4 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/DataSynchroUI.jaxx @@ -0,0 +1,139 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<!-- ************************************************************* --> +<!-- L'écran de synchronisation bi-directionnel des données --> +<!-- ************************************************************* --> + +<fr.ird.observe.application.swing.ui.admin.AdminTabUI> + + <import> + fr.ird.observe.application.swing.ui.UIHelper + fr.ird.observe.application.swing.ui.admin.AdminUI + fr.ird.observe.application.swing.ui.admin.AdminStep + fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper + fr.ird.observe.application.swing.ui.tree.DataSelectionTreeCellRenderer + fr.ird.observe.application.swing.ui.tree.DataSelectionTreeSelectionModel + fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel + + jaxx.runtime.SwingUtil + + javax.swing.ListSelectionModel + javax.swing.tree.TreeSelectionModel + + </import> + + <ObserveTreeHelper id='leftTreeHelper'/> + <ObserveTreeHelper id='rightTreeHelper'/> + + <DataSynchroUIHandler id='handler' constructorParams='this'/> + + <DataSynchroModel id='stepModel' initializer='getModel().getDataSynchroModel()'/> + + <DataSelectionModel id='leftSelectDataModel' + initializer='getModel().getDataSynchroModel().getLeftSelectionDataModel()'/> + <DataSelectionTreeSelectionModel id='leftSelectionModel'/> + + <DataSelectionModel id='rightSelectDataModel' + initializer='getModel().getDataSynchroModel().getRightSelectionDataModel()'/> + <DataSelectionTreeSelectionModel id='rightSelectionModel'/> + <JPanel id='invisiblePanel'> + <DataSelectionTreeCellRenderer id='leftSelectionRenderer'/> + <DataSelectionTreeCellRenderer id='rightSelectionRenderer'/> + </JPanel> + + <script><![CDATA[ +public DataSynchroUI(AdminUI parentContext) { + super(AdminStep.DATA_SYNCHRONIZE, parentContext); +} + +public void initUI(AdminUI ui) { + getHandler().initTabUI(ui, this); +} + +@Override +public void destroy() { + leftSelectionModel.clearSelection(); + rightSelectionModel.clearSelection(); + super.destroy(); +} +]]> + </script> + + <JPanel id='PENDING_content'> + <Table constraints='BorderLayout.CENTER' fill='both' weightx='1' + weighty='1'> + <row> + <cell> + <JButton id='startAction' onActionPerformed="getHandler().doStartAction()"/> + </cell> + </row> + </Table> + </JPanel> + <JPanel id='NEED_FIX_content'> + <JSplitPane id="contentSplitPane" constraints='BorderLayout.CENTER'> + <Table id='contentNorth' fill="both" weighty="1"> + <row> + <cell weightx="0.45"> + <JScrollPane id='leftTreePane' decorator='boxed'> + <JTree id='leftTree'/> + </JScrollPane> + </cell> + <cell weightx="0.1"> + <JPanel layout="{new BorderLayout()}" border='{new TitledBorder(" ")}'> + <JPanel id="middleActions" layout="{new GridLayout(0, 2)}" constraints='BorderLayout.CENTER'> + <JButton id="copyToRight" onActionPerformed="getHandler().addCopyToRightTasks()"/> + <JButton id="copyToLeft" onActionPerformed="getHandler().addCopyToLeftTasks()"/> + <JButton id="deleteFromLeft" onActionPerformed="getHandler().addDeleteFromLeftTasks()"/> + <JButton id="deleteFromRight" onActionPerformed="getHandler().addDeleteFromRightTasks()"/> + </JPanel> + </JPanel> + </cell> + <cell weightx="0.45"> + <JScrollPane id='rightTreePane' decorator='boxed'> + <JTree id='rightTree'/> + </JScrollPane> + </cell> + </row> + </Table> + <Table id='contentSouth' fill="both"> + <row weighty="1"> + <cell weightx="1"> + <JScrollPane id='actionsToConsumePane'> + <JList id="actionsToConsume"/> + </JScrollPane> + </cell> + </row> + <row> + <cell> + <JPanel layout="{new BorderLayout()}"> + <JButton id='applyAction' constraints='BorderLayout.CENTER' + onActionPerformed='getHandler().doExecuteAction()'/> + </JPanel> + </cell> + </row> + </Table> + </JSplitPane> + + </JPanel> + +</fr.ird.observe.application.swing.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/DataSynchroUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/DataSynchroUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/DataSynchroUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/DataSynchroUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/DataSynchroUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/DataSynchroUIHandler.java new file mode 100644 index 0000000..1dfa5ea --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/DataSynchroUIHandler.java @@ -0,0 +1,301 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.data; + +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaH2; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.service.actions.synchro.data.DataSynchronizeRequest; +import fr.ird.observe.services.service.actions.synchro.data.DataSynchronizeService; +import fr.ird.observe.services.service.actions.synchro.data.task.DataSynchronizeCopyTask; +import fr.ird.observe.services.service.actions.synchro.data.task.DataSynchronizeDeleteTask; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.admin.AdminStep; +import fr.ird.observe.application.swing.ui.admin.AdminTabUI; +import fr.ird.observe.application.swing.ui.admin.AdminTabUIHandler; +import fr.ird.observe.application.swing.ui.admin.AdminUI; +import fr.ird.observe.application.swing.ui.admin.config.ConfigUI; +import fr.ird.observe.application.swing.ui.admin.synchronize.data.task.CopyToLeftDataSynchronizeTask; +import fr.ird.observe.application.swing.ui.admin.synchronize.data.task.CopyToRightDataSynchronizeTask; +import fr.ird.observe.application.swing.ui.admin.synchronize.data.task.DataSynchronizeTaskSupport; +import fr.ird.observe.application.swing.ui.admin.synchronize.data.task.DeleteFromLeftDataSynchronizeTask; +import fr.ird.observe.application.swing.ui.admin.synchronize.data.task.DeleteFromRightDataSynchronizeTask; +import fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import jaxx.runtime.swing.wizard.ext.WizardState; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.DefaultListModel; +import javax.swing.border.TitledBorder; +import java.util.List; +import java.util.Map; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 02/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class DataSynchroUIHandler extends AdminTabUIHandler { + + /** Logger */ + private static final Log log = LogFactory.getLog(DataSynchroUIHandler.class); + + public DataSynchroUIHandler(DataSynchroUI ui) { + super(ui); + } + + public DataSynchroModel getStepModel() { + return model.getDataSynchroModel(); + } + + @Override + public DataSynchroUI getUi() { + return (DataSynchroUI) super.getUi(); + } + + @Override + public void updateState(AdminTabUI ui, WizardState newState) { + super.updateState(ui, newState); + } + + public void initTabUI(AdminUI ui, DataSynchroUI tabUI) { + + super.initTabUI(ui, tabUI); + + if (log.isDebugEnabled()) { + log.debug(" specialized for [" + tabUI.getStep() + "] for main ui " + ui.getClass().getName() + "@" + System.identityHashCode(ui)); + } + + getStepModel().getLeftSelectionDataModel().addPropertyChangeListener(evt -> { + + DataSelectionModel model = (DataSelectionModel) evt.getSource(); + boolean withDataSelected = !model.isDataEmpty(); + + tabUI.getCopyToRight().setEnabled(withDataSelected); + tabUI.getDeleteFromLeft().setEnabled(withDataSelected); + + }); + getStepModel().getRightSelectionDataModel().addPropertyChangeListener(evt -> { + + DataSelectionModel model = (DataSelectionModel) evt.getSource(); + boolean withDataSelected = !model.isDataEmpty(); + + tabUI.getCopyToLeft().setEnabled(withDataSelected); + tabUI.getDeleteFromRight().setEnabled(withDataSelected); + + }); + + UIHelper.initUI(tabUI.getLeftTreePane(), tabUI.getLeftTree()); + UIHelper.initUI(tabUI.getRightTreePane(), tabUI.getRightTree()); + + } + + public void doStartAction() { + + addAdminWorker(getUi().getStartAction().getToolTipText(), this::doStartAction0); + + } + + private WizardState doStartAction0() { + + DataSynchroUI tabUI = getUi(); + DataSynchroModel stepModel = getStepModel(); + ConfigUI configUI = (ConfigUI) parentUI.getStepUI(AdminStep.CONFIG); + + ObserveSwingDataSource leftSource = getModel().getSafeLocalSource(true); + stepModel.setLeftSource(leftSource); + + ObserveSwingDataSource rightSource = getModel().getSafeCentralSource(true); + stepModel.setRightSource(rightSource); + + tabUI.getLeftTreePane().setBorder(new TitledBorder(getModel().getLocalSourceModel().getLabel())); + stepModel.populateLeftSelectionModel(); + updateSelectionModel(tabUI, tabUI.getLeftTreeHelper(), tabUI.getLeftTree(), leftSource, stepModel.getLeftSelectionDataModel(), tabUI.getLeftSelectionModel()); + sendMessage(t("observe.actions.synchro.referential.message.data.leftData.loaded")); + + configUI.getLocalSourceConfig().setBorder(new TitledBorder(getModel().getLocalSourceLabel())); + + tabUI.getRightTreePane().setBorder(new TitledBorder(getModel().getCentralSourceModel().getLabel())); + stepModel.populateRightSelectionModel(); + updateSelectionModel(tabUI, tabUI.getRightTreeHelper(), tabUI.getRightTree(), rightSource, stepModel.getRightSelectionDataModel(), tabUI.getRightSelectionModel()); + sendMessage(t("observe.actions.synchro.referential.message.data.rightData.loaded")); + + configUI.getCentralSourceConfig().setBorder(new TitledBorder(getModel().getCentralSourceLabel())); + + return WizardState.NEED_FIX; + + } + + public void addCopyToLeftTasks() { + + DataSelectionModel rightSelectionDataModel = getStepModel().getRightSelectionDataModel(); + DataSelectionModel leftSelectionDataModel = getStepModel().getLeftSelectionDataModel(); + ObserveTreeHelper rightTreeHelper = getUi().getRightTreeHelper(); + ObserveTreeHelper leftTreeHelper = getUi().getLeftTreeHelper(); + Map<ReferentialReference<ProgramDto>, List<DataReference>> selectedDataByProgram = rightSelectionDataModel.getSelectedDataByProgram(); + rightSelectionDataModel.removeAllSelectedData(); + for (Map.Entry<ReferentialReference<ProgramDto>, List<DataReference>> entry : selectedDataByProgram.entrySet()) { + ReferentialReference<ProgramDto> program = entry.getKey(); + for (DataReference trip : entry.getValue()) { + boolean tripExistOnLeft = leftSelectionDataModel.containsData(program, trip); + getStepModel().addTask(new CopyToLeftDataSynchronizeTask(program, trip, tripExistOnLeft)); + rightTreeHelper.removeTrip(program, trip); + rightSelectionDataModel.removeTrip(program, trip); + + if (tripExistOnLeft) { + leftTreeHelper.removeTrip(program, trip); + leftSelectionDataModel.removeTrip(program, trip); + } + } + } + + + } + + public void addCopyToRightTasks() { + + DataSelectionModel leftSelectionDataModel = getStepModel().getLeftSelectionDataModel(); + DataSelectionModel rightSelectionDataModel = getStepModel().getRightSelectionDataModel(); + ObserveTreeHelper leftTreeHelper = getUi().getLeftTreeHelper(); + ObserveTreeHelper rightTreeHelper = getUi().getRightTreeHelper(); + Map<ReferentialReference<ProgramDto>, List<DataReference>> selectedDataByProgram = leftSelectionDataModel.getSelectedDataByProgram(); + leftSelectionDataModel.removeAllSelectedData(); + for (Map.Entry<ReferentialReference<ProgramDto>, List<DataReference>> entry : selectedDataByProgram.entrySet()) { + ReferentialReference<ProgramDto> program = entry.getKey(); + for (DataReference trip : entry.getValue()) { + + boolean tripExistOnRight = rightSelectionDataModel.containsData(program, trip); + getStepModel().addTask(new CopyToRightDataSynchronizeTask(program, trip, tripExistOnRight)); + leftTreeHelper.removeTrip(program, trip); + leftSelectionDataModel.removeTrip(program, trip); + + if (tripExistOnRight) { + rightTreeHelper.removeTrip(program, trip); + rightSelectionDataModel.removeTrip(program, trip); + } + } + } + + } + + public void addDeleteFromLeftTasks() { + + DataSelectionModel selectionDataModel = getStepModel().getLeftSelectionDataModel(); + ObserveTreeHelper treeHelper = getUi().getLeftTreeHelper(); + Map<ReferentialReference<ProgramDto>, List<DataReference>> selectedDataByProgram = selectionDataModel.getSelectedDataByProgram(); + selectionDataModel.removeAllSelectedData(); + for (Map.Entry<ReferentialReference<ProgramDto>, List<DataReference>> entry : selectedDataByProgram.entrySet()) { + ReferentialReference<ProgramDto> program = entry.getKey(); + for (DataReference trip : entry.getValue()) { + getStepModel().addTask(new DeleteFromLeftDataSynchronizeTask(program, trip)); + treeHelper.removeTrip(program, trip); + selectionDataModel.removeTrip(program, trip); + } + } + + } + + public void addDeleteFromRightTasks() { + + DataSelectionModel selectionDataModel = getStepModel().getRightSelectionDataModel(); + ObserveTreeHelper treeHelper = getUi().getRightTreeHelper(); + Map<ReferentialReference<ProgramDto>, List<DataReference>> selectedDataByProgram = selectionDataModel.getSelectedDataByProgram(); + selectionDataModel.removeAllSelectedData(); + for (Map.Entry<ReferentialReference<ProgramDto>, List<DataReference>> entry : selectedDataByProgram.entrySet()) { + ReferentialReference<ProgramDto> program = entry.getKey(); + for (DataReference trip : entry.getValue()) { + getStepModel().addTask(new DeleteFromRightDataSynchronizeTask(program, trip)); + treeHelper.removeTrip(program, trip); + selectionDataModel.removeTrip(program, trip); + } + } + + } + + public void doExecuteAction() { + + ObserveSwingDataSource leftSource = getStepModel().getLeftSource(); + boolean leftSourceIsH2 = leftSource.getConfiguration() instanceof ObserveDataSourceConfigurationTopiaH2; + + ObserveSwingDataSource rightSource = getStepModel().getRightSource(); + boolean rightSourceIsH2 = rightSource.getConfiguration() instanceof ObserveDataSourceConfigurationTopiaH2; + + DefaultListModel<DataSynchronizeTaskSupport> tasks = getStepModel().getTasks(); + int size = tasks.size(); + + DecoratorService decoratorService = getDecoratorService(); + ReferentialReferenceDecorator<ProgramDto> programDecorator = decoratorService.getReferentialReferenceDecorator(ProgramDto.class); + + DataSynchronizeRequest.Builder leftDataSynchronizeRequestBuilder = DataSynchronizeRequest.builder(leftSourceIsH2, rightSourceIsH2); + DataSynchronizeRequest.Builder rightDataSynchronizeRequestBuilder = DataSynchronizeRequest.builder(rightSourceIsH2, leftSourceIsH2); + for (int i = 0; i < size; i++) { + + DataSynchronizeTaskSupport task = tasks.getElementAt(i); + + String programStr = programDecorator.toString(task.getProgram()); + String tripStr = decoratorService.getTripReferenceDecorator(task.getTrip()).toString(task.getTrip()); + + if (task instanceof DeleteFromLeftDataSynchronizeTask) { + + sendMessage(t("observe.actions.synchro.data.prepare.deleteFromLeftTask", programStr, tripStr)); + leftDataSynchronizeRequestBuilder.addDeleteTask(new DataSynchronizeDeleteTask(task.getProgram().getId(), task.getTrip().getId())); + continue; + } + + if (task instanceof DeleteFromRightDataSynchronizeTask) { + sendMessage(t("observe.actions.synchro.data.prepare.deleteFromRightTask", programStr, tripStr)); + rightDataSynchronizeRequestBuilder.addDeleteTask(new DataSynchronizeDeleteTask(task.getProgram().getId(), task.getTrip().getId())); + continue; + } + + if (task instanceof CopyToLeftDataSynchronizeTask) { + CopyToLeftDataSynchronizeTask task1 = (CopyToLeftDataSynchronizeTask) task; + if (task1.isTripExistOnLeft()) { + sendMessage(t("observe.actions.synchro.data.prepare.deleteFromLeftTask", programStr, tripStr)); + leftDataSynchronizeRequestBuilder.addDeleteTask(new DataSynchronizeDeleteTask(task.getProgram().getId(), task.getTrip().getId())); + } + sendMessage(t("observe.actions.synchro.data.prepare.copyToLeftTask", programStr, tripStr)); + leftDataSynchronizeRequestBuilder.addCopyTask(new DataSynchronizeCopyTask(task.getProgram().getId(), task.getTrip().getId())); + continue; + } + + if (task instanceof CopyToRightDataSynchronizeTask) { + CopyToRightDataSynchronizeTask task1 = (CopyToRightDataSynchronizeTask) task; + if (task1.isTripExistOnRight()) { + sendMessage(t("observe.actions.synchro.data.prepare.deleteFromRightTask", programStr, tripStr)); + rightDataSynchronizeRequestBuilder.addDeleteTask(new DataSynchronizeDeleteTask(task.getProgram().getId(), task.getTrip().getId())); + } + sendMessage(t("observe.actions.synchro.data.prepare.copyToRightTask", programStr, tripStr)); + rightDataSynchronizeRequestBuilder.addCopyTask(new DataSynchronizeCopyTask(task.getProgram().getId(), task.getTrip().getId())); + } + + } + + DataSynchronizeService leftDataSynchronizeService = leftSource.newDataSynchronizeService(); + DataSynchronizeService rightDataSynchronizeService = rightSource.newDataSynchronizeService(); + + DataSynchronizeRequest leftDataSynchronizeRequest = leftDataSynchronizeRequestBuilder.build(); + if (leftDataSynchronizeRequest.isNotEmpty()) { + byte[][] copySqlCodes = rightDataSynchronizeService.getCopySqlCodes(leftDataSynchronizeRequest); + byte[][] deleteSqlCodes = leftDataSynchronizeService.getDeleteSqlCodes(leftDataSynchronizeRequest); + leftDataSynchronizeService.executeRequest(copySqlCodes, deleteSqlCodes); + } + + DataSynchronizeRequest rightDataSynchronizeRequest = rightDataSynchronizeRequestBuilder.build(); + if (rightDataSynchronizeRequest.isNotEmpty()) { + byte[][] copySqlCodes = leftDataSynchronizeService.getCopySqlCodes(rightDataSynchronizeRequest); + byte[][] deleteSqlCodes = rightDataSynchronizeService.getDeleteSqlCodes(rightDataSynchronizeRequest); + rightDataSynchronizeService.executeRequest(copySqlCodes, deleteSqlCodes); + } + + getModel().setStepState(WizardState.SUCCESSED); + + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/DataSynchronizeTaskListCellRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/DataSynchronizeTaskListCellRenderer.java new file mode 100644 index 0000000..83507ad --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/DataSynchronizeTaskListCellRenderer.java @@ -0,0 +1,29 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.data; + +import fr.ird.observe.application.swing.ui.admin.synchronize.data.task.DataSynchronizeTaskSupport; + +import javax.swing.DefaultListCellRenderer; +import javax.swing.JList; +import java.awt.Component; + +/** + * Created on 03/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class DataSynchronizeTaskListCellRenderer extends DefaultListCellRenderer { + + private static final long serialVersionUID = 1L; + + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + + DataSynchronizeTaskSupport task = (DataSynchronizeTaskSupport) value; + super.getListCellRendererComponent(list, task.getLabel(), index, isSelected, cellHasFocus); + setIcon(task.getIcon()); + return this; + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/task/CopyToLeftDataSynchronizeTask.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/task/CopyToLeftDataSynchronizeTask.java new file mode 100644 index 0000000..43ca74c --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/task/CopyToLeftDataSynchronizeTask.java @@ -0,0 +1,33 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.data.task; + +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 03/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class CopyToLeftDataSynchronizeTask extends DataSynchronizeTaskSupport { + + private final boolean tripExistOnLeft; + + public CopyToLeftDataSynchronizeTask(ReferentialReference<ProgramDto> programReference, DataReference tripReference, boolean tripExistOnLeft) { + super(programReference, tripReference, "copyToLeft"); + this.tripExistOnLeft=tripExistOnLeft; + } + + @Override + public String getLabel() { + return t("observe.actions.synchro.data.copyToLeftTask", decorateProgram(), decorateTrip()); + } + + public boolean isTripExistOnLeft() { + return tripExistOnLeft; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/task/CopyToRightDataSynchronizeTask.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/task/CopyToRightDataSynchronizeTask.java new file mode 100644 index 0000000..6e321dd --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/task/CopyToRightDataSynchronizeTask.java @@ -0,0 +1,33 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.data.task; + +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 03/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class CopyToRightDataSynchronizeTask extends DataSynchronizeTaskSupport { + + private final boolean tripExistOnRight; + + public CopyToRightDataSynchronizeTask(ReferentialReference<ProgramDto> programReference, DataReference tripReference, boolean tripExistOnRight) { + super(programReference, tripReference, "copyToRight"); + this.tripExistOnRight = tripExistOnRight; + } + + @Override + public String getLabel() { + return t("observe.actions.synchro.data.copyToRightTask", decorateProgram(), decorateTrip()); + } + + public boolean isTripExistOnRight() { + return tripExistOnRight; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/task/DataSynchronizeTaskSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/task/DataSynchronizeTaskSupport.java new file mode 100644 index 0000000..5e3f787 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/task/DataSynchronizeTaskSupport.java @@ -0,0 +1,56 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.data.task; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import jaxx.runtime.SwingUtil; + +import javax.swing.Icon; + +/** + * Created on 03/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public abstract class DataSynchronizeTaskSupport { + + private final ReferentialReference<ProgramDto> program; + private final DataReference trip; + private final Icon icon; + + public abstract String getLabel(); + + public ReferentialReference<ProgramDto> getProgram() { + return program; + } + + public DataReference getTrip() { + return trip; + } + + public Icon getIcon() { + return icon; + } + + protected DataSynchronizeTaskSupport(ReferentialReference<ProgramDto> program, DataReference trip, String iconName) { + this.program = program; + this.trip = trip; + this.icon = SwingUtil.createActionIcon(iconName); + } + + protected String decorateProgram() { + DecoratorService decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); + String programStr = decoratorService.getReferentialReferenceDecorator(ProgramDto.class).toString(getProgram()); + return programStr; + } + + protected String decorateTrip() { + DecoratorService decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); + String tripStr = decoratorService.getTripReferenceDecorator(getTrip()).toString(getTrip()); + return tripStr; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/task/DeleteFromLeftDataSynchronizeTask.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/task/DeleteFromLeftDataSynchronizeTask.java new file mode 100644 index 0000000..965adf7 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/task/DeleteFromLeftDataSynchronizeTask.java @@ -0,0 +1,25 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.data.task; + +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 03/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class DeleteFromLeftDataSynchronizeTask extends DataSynchronizeTaskSupport { + + public DeleteFromLeftDataSynchronizeTask(ReferentialReference<ProgramDto> programReference, DataReference tripReference) { + super(programReference, tripReference, "deleteFromLeft"); + } + + @Override + public String getLabel() { + return t("observe.actions.synchro.data.deleteFromLeftTask", decorateProgram(), decorateTrip()); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/task/DeleteFromRightDataSynchronizeTask.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/task/DeleteFromRightDataSynchronizeTask.java new file mode 100644 index 0000000..99908a1 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/data/task/DeleteFromRightDataSynchronizeTask.java @@ -0,0 +1,25 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.data.task; + +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 03/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class DeleteFromRightDataSynchronizeTask extends DataSynchronizeTaskSupport { + + public DeleteFromRightDataSynchronizeTask(ReferentialReference<ProgramDto> programReference, DataReference tripReference) { + super(programReference, tripReference, "deleteFromRight"); + } + + @Override + public String getLabel() { + return t("observe.actions.synchro.data.deleteFromRightTask", decorateProgram(), decorateTrip()); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/legacy/ObsoleteReferentialReference.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/legacy/ObsoleteReferentialReference.java new file mode 100644 index 0000000..4150d3e --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/legacy/ObsoleteReferentialReference.java @@ -0,0 +1,74 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.legacy; + +/*- + * #%L + * ObServe :: Application Swing + * %% + * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; + +import java.util.Objects; + +/** + * Représente une référence obsolète à remplacer. + * + * Created on 13/07/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class ObsoleteReferentialReference<R extends ReferentialDto> { + + private final ReferentialReference<R> referentialReference; + + public ObsoleteReferentialReference(Class<R>referentialName, ReferentialReference<R> referentialReference) { + this.referentialReference = referentialReference; + } + + public Class<R> getReferentialName() { + return getType(); + } + + public ReferentialReference<R> getReferentialReference() { + return referentialReference; + } + + public String getId() { + return referentialReference.getId(); + } + + public Class<R> getType() { + return referentialReference.getType(); + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + ObsoleteReferentialReference that = (ObsoleteReferentialReference) o; + return Objects.equals(getReferentialReference(), that.getReferentialReference()); + } + + @Override + public int hashCode() { + return Objects.hash(getReferentialReference()); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/legacy/ObsoleteReferentialReferenceListCellRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/legacy/ObsoleteReferentialReferenceListCellRenderer.java new file mode 100644 index 0000000..df9d436 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/legacy/ObsoleteReferentialReferenceListCellRenderer.java @@ -0,0 +1,72 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.legacy; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import org.nuiton.decorator.Decorator; + +import javax.swing.DefaultListCellRenderer; +import javax.swing.JList; +import java.awt.Component; + +import static org.nuiton.i18n.I18n.t; + +public class ObsoleteReferentialReferenceListCellRenderer extends DefaultListCellRenderer { + + private static final long serialVersionUID = 1L; + + protected transient DecoratorService decoratorService; + + public DecoratorService getDecoratorService() { + if (decoratorService == null) { + decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); + } + return decoratorService; + } + + @Override + public Component getListCellRendererComponent( + JList list, + Object value, + int index, + boolean isSelected, + boolean cellHasFocus) { + + ObsoleteReferentialReference referentialReference = (ObsoleteReferentialReference) value; + + DecoratorService service = getDecoratorService(); + Class referentialReferenceType = referentialReference.getReferentialReference().getType(); + String type = t(DecoratorService.getEntityLabel(referentialReferenceType)); + Decorator<?> decorator = service.getReferentialReferenceDecorator(referentialReferenceType); + + String text = type + " : " + decorator.toString(referentialReference.getReferentialReference()); + + return super.getListCellRendererComponent( + list, + text, + index, + isSelected, + cellHasFocus + ); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/legacy/SynchronizeModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/legacy/SynchronizeModel.java new file mode 100644 index 0000000..3cdf31d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/legacy/SynchronizeModel.java @@ -0,0 +1,124 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.legacy; + +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeCallbackResults; +import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeContext; +import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeEngine; +import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeResult; +import fr.ird.observe.application.swing.ui.admin.AdminActionModel; +import fr.ird.observe.application.swing.ui.admin.AdminStep; +import jaxx.runtime.swing.model.JaxxDefaultListModel; + +import javax.swing.DefaultListSelectionModel; +import java.util.List; + +/** + * Le modèle de l'opération de synchronization de réferentiel. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class SynchronizeModel extends AdminActionModel { + + private final JaxxDefaultListModel<ObsoleteReferentialReference> obsoleteReferences = new JaxxDefaultListModel<>(); + private final DefaultListSelectionModel obsoleteReferencesSelectionModel = new DefaultListSelectionModel(); + /** data source we want to synchronize. */ + protected ObserveSwingDataSource source; + /** data source which contains central referentiel. */ + protected ObserveSwingDataSource centralSource; + /** Le resultat de la synchronisation des référentiels. */ + private UnidirectionalReferentialSynchronizeResult referentialSynchronizeResult; + private UnidirectionalReferentialSynchronizeEngine engine; + private UnidirectionalReferentialSynchronizeContext referentialSynchronizeContext; + private UnidirectionalReferentialSynchronizeCallbackResults referentialSynchronizeCallbackResults; + + public SynchronizeModel() { + super(AdminStep.SYNCHRONIZE); + } + + public ObserveSwingDataSource getSource() { + return source; + } + + public void setSource(ObserveSwingDataSource source) { + this.source = source; + } + + public ObserveSwingDataSource getCentralSource() { + return centralSource; + } + + public void setCentralSource(ObserveSwingDataSource centralSource) { + this.centralSource = centralSource; + } + + public UnidirectionalReferentialSynchronizeResult getReferentialSynchronizeResult() { + return referentialSynchronizeResult; + } + + public void setReferentialSynchronizeResult(UnidirectionalReferentialSynchronizeResult referentialSynchronizeResult) { + this.referentialSynchronizeResult = referentialSynchronizeResult; + } + + public UnidirectionalReferentialSynchronizeEngine getEngine() { + return engine; + } + + public void setEngine(UnidirectionalReferentialSynchronizeEngine engine) { + this.engine = engine; + } + + public UnidirectionalReferentialSynchronizeContext getReferentialSynchronizeContext() { + return referentialSynchronizeContext; + } + + public void setReferentialSynchronizeContext(UnidirectionalReferentialSynchronizeContext referentialSynchronizeContext) { + this.referentialSynchronizeContext = referentialSynchronizeContext; + } + + public UnidirectionalReferentialSynchronizeCallbackResults getReferentialSynchronizeCallbackResults() { + return referentialSynchronizeCallbackResults; + } + + public void setReferentialSynchronizeCallbackResults(UnidirectionalReferentialSynchronizeCallbackResults referentialSynchronizeCallbackResults) { + this.referentialSynchronizeCallbackResults = referentialSynchronizeCallbackResults; + } + + public JaxxDefaultListModel<ObsoleteReferentialReference> getObsoleteReferences() { + return obsoleteReferences; + } + + public void setObsoleteReferences(List<ObsoleteReferentialReference> obsoleteReferences) { + this.obsoleteReferences.setAllElements(obsoleteReferences); + } + + public DefaultListSelectionModel getObsoleteReferencesSelectionModel() { + return obsoleteReferencesSelectionModel; + } + + public void destroy() { + obsoleteReferencesSelectionModel.clearSelection(); + obsoleteReferences.clear(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/legacy/SynchronizeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/legacy/SynchronizeUI.jaxx new file mode 100644 index 0000000..34fea69 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/legacy/SynchronizeUI.jaxx @@ -0,0 +1,120 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<!-- ****************************************** --> +<!-- L'écran de synchronization du référentiel --> +<!-- ****************************************** --> + +<fr.ird.observe.application.swing.ui.admin.AdminTabUI> + + <import> + fr.ird.observe.application.swing.ui.admin.AdminUI + fr.ird.observe.application.swing.ui.admin.AdminStep + + jaxx.runtime.swing.CardLayout2 + jaxx.runtime.swing.wizard.ext.WizardState + + </import> + + <!-- un etat pour savoir quand on peut activer l'action apply --> + <Boolean id='canApply' javaBean='false'/> + + <SynchronizeUIHandler id='handler' constructorParams='this'/> + + <SynchronizeModel id='stepModel' initializer='getModel().getSynchronizeReferentielModel()'/> + + <CardLayout2 id='safeRefsPanelLayout'/> + + <script><![CDATA[ +public SynchronizeUI(AdminUI parentContext) { + super(AdminStep.SYNCHRONIZE, parentContext); +} + +@Override +public void initUI(AdminUI ui) { + getHandler().initTabUI(ui, this); +} + +@Override +public void destroy() { + stepModel.destroy(); + super.destroy(); + safeRefsPanelLayout.reset(safeRefsPanel); +} + +@Override +public void updateState(WizardState newState) { + getHandler().updateState(this, newState); +} + +protected void apply() { + getHandler().resolveObsoleteReference(); +} + +]]> + </script> + + <JPanel id='PENDING_content'> + <Table constraints='BorderLayout.CENTER' fill='both' weightx='1' + weighty='1'> + <row> + <cell> + <JButton id='startAction' onActionPerformed="getHandler().doStartAction()"/> + </cell> + </row> + </Table> + </JPanel> + + <JPanel id='NEED_FIX_content'> + <JScrollPane id='errorsPane' constraints='BorderLayout.NORTH'> + <JList id='obsoleteReferencesList'/> + </JScrollPane> + + <Table fill='both' constraints='BorderLayout.CENTER' + border='{new TitledBorder(t("observe.actions.synchro.referential.obsolete.entity.fix"))}'> + + <row> + <cell> + <JLabel text='observe.actions.synchro.referential.safe.entity.to.choose.label'/> + </cell> + <cell weightx='1' fill='both'> + + <!-- le panel dans lequel on positionne la liste déroulante de remplacement --> + <JPanel id='safeRefsPanel'/> + </cell> + </row> + <row> + <cell columns='2'> + <JSeparator/> + </cell> + </row> + <row> + <cell columns='2'> + <!-- pour appliquer les remplacements de l'entité obsolète --> + <JButton id='applyAction' onActionPerformed='getHandler().resolveObsoleteReference()'/> + </cell> + </row> + </Table> + + </JPanel> + +</fr.ird.observe.application.swing.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/legacy/SynchronizeUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/legacy/SynchronizeUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/legacy/SynchronizeUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/legacy/SynchronizeUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/legacy/SynchronizeUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/legacy/SynchronizeUIHandler.java new file mode 100644 index 0000000..52a00bc --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/legacy/SynchronizeUIHandler.java @@ -0,0 +1,356 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.legacy; + +import com.google.common.collect.ImmutableSet; +import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.service.actions.synchro.referential.diff.ReferentialSynchronizeDiffsEngine; +import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeCallbackRequest; +import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeCallbackRequests; +import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeCallbackResults; +import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeContext; +import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeEngine; +import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeResult; +import fr.ird.observe.application.swing.ui.admin.AdminStep; +import fr.ird.observe.application.swing.ui.admin.AdminTabUIHandler; +import fr.ird.observe.application.swing.ui.admin.AdminUI; +import jaxx.runtime.swing.CardLayout2; +import jaxx.runtime.swing.editor.bean.BeanComboBox; +import jaxx.runtime.swing.model.JaxxDefaultListModel; +import jaxx.runtime.swing.wizard.ext.WizardState; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.DefaultListSelectionModel; +import javax.swing.JPanel; +import javax.swing.ListSelectionModel; +import javax.swing.event.ListSelectionEvent; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; + +import static org.nuiton.i18n.I18n.t; + +/** + * Le controleur des onglets. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class SynchronizeUIHandler extends AdminTabUIHandler { + + /** Logger */ + private static final Log log = LogFactory.getLog(SynchronizeUIHandler.class); + + public SynchronizeUIHandler(SynchronizeUI ui) { + super(ui); + } + + public SynchronizeModel getStepModel() { + return model.getSynchronizeReferentielModel(); + } + + @Override + public SynchronizeUI getUi() { + return (SynchronizeUI) super.getUi(); + } + + public void initTabUI(AdminUI ui, SynchronizeUI tabUI) { + + super.initTabUI(ui, tabUI); + + if (log.isDebugEnabled()) { + log.debug(" specialized for [" + tabUI.getStep() + "] for main ui " + ui.getClass().getName() + "@" + System.identityHashCode(ui)); + } + + tabUI.getStartAction().setText(t("observe.actions.synchro.referential.legacy.launch.operation", t(tabUI.getStep().getOperationLabel()))); + + DefaultListSelectionModel obsoleteReferenceSelectionModel = tabUI.getModel().getSynchronizeReferentielModel().getObsoleteReferencesSelectionModel(); + obsoleteReferenceSelectionModel.addListSelectionListener(this::updateSelectedObsoleteEntity); + obsoleteReferenceSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + + } + + public void doStartAction() { + + addAdminWorker(getUi().getStartAction().getToolTipText(), this::doStartAction0); + + } + + private WizardState doStartAction0() throws Exception { + + if (log.isDebugEnabled()) { + log.debug(this); + } + + SynchronizeModel stepModel = getStepModel(); + + // on cree les sources de données + + ObserveSwingDataSource source = model.getSafeLocalSource(false); + stepModel.setSource(source); + + ObserveSwingDataSource centralSource = model.getSafeCentralSource(false); + stepModel.setCentralSource(centralSource); + + openSource(source); + openSource(centralSource); + + // construction du différentiel + sendMessage(t("observe.actions.synchro.referential.message.build.diff", centralSource.getLabel())); + + ReferentialSynchronizeDiffsEngine diffsEngine = new ReferentialSynchronizeDiffsEngine( + source.newReferentialSynchronizeDiffService(), + centralSource.newReferentialSynchronizeDiffService() + ); + + UnidirectionalReferentialSynchronizeEngine engine = new UnidirectionalReferentialSynchronizeEngine( + diffsEngine, source.newUnidirectionalReferentialSynchronizeLocalService() + ); + + stepModel.setEngine(engine); + + UnidirectionalReferentialSynchronizeContext unidirectionalReferentialSynchronizeContext = engine.prepareContext(); + + stepModel.setReferentialSynchronizeContext(unidirectionalReferentialSynchronizeContext); + + boolean needCallback = unidirectionalReferentialSynchronizeContext.isNeedCallback(); + + if (needCallback) { + + // il existe des références obsolètes à traiter + + sendMessage(t("observe.actions.operation.message.needFix")); + + stepModel.setReferentialSynchronizeCallbackResults(new UnidirectionalReferentialSynchronizeCallbackResults()); + + // des références obsolètes ont été détectées, on prépare les interfaces graphiques + // avec les données à corriger + + List<ObsoleteReferentialReference> obsoleteReferentialReferences = new LinkedList<>(); + UnidirectionalReferentialSynchronizeCallbackRequests callbackRequests = stepModel.getReferentialSynchronizeContext().getCallbackRequests(); + + for (UnidirectionalReferentialSynchronizeCallbackRequest<?> callbackRequest : callbackRequests) { + + Class referentialName = callbackRequest.getReferentialName(); + + obsoleteReferentialReferences.addAll( + callbackRequest.getReferentialsToReplace().stream() + .map(referentialReference -> new ObsoleteReferentialReference(referentialName, referentialReference)) + .collect(Collectors.toList())); + + } + + stepModel.setObsoleteReferences(obsoleteReferentialReferences); + + return WizardState.NEED_FIX; + + } + + // pas de reference obsolete à traiter + + // on termine le traitement + beforeSuccess(); + + return WizardState.SUCCESSED; + + } + + public <R extends ReferentialDto> void resolveObsoleteReference() { + + ObsoleteReferentialReference<R> obsoleteRef = (ObsoleteReferentialReference) getUi().getObsoleteReferencesList().getSelectedValue(); + + BeanComboBox<ReferentialReference<R>> safeComboBox = (BeanComboBox<ReferentialReference<R>>) getSafeComboBox(); + ReferentialReference<R> safeRef = (ReferentialReference<R>) safeComboBox.getSelectedItem(); + + UnidirectionalReferentialSynchronizeCallbackResults referentialSynchronizeCallbackResults = getStepModel().getReferentialSynchronizeCallbackResults(); + referentialSynchronizeCallbackResults.addCallbackResult(obsoleteRef.getType(), obsoleteRef.getId(), safeRef.getId()); + + // On supprime le référentiel corrigé de la liste des référentiels à corriger + + getStepModel().getObsoleteReferences().removeElement(obsoleteRef); + + // on supprime la sélection de la liste des remplacements + + safeComboBox.setSelectedItem(null); + + // S'il ne reste plus de référentiel à corriger, on peut terminer le traitement + + if (getStepModel().getObsoleteReferences().isEmpty()) { + + beforeSuccess(); + + getModel().setStepState(WizardState.SUCCESSED); +// updateState(getUi(), WizardState.SUCCESSED); + + } + + } + + private void updateSelectedObsoleteEntity(ListSelectionEvent e) { + + if (e.getValueIsAdjusting()) { + return; + } + + SynchronizeUI ui = getUi(); + + int row = getStepModel().getObsoleteReferencesSelectionModel().getMinSelectionIndex(); + + JaxxDefaultListModel<ObsoleteReferentialReference> obsoleteReferences = getStepModel().getObsoleteReferences(); + + if (row != -1 && obsoleteReferences.getElementAt(row) != null) { + + ObsoleteReferentialReference referentialReference = obsoleteReferences.getElementAt(row); + + String key = referentialReference.getReferentialName().getName(); + CardLayout2 safeRefsPanelLayout = ui.getSafeRefsPanelLayout(); + JPanel safeRefsPanel = ui.getSafeRefsPanel(); + if (safeRefsPanelLayout.contains(key)) { + + // la liste déroulante existe deja pour ce type + BeanComboBox<?> list = (BeanComboBox<?>) safeRefsPanelLayout.getComponent(safeRefsPanel, key); + + if (!getSafeComboBox().equals(list)) { + + // on l'affiche + safeRefsPanelLayout.show(safeRefsPanel, key); + + } + + } else { + + ReferentialReferenceDecorator decorator = getDecoratorService().getReferentialReferenceDecorator(referentialReference.getType()); + + UnidirectionalReferentialSynchronizeCallbackRequest<?> callbackRequest = getStepModel().getReferentialSynchronizeContext().getCallbackRequests().getCallbackRequest(referentialReference.getReferentialName()); + ImmutableSet<? extends ReferentialReference<?>> availableReferentials = callbackRequest.getAvailableReferentials(); + + List<ReferentialReference> data = new ArrayList<>(availableReferentials); + + // la liste n'existe pas encore + BeanComboBox<ReferentialReference> box = new BeanComboBox<>(ui); + box.setBean(this); + box.setProperty("safeEntity"); + box.setShowReset(true); + box.addPropertyChangeListener("selectedItem", evt -> updateCanApply()); + safeRefsPanel.add(box, key); + box.init(decorator, data); + + safeRefsPanelLayout.show(safeRefsPanel, key); + + } + + } + } + + private BeanComboBox<?> getSafeComboBox() { + SynchronizeUI ui = getUi(); + JPanel panel = ui.getSafeRefsPanel(); + return (BeanComboBox<?>) ui.getSafeRefsPanelLayout().getVisibleComponent(panel); + } + + private void updateCanApply() { + SynchronizeUI ui = getUi(); + BeanComboBox<?> safeComboBox = getSafeComboBox(); + ui.setCanApply(safeComboBox != null && safeComboBox.getSelectedItem() != null); + } + + private void beforeSuccess() { + + SynchronizeModel stepModel = getStepModel(); + + UnidirectionalReferentialSynchronizeEngine engine = stepModel.getEngine(); + + UnidirectionalReferentialSynchronizeContext referentialSynchronizeContext = stepModel.getReferentialSynchronizeContext(); + + UnidirectionalReferentialSynchronizeCallbackResults referentialSynchronizeCallbackResults = stepModel.getReferentialSynchronizeCallbackResults(); + + UnidirectionalReferentialSynchronizeResult referentialSynchronizeResult = engine.prepareResult(referentialSynchronizeContext, referentialSynchronizeCallbackResults); + stepModel.setReferentialSynchronizeResult(referentialSynchronizeResult); + + if (referentialSynchronizeResult.isEmpty()) { + + sendMessage(t("observe.actions.synchro.referential.message.ref.is.updtodate")); + + } else { + + for (Class<? extends ReferentialDto> referentialName : referentialSynchronizeResult.getReferentialNames()) { + + Collection<String> referentialAdded = referentialSynchronizeResult.getReferentialAdded(referentialName); + if (CollectionUtils.isNotEmpty(referentialAdded)) { + + sendMessage(t("observe.actions.synchro.referential.message.referentiel.was.added", referentialName, referentialAdded.size())); + for (String id : referentialAdded) { + sendMessage(" - " + id); + } + + } + + Collection<String> referentialUpdated = referentialSynchronizeResult.getReferentialUpdated(referentialName); + if (CollectionUtils.isNotEmpty(referentialUpdated)) { + + sendMessage(t("observe.actions.synchro.referential.message.referentiel.was.modified", referentialName, referentialUpdated.size())); + for (String id : referentialUpdated) { + sendMessage(" - " + id); + } + + } + + Collection<String> referentialRemoved = referentialSynchronizeResult.getReferentialRemoved(referentialName); + if (CollectionUtils.isNotEmpty(referentialRemoved)) { + + sendMessage(t("observe.actions.synchro.referential.message.referentiel.was.removed", referentialName, referentialRemoved.size())); + for (String id : referentialRemoved) { + sendMessage(" - " + id); + } + + } + + Collection<Pair<String, String>> referentialReplaced = referentialSynchronizeResult.getReferentialReplaced(referentialName); + if (CollectionUtils.isNotEmpty(referentialReplaced)) { + + sendMessage(t("observe.actions.synchro.referential.message.referentiel.was.replaced", referentialName, referentialReplaced.size())); + for (Pair<String, String> ids : referentialReplaced) { + sendMessage(" - " + ids.getLeft() + " → " + ids.getRight()); + } + + } + + } + + getModel().getSaveLocalModel().addStepForSave(AdminStep.SYNCHRONIZE); + + } + + sendMessage(t("observe.actions.operation.message.done", new Date())); + + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialReplaceUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialReplaceUI.jaxx similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialReplaceUI.jaxx rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialReplaceUI.jaxx diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialReplaceUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialReplaceUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialReplaceUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialReplaceUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialReplaceUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialReplaceUIHandler.java new file mode 100644 index 0000000..8ad5a93 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialReplaceUIHandler.java @@ -0,0 +1,40 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng; + +import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import jaxx.runtime.swing.editor.bean.BeanComboBox; + +import java.awt.Dimension; +import java.beans.PropertyChangeListener; +import java.util.List; + +/** + * Created on 11/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + */ +public class ReferentialReplaceUIHandler<R extends ReferentialDto> { + + public static final String CONTEXT_NAME = "replaceUI"; + + private final ReferentialReplaceUI<R> ui; + protected PropertyChangeListener listenData; + + public ReferentialReplaceUIHandler(ReferentialReplaceUI<R> ui) { + this.ui = ui; + this.listenData = evt -> ui.setReplaceReference((ReferentialReference) evt.getNewValue()); + } + + public void init() { + BeanComboBox<ReferentialReference<R>> beanComboBox = ui.getList(); + + beanComboBox.setI18nPrefix("observe.common."); + beanComboBox.setMinimumSize(new Dimension(0, 24)); + beanComboBox.setBeanType((Class) ReferentialReference.class); + List<ReferentialReference<R>> references = ui.getContextValue(List.class,CONTEXT_NAME); + ReferentialReferenceDecorator<R> decorator = ui.getContextValue(ReferentialReferenceDecorator.class,CONTEXT_NAME); + beanComboBox.init(decorator, references); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchroConfigUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchroConfigUI.jaxx new file mode 100644 index 0000000..ab51667 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchroConfigUI.jaxx @@ -0,0 +1,80 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<!-- ************************************************************* --> +<!-- La configuration de l'import GPS --> +<!-- ************************************************************* --> + +<JPanel id="referentialSynchronizeConfig"> + + <import> + fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig + fr.ird.observe.services.service.actions.synchro.referential.ReferentialSynchronizeMode + fr.ird.observe.application.swing.ui.admin.AdminUIModel + fr.ird.observe.application.swing.validation.ValidationModelMode + + org.nuiton.validator.NuitonValidatorScope + + java.io.File + + javax.swing.JComboBox + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + </import> + + <ReferentialSynchroUIHandler id='handler' initializer='getContextValue(ReferentialSynchroUIHandler.class)'/> + + <AdminUIModel id='model' initializer='getContextValue(AdminUIModel.class)'/> + + <ReferentialSynchroModel id='stepModel' initializer='model.getReferentialSynchroModel()'/> + + <ButtonGroup id='synchronizeMode' + onStateChanged='stepModel.setSynchronizeMode((ReferentialSynchronizeMode) synchronizeMode.getSelectedValue())'/> + + <script><![CDATA[ +public void destroy() { + model = null; + stepModel = null; +} + +@Override +protected void finalize() throws Throwable { + super.finalize(); + destroy(); +} + +]]> + </script> + + <JPanel id="referentialSynchronizeConfigPanel" constraints='BorderLayout.CENTER' layout='{new GridLayout(0, 1)}'> + <JToggleButton id="LEFT_TO_RIGHT"/> + <JToggleButton id="RIGHT_TO_LEFT"/> + <JToggleButton id="BOTH"/> + </JPanel> + <Table constraints='BorderLayout.SOUTH' weightx='1' weighty='1'> + <row> + <cell> + <JLabel/> + </cell> + </row> + </Table> + +</JPanel> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchroConfigUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchroConfigUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchroConfigUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchroConfigUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchroModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchroModel.java new file mode 100644 index 0000000..6e03cbf --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchroModel.java @@ -0,0 +1,299 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng; + +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.ReferentialReferenceSet; +import fr.ird.observe.services.service.actions.synchro.referential.ReferentialSynchronizeMode; +import fr.ird.observe.services.service.actions.synchro.referential.diff.ReferentialSynchronizeDiffsEngine; +import fr.ird.observe.services.service.actions.synchro.referential.ng.ReferentialSynchronizeService; +import fr.ird.observe.services.service.actions.synchro.referential.ng.ReferentialSynchronizeServiceEngine; +import fr.ird.observe.application.swing.ui.admin.AdminActionModel; +import fr.ird.observe.application.swing.ui.admin.AdminStep; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task.AddReferentialSynchronizeTask; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task.DeleteReferentialSynchronizeTask; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task.DesactivateReferentialSynchronizeTask; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task.ReferentialSynchronizeTaskSupport; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.ReferentialSynchronizeTreeModel; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created on 02/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class ReferentialSynchroModel extends AdminActionModel { + + public static final String LEFT_SOURCE_PROPERTY_NAME = "leftSource"; + public static final String RIGHT_SOURCE_PROPERTY_NAME = "rightSource"; + public static final String TASKS_PROPERTY_NAME = "tasks"; + public static final String SYNCHRONIZE_MODE_PROPERTY_NAME = "synchronizeMode"; + public static final String RIGHT_TREE_MODEL_PROPERTY_NAME = "rightTreeModel"; + public static final String LEFT_TREE_MODEL_PROPERTY_NAME = "lefttTreeModel"; + public static final String COPY_RIGHT_PROPERTY_NAME = "copyRight"; + public static final String COPY_LEFT_PROPERTY_NAME = "copyLeft"; + public static final String SKIP_RIGHT_PROPERTY_NAME = "skipRight"; + public static final String SKIP_LEFT_PROPERTY_NAME = "skipLeft"; + public static final String DELETE_RIGHT_PROPERTY_NAME = "deleteRight"; + public static final String DELETE_LEFT_PROPERTY_NAME = "deleteLeft"; + public static final String DESACTIVATE_RIGHT_PROPERTY_NAME = "desactivateRight"; + public static final String DESACTIVATE_LEFT_PROPERTY_NAME = "desactivateLeft"; + public static final String DESACTIVATE_WITH_REPLACE_RIGHT_PROPERTY_NAME = "desactivateWithReplaceRight"; + public static final String DESACTIVATE_WITH_REPLACE_LEFT_PROPERTY_NAME = "desactivateWithReplaceLeft"; + public static final String REVERT_RIGHT_PROPERTY_NAME = "revertRight"; + public static final String REVERT_LEFT_PROPERTY_NAME = "revertLeft"; + /** Logger. */ + private static final Log log = LogFactory.getLog(ReferentialSynchroModel.class); + private final ReferentialSynchronizeTaskListModel tasks; + private ObserveSwingDataSource leftSource; + private ObserveSwingDataSource rightSource; + private ReferentialSynchronizeMode synchronizeMode; + private ReferentialSynchronizeTreeModel leftTreeModel; + private ReferentialSynchronizeTreeModel rightTreeModel; + private ReferentialSynchronizeDiffsEngine engine; + private boolean copyLeft; + private boolean revertLeft; + private boolean skipLeft; + private boolean deleteLeft; + private boolean desactivateLeft; + private boolean desactivateWithReplaceLeft; + private boolean copyRight; + private boolean revertRight; + private boolean skipRight; + private boolean deleteRight; + private boolean desactivateRight; + private boolean desactivateWithReplaceRight; + + public ReferentialSynchroModel() { + super(AdminStep.REFERENTIAL_SYNCHRONIZE); + this.tasks = new ReferentialSynchronizeTaskListModel(); + } + + public ReferentialSynchronizeMode getSynchronizeMode() { + return synchronizeMode; + } + + public void setSynchronizeMode(ReferentialSynchronizeMode synchronizeMode) { + Object oldValue = getSynchronizeMode(); + this.synchronizeMode = synchronizeMode; + firePropertyChange(SYNCHRONIZE_MODE_PROPERTY_NAME, oldValue, synchronizeMode); + } + + public ObserveSwingDataSource getLeftSource() { + return leftSource; + } + + public void setLeftSource(ObserveSwingDataSource leftSource) { + this.leftSource = leftSource; + firePropertyChange(LEFT_SOURCE_PROPERTY_NAME, leftSource); + } + + public ObserveSwingDataSource getRightSource() { + return rightSource; + } + + public void setRightSource(ObserveSwingDataSource rightSource) { + this.rightSource = rightSource; + firePropertyChange(RIGHT_SOURCE_PROPERTY_NAME, rightSource); + } + + public ReferentialSynchronizeTreeModel getLeftTreeModel() { + return leftTreeModel; + } + + public void setLeftTreeModel(ReferentialSynchronizeTreeModel leftTreeModel) { + Object oldValue = getLeftTreeModel(); + this.leftTreeModel = leftTreeModel; + firePropertyChange(LEFT_TREE_MODEL_PROPERTY_NAME, oldValue, leftTreeModel); + } + + public ReferentialSynchronizeTreeModel getRightTreeModel() { + return rightTreeModel; + } + + public void setRightTreeModel(ReferentialSynchronizeTreeModel rightTreeModel) { + Object oldValue = getRightTreeModel(); + this.rightTreeModel = rightTreeModel; + firePropertyChange(RIGHT_TREE_MODEL_PROPERTY_NAME, oldValue, rightTreeModel); + } + + public ReferentialSynchronizeTaskListModel getTasks() { + return tasks; + } + + public void setEngine(ReferentialSynchronizeDiffsEngine engine) { + this.engine = engine; + } + + public <D extends ReferentialDto> List<ReferentialReference<D>> getPossibleReplaceUniverse(boolean left, Class<D> type, ReferentialReference<D> referenceToReplace) { + + ReferentialReferenceSet<D> referencesSet; + if (left) { + referencesSet = engine.getLeftEnabledReferentialReferenceSet(type); + } else { + referencesSet = engine.getRightEnabledReferentialReferenceSet(type); + } + + List<ReferentialReference<D>> references = new ArrayList<>(referencesSet.getReferences()); + references.remove(referenceToReplace); + + for (ReferentialSynchronizeTaskSupport task : tasks) { + + if (!type.equals(task.getType())) { + continue; + } + if (left == task.isLeft()) { + + if (task instanceof DeleteReferentialSynchronizeTask) { + + // on enlève ce référentiel car il a été supprimé de ce côté + ReferentialReference<D> referential = task.getReferential(); + references.remove(referential); + } + + if (task instanceof DesactivateReferentialSynchronizeTask) { + + // on enlève ce référentiel car il a été désactivé de ce côté + ReferentialReference<D> referential = task.getReferential(); + references.remove(referential); + } + + continue; + } + + if (type.equals(task.getType())) { + + if (task instanceof AddReferentialSynchronizeTask) { + + // on ajoute ce référentiel car il a été ajouté depuis l'autre côté + ReferentialReference<D> referential = task.getReferential(); + references.add(referential); + } + + } + + } + + return references; + } + + public boolean isCopyRight() { + return copyRight; + } + + public void setCopyRight(boolean copyRight) { + this.copyRight = copyRight; + firePropertyChange(COPY_RIGHT_PROPERTY_NAME, copyRight); + } + + public boolean isCopyLeft() { + return copyLeft; + } + + public void setCopyLeft(boolean copyLeft) { + this.copyLeft = copyLeft; + firePropertyChange(COPY_LEFT_PROPERTY_NAME, copyLeft); + } + + public boolean isRevertRight() { + return revertRight; + } + + public void setRevertRight(boolean revertRight) { + this.revertRight = revertRight; + firePropertyChange(REVERT_RIGHT_PROPERTY_NAME, revertRight); + } + + public boolean isRevertLeft() { + return revertLeft; + } + + public void setRevertLeft(boolean revertLeft) { + this.revertLeft = revertLeft; + firePropertyChange(REVERT_LEFT_PROPERTY_NAME, revertLeft); + } + + public boolean isSkipLeft() { + return skipLeft; + } + + public void setSkipLeft(boolean skipLeft) { + this.skipLeft = skipLeft; + firePropertyChange(SKIP_LEFT_PROPERTY_NAME, skipLeft); + } + + public boolean isSkipRight() { + return skipRight; + } + + public void setSkipRight(boolean skipRight) { + this.skipRight = skipRight; + firePropertyChange(SKIP_RIGHT_PROPERTY_NAME, skipRight); + } + + public boolean isDeleteLeft() { + return deleteLeft; + } + + public void setDeleteLeft(boolean deleteLeft) { + this.deleteLeft = deleteLeft; + firePropertyChange(DELETE_LEFT_PROPERTY_NAME, deleteLeft); + } + + public boolean isDeleteRight() { + return deleteRight; + } + + public void setDeleteRight(boolean deleteRight) { + this.deleteRight = deleteRight; + firePropertyChange(DELETE_RIGHT_PROPERTY_NAME, deleteRight); + } + + public boolean isDesactivateRight() { + return desactivateRight; + } + + public void setDesactivateRight(boolean desactivateRight) { + this.desactivateRight = desactivateRight; + firePropertyChange(DESACTIVATE_RIGHT_PROPERTY_NAME, desactivateRight); + } + + public boolean isDesactivateLeft() { + return desactivateLeft; + } + + public void setDesactivateLeft(boolean desactivateLeft) { + this.desactivateLeft = desactivateLeft; + firePropertyChange(DESACTIVATE_LEFT_PROPERTY_NAME, desactivateLeft); + } + + public boolean isDesactivateWithReplaceRight() { + return desactivateWithReplaceRight; + } + + public void setDesactivateWithReplaceRight(boolean desactivateWithReplaceRight) { + this.desactivateWithReplaceRight = desactivateWithReplaceRight; + firePropertyChange(DESACTIVATE_WITH_REPLACE_RIGHT_PROPERTY_NAME, desactivateWithReplaceRight); + } + + public boolean isDesactivateWithReplaceLeft() { + return desactivateWithReplaceLeft; + } + + public void setDesactivateWithReplaceLeft(boolean desactivateWithReplaceLeft) { + this.desactivateWithReplaceLeft = desactivateWithReplaceLeft; + firePropertyChange(DESACTIVATE_WITH_REPLACE_LEFT_PROPERTY_NAME, desactivateWithReplaceLeft); + } + + + public ReferentialSynchronizeServiceEngine newReferentialSynchronizeServiceEngine() { + ReferentialSynchronizeService leftService = leftSource.newReferentialSynchronizeService(); + ReferentialSynchronizeService rightService = rightSource.newReferentialSynchronizeService(); + return new ReferentialSynchronizeServiceEngine(leftService, rightService); + } +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchroUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchroUI.jaxx new file mode 100644 index 0000000..1fbff42 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchroUI.jaxx @@ -0,0 +1,144 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<!-- ************************************************************* --> +<!-- L'écran de synchronisation bi-directionnel des données --> +<!-- ************************************************************* --> + +<fr.ird.observe.application.swing.ui.admin.AdminTabUI> + + <import> + fr.ird.observe.application.swing.ui.UIHelper + fr.ird.observe.application.swing.ui.admin.AdminUI + fr.ird.observe.application.swing.ui.admin.AdminStep + fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.action.ApplyAction + fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.action.RegisterCopyTaskAction + fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.action.RegisterDeleteTaskAction + fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.action.RegisterDesactivateTaskAction + fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.action.RegisterRevertTaskAction + fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.action.RegisterSkipTaskAction + fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.ReferentialSynchronizeTreeModel + fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.ReferentialSynchronizeTreeCellRenderer + fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper + + javax.swing.ListSelectionModel + + static org.nuiton.i18n.I18n.t; + + </import> + + <ObserveTreeHelper id='leftTreeHelper'/> + <ObserveTreeHelper id='rightTreeHelper'/> + + <ReferentialSynchroUIHandler id='handler' constructorParams='this'/> + + <ReferentialSynchroModel id='stepModel' javaBean='getModel().getReferentialSynchroModel()'/> + + <ReferentialSynchronizeTreeModel id="leftTreeModel" javaBean="getStepModel().getLeftTreeModel()"/> + <ReferentialSynchronizeTreeModel id="rightTreeModel" javaBean="getStepModel().getRightTreeModel()"/> + <JPanel id='invisiblePanel'> + + </JPanel> + + <script><![CDATA[ +public ReferentialSynchroUI(AdminUI parentContext) { + super(AdminStep.REFERENTIAL_SYNCHRONIZE, parentContext); +} + +public void initUI(AdminUI ui) { + getHandler().initTabUI(ui, this); +} + +@Override +public void destroy() { + leftTreeModel.clearSelection(); + rightTreeModel.clearSelection(); + super.destroy(); +} +]]> + </script> + + <JPanel id='PENDING_content'> + <Table constraints='BorderLayout.CENTER' fill='both' weightx='1' + weighty='1'> + <row> + <cell> + <JButton id='startAction' onActionPerformed="getHandler().doStartAction()"/> + </cell> + </row> + </Table> + </JPanel> + <JPanel id='NEED_FIX_content'> + <JSplitPane id="contentSplitPane" constraints='BorderLayout.CENTER'> + <Table id='contentNorth' fill="both" weighty="1"> + <row> + <cell weightx="0.5"> + <JScrollPane id='leftTreePane'> + <JTree id='leftTree'/> + </JScrollPane> + </cell> + <cell> + <JPanel layout="{new BorderLayout()}" border='{new TitledBorder("")}'> + <JToolBar id="middleActions" layout="{new GridLayout(0, 2)}" constraints='BorderLayout.CENTER'> + <JButton id="copyLeft" opaque="true"/> + <JButton id="copyRight" opaque="true"/> + <JButton id="revertLeft" opaque="true"/> + <JButton id="revertRight" opaque="true"/> + <JButton id="desactivateLeft" opaque="false"/> + <JButton id="desactivateRight" opaque="false"/> + <JButton id="desactivateWithReplaceLeft" opaque="false"/> + <JButton id="desactivateWithReplaceRight" opaque="false"/> + <JButton id="deleteLeft" opaque="false"/> + <JButton id="deleteRight" opaque="false"/> + <JButton id="skipLeft" opaque="false"/> + <JButton id="skipRight" opaque="false"/> + </JToolBar> + </JPanel> + </cell> + <cell weightx="0.5"> + <JScrollPane id='rightTreePane'> + <JTree id='rightTree'/> + </JScrollPane> + </cell> + </row> + </Table> + <Table id='contentSouth' fill="both"> + <row weighty="1"> + <cell weightx="1"> + <JScrollPane id='actionsToConsumePane'> + <JList id="actionsToConsume"/> + </JScrollPane> + </cell> + </row> + <row> + <cell> + <JPanel layout="{new BorderLayout()}"> + <JButton id='applyAction' constraints='BorderLayout.CENTER'/> + </JPanel> + </cell> + </row> + </Table> + </JSplitPane> + + </JPanel> + +</fr.ird.observe.application.swing.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchroUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchroUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchroUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchroUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchroUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchroUIHandler.java new file mode 100644 index 0000000..6897ef5 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchroUIHandler.java @@ -0,0 +1,191 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng; + +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.service.actions.synchro.referential.ReferentialSynchronizeMode; +import fr.ird.observe.services.service.actions.synchro.referential.diff.ReferentialSynchronizeDiffService; +import fr.ird.observe.services.service.actions.synchro.referential.diff.ReferentialSynchronizeDiffsEngine; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.admin.AdminStep; +import fr.ird.observe.application.swing.ui.admin.AdminTabUIHandler; +import fr.ird.observe.application.swing.ui.admin.AdminUI; +import fr.ird.observe.application.swing.ui.admin.config.ConfigUI; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.ReferentialSynchronizeTreeModel; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.ReferentialSynchronizeTreeModelsBuilder; +import jaxx.runtime.context.JAXXInitialContext; +import jaxx.runtime.swing.wizard.ext.WizardState; +import org.apache.commons.lang3.tuple.Pair; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JScrollPane; +import javax.swing.JTree; +import javax.swing.border.TitledBorder; +import javax.swing.event.TreeSelectionListener; +import java.awt.Color; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 02/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class ReferentialSynchroUIHandler extends AdminTabUIHandler { + + /** Logger */ + private static final Log log = LogFactory.getLog(ReferentialSynchroUIHandler.class); + + private final TreeSelectionListener treeSelectionListener; + + public ReferentialSynchroUIHandler(ReferentialSynchroUI ui) { + super(ui); + this.treeSelectionListener = evt -> updateEnabledActions(); + } + + public ReferentialSynchroModel getStepModel() { + return model.getReferentialSynchroModel(); + } + + @Override + public ReferentialSynchroUI getUi() { + return (ReferentialSynchroUI) super.getUi(); + } + + public void initTabUI(AdminUI ui, ReferentialSynchroUI tabUI) { + + super.initTabUI(ui, tabUI); + + if (log.isDebugEnabled()) { + log.debug(" specialized for [" + tabUI.getStep() + "] for main ui " + ui.getClass().getName() + "@" + System.identityHashCode(ui)); + } + + ConfigUI configUI = (ConfigUI) ui.getStepUI(AdminStep.CONFIG); + JAXXInitialContext tx = new JAXXInitialContext().add(configUI).add(this); + ReferentialSynchroConfigUI extraConfig = new ReferentialSynchroConfigUI(tx); + configUI.getExtraConfig().add(extraConfig); + + } + + public void doStartAction() { + + addAdminWorker(getUi().getStartAction().getToolTipText(), this::doStartAction0); + + } + + private WizardState doStartAction0() { + + ReferentialSynchroModel stepModel = getStepModel(); + + ObserveSwingDataSource leftSource = getModel().getSafeLocalSource(true); + stepModel.setLeftSource(leftSource); + + ObserveSwingDataSource rightSource = getModel().getSafeCentralSource(true); + stepModel.setRightSource(rightSource); + + ReferentialSynchronizeDiffService leftDiffSynchronizeService = leftSource.newReferentialSynchronizeDiffService(); + ReferentialSynchronizeDiffService rightDiffSynchronizeService = rightSource.newReferentialSynchronizeDiffService(); + + ReferentialSynchronizeDiffsEngine engine = new ReferentialSynchronizeDiffsEngine(leftDiffSynchronizeService, rightDiffSynchronizeService); + stepModel.setEngine(engine); + + ReferentialSynchronizeMode synchronizeMode = stepModel.getSynchronizeMode(); + ReferentialSynchronizeTreeModelsBuilder treeModelsBuilder = new ReferentialSynchronizeTreeModelsBuilder(synchronizeMode, engine); + Pair<ReferentialSynchronizeTreeModel, ReferentialSynchronizeTreeModel> treePair = treeModelsBuilder.build(); + stepModel.setLeftTreeModel(treePair.getLeft()); + stepModel.setRightTreeModel(treePair.getRight()); + + stepModel.getTasks().removeAllElements(); + + ReferentialSynchroUI ui = getUi(); + initTree(ui.getLeftTree(), + ui.getLeftTreePane(), + stepModel.getLeftTreeModel(), + getModel().getLocalSourceModel().getLabel(), + t("observe.actions.synchro.referential.message.referential.leftData.loaded")); + + initTree(ui.getRightTree(), + ui.getRightTreePane(), + stepModel.getRightTreeModel(), + getModel().getCentralSourceModel().getLabel(), + t("observe.actions.synchro.referential.message.referential.rightData.loaded")); + + return WizardState.NEED_FIX; + + } + + private void updateEnabledActions() { + + ReferentialSynchroModel stepModel = getStepModel(); + + updateLeftTreeEnableActions(stepModel.getLeftTreeModel()); + updateRightTreeEnableActions(stepModel.getRightTreeModel()); + + } + + private void updateLeftTreeEnableActions(ReferentialSynchronizeTreeModel treeModel) { + + ReferentialSynchroModel stepModel = getStepModel(); + + treeModel.updateSelectedActions(); + stepModel.setCopyLeft(treeModel.isCanAdd() || treeModel.isCanUpdate()); + stepModel.setDeleteLeft(treeModel.isCanDelete()); + stepModel.setDesactivateLeft(treeModel.isCanDelete()); + stepModel.setDesactivateWithReplaceLeft(treeModel.isCanDelete()); + stepModel.setRevertLeft(treeModel.isCanRevert()); + stepModel.setSkipLeft(treeModel.isCanSkip()); + } + + private void updateRightTreeEnableActions(ReferentialSynchronizeTreeModel treeModel) { + + ReferentialSynchroModel stepModel = getStepModel(); + + treeModel.updateSelectedActions(); + + stepModel.setCopyRight(treeModel.isCanAdd() || treeModel.isCanUpdate()); + stepModel.setDeleteRight(treeModel.isCanDelete()); + stepModel.setDesactivateRight(treeModel.isCanDelete()); + stepModel.setDesactivateWithReplaceRight(treeModel.isCanDelete()); + stepModel.setRevertRight(treeModel.isCanRevert()); + stepModel.setSkipRight(treeModel.isCanSkip()); + } + + private void initTree(JTree tree, JScrollPane treePane, ReferentialSynchronizeTreeModel treeModel, String title, String message) { + + ReferentialSynchronizeMode newValue = getStepModel().getSynchronizeMode(); + + Color color = + (treeModel.isLeft() && newValue.isLeftWrite() || !treeModel.isLeft() && newValue.isRightWrite()) ? + Color.BLACK : Color.RED; + + TitledBorder border = new TitledBorder(title); + border.setTitleColor(color); + + treePane.setBorder(border); + tree.setModel(treeModel); + tree.setSelectionModel(treeModel); + + treeModel.removeTreeSelectionListener(treeSelectionListener); + treeModel.addTreeSelectionListener(treeSelectionListener); + + UIHelper.initUI(treePane, tree); + //UIHelper.expandTree(tree); + + sendMessage(message); + + if (treeModel.isLeft()) { + + updateLeftTreeEnableActions(treeModel); + + } else { + updateRightTreeEnableActions(treeModel); + } + + ConfigUI configUI = (ConfigUI) parentUI.getStepUI(AdminStep.CONFIG); + configUI.getLocalSourceConfig().setBorder(new TitledBorder(getModel().getLocalSourceLabel())); + configUI.getCentralSourceConfig().setBorder(new TitledBorder(getModel().getCentralSourceLabel())); + + } + + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchronizeResources.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchronizeResources.java new file mode 100644 index 0000000..f189461 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchronizeResources.java @@ -0,0 +1,161 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng; + +import fr.ird.observe.services.service.actions.synchro.referential.ng.task.ReferentialSynchronizeTaskType; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node.ReferenceReferentialSynchroNodeSupport; + +import javax.swing.Icon; +import java.util.function.Predicate; + +import static org.nuiton.i18n.I18n.n; + +/** + * Created on 12/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + */ +public enum ReferentialSynchronizeResources { + + ADD( + "copyToRight", + "copyToLeft", + n("observe.actions.synchro.referential.task.addToRight"), + n("observe.actions.synchro.referential.task.addToLeft"), + null, + null, + null, + null, + ReferentialSynchronizeTaskType.ADD, + ReferenceReferentialSynchroNodeSupport::isCanAdd), + UPDATE( + "copyToRight", + "copyToLeft", + n("observe.actions.synchro.referential.task.updateToRight"), + n("observe.actions.synchro.referential.task.updateToLeft"), + null, + null, + null, + null, + ReferentialSynchronizeTaskType.UPDATE, + ReferenceReferentialSynchroNodeSupport::isCanUpdate), + COPY( + "copyToRight", + "copyToLeft", + null, + null, + n("observe.actions.synchro.referential.action.copyToRight.tip"), + n("observe.actions.synchro.referential.action.copyToLeft.tip"), + ReferentialSynchroModel.COPY_LEFT_PROPERTY_NAME, + ReferentialSynchroModel.COPY_RIGHT_PROPERTY_NAME, + null, + node -> false), + DELETE( + "deleteFromLeft", + "deleteFromRight", + n("observe.actions.synchro.referential.task.deleteFromLeft"), + n("observe.actions.synchro.referential.task.deleteFromRight"), + n("observe.actions.synchro.referential.action.deleteFromLeft.tip"), + n("observe.actions.synchro.referential.action.deleteFromRight.tip"), + ReferentialSynchroModel.DELETE_LEFT_PROPERTY_NAME, + ReferentialSynchroModel.DELETE_RIGHT_PROPERTY_NAME, + ReferentialSynchronizeTaskType.DELETE, + ReferenceReferentialSynchroNodeSupport::isCanDelete), + REVERT( + "revertFromLeft", + "revertFromRight", + n("observe.actions.synchro.referential.task.revertFromLeft"), + n("observe.actions.synchro.referential.task.revertFromRight"), + n("observe.actions.synchro.referential.action.revertFromLeft.tip"), + n("observe.actions.synchro.referential.action.revertFromRight.tip"), + ReferentialSynchroModel.REVERT_LEFT_PROPERTY_NAME, + ReferentialSynchroModel.REVERT_RIGHT_PROPERTY_NAME, + ReferentialSynchronizeTaskType.REVERT, + ReferenceReferentialSynchroNodeSupport::isCanRevert), + SKIP( + "skipFromLeft", + "skipFromRight", + n("observe.actions.synchro.referential.task.skipFromLeft"), + n("observe.actions.synchro.referential.task.skipFromRight"), + n("observe.actions.synchro.referential.action.skipFromLeft.tip"), + n("observe.actions.synchro.referential.action.skipFromRight.tip"), + ReferentialSynchroModel.SKIP_LEFT_PROPERTY_NAME, + ReferentialSynchroModel.SKIP_RIGHT_PROPERTY_NAME, + null, + node -> true), + DESACTIVATE( + "desactivateFromLeft", + "desactivateFromRight", + n("observe.actions.synchro.referential.task.desactivateWithReplaceFromLeft"), + n("observe.actions.synchro.referential.task.desactivateWithReplaceFromRight"), + n("observe.actions.synchro.referential.action.desactivateFromLeft.tip"), + n("observe.actions.synchro.referential.action.desactivateFromRight.tip"), + ReferentialSynchroModel.DESACTIVATE_LEFT_PROPERTY_NAME, + ReferentialSynchroModel.DESACTIVATE_RIGHT_PROPERTY_NAME, + ReferentialSynchronizeTaskType.DESACTIVATE, + ReferenceReferentialSynchroNodeSupport::isCanDelete); + + private final String leftActionName; + private final String leftTaskI18nKey; + private final String rightActionName; + private final String leftActionTipI18nKey; + private final String rightTaskI18nKey; + private final String rightActionTipI18nKey; + private final String leftPropertyName; + private final String rightPropertyName; + private final Predicate<ReferenceReferentialSynchroNodeSupport> predicate; + private final ReferentialSynchronizeTaskType taskType; + private transient Icon actionIcon; + + ReferentialSynchronizeResources(String leftActionName, + String rightActionName, + String leftTaskI18nKey, + String rightTaskI18nKey, + String leftActionTipI18nKey, + String rightActionTipI18nKey, + String leftPropertyName, + String rightPropertyName, + ReferentialSynchronizeTaskType taskType, + Predicate<ReferenceReferentialSynchroNodeSupport> predicate) { + this.leftActionName = leftActionName; + this.rightActionName = rightActionName; + this.leftTaskI18nKey = leftTaskI18nKey; + this.rightTaskI18nKey = rightTaskI18nKey; + this.leftActionTipI18nKey = leftActionTipI18nKey; + this.rightActionTipI18nKey = rightActionTipI18nKey; + this.leftPropertyName = leftPropertyName; + this.rightPropertyName = rightPropertyName; + this.taskType = taskType; + this.predicate = predicate; + } + + public Predicate<ReferenceReferentialSynchroNodeSupport> getPredicate() { + return predicate; + } + + public Icon getIcon(boolean left) { + if (actionIcon == null) { + actionIcon = UIHelper.getUIManagerActionIcon(left ? leftActionName : rightActionName); + } + return actionIcon; + } + + public String getTaskLabel(boolean left) { + return left ? leftTaskI18nKey : rightTaskI18nKey; + } + + public String getActionTip(boolean left) { + return left ? leftActionTipI18nKey : rightActionTipI18nKey; + } + + public String getActionName(boolean left) { + return left ? leftActionName : rightActionName; + } + + public String getPropertyName(boolean left) { + return left ? leftPropertyName : rightPropertyName; + } + + public ReferentialSynchronizeTaskType getTaskType() { + return taskType; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchronizeTaskListCellRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchronizeTaskListCellRenderer.java new file mode 100644 index 0000000..d64eb35 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchronizeTaskListCellRenderer.java @@ -0,0 +1,29 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng; + +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task.ReferentialSynchronizeTaskSupport; + +import javax.swing.DefaultListCellRenderer; +import javax.swing.JList; +import java.awt.Component; + +/** + * Created on 03/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class ReferentialSynchronizeTaskListCellRenderer extends DefaultListCellRenderer { + + private static final long serialVersionUID = 1L; + + @Override + public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { + + ReferentialSynchronizeTaskSupport task = (ReferentialSynchronizeTaskSupport) value; + super.getListCellRendererComponent(list, "<html><body>" + task.getLabel(), index, isSelected, cellHasFocus); + setIcon(task.getIcon()); + return this; + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchronizeTaskListModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchronizeTaskListModel.java new file mode 100644 index 0000000..f011191 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/ReferentialSynchronizeTaskListModel.java @@ -0,0 +1,52 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng; + +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task.ReferentialSynchronizeTaskSupport; + +import javax.swing.DefaultListModel; +import java.util.Collection; +import java.util.Collections; +import java.util.Iterator; + +/** + * Created on 13/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class ReferentialSynchronizeTaskListModel extends DefaultListModel<ReferentialSynchronizeTaskSupport> implements Iterable<ReferentialSynchronizeTaskSupport> { + + private static final long serialVersionUID = 1L; + + private boolean tasksIsAdjusting; + + public void addTasks(Collection<ReferentialSynchronizeTaskSupport> addedTasks) { + + tasksIsAdjusting = true; + try { + int minIndex = size(); + int maxIndex = minIndex + addedTasks.size() - 1; + ensureCapacity(maxIndex); + + for (ReferentialSynchronizeTaskSupport addedTask : addedTasks) { + addElement(addedTask); + } + + super.fireIntervalAdded(this, minIndex, maxIndex); + } finally { + tasksIsAdjusting = false; + } + } + + @Override + protected void fireIntervalAdded(Object source, int index0, int index1) { + if (tasksIsAdjusting) { + return; + } + super.fireIntervalAdded(source, index0, index1); + } + + @Override + public Iterator<ReferentialSynchronizeTaskSupport> iterator() { + return Collections.list(elements()).iterator(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/ApplyAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/ApplyAction.java new file mode 100644 index 0000000..68e222d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/ApplyAction.java @@ -0,0 +1,86 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.action; + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.service.actions.synchro.referential.ReferentialSynchronizeMode; +import fr.ird.observe.services.service.actions.synchro.referential.ng.ReferentialSynchronizeServiceEngine; +import fr.ird.observe.services.service.actions.synchro.referential.ng.ReferentialSynchronizeServiceProduceSqlsRequest; +import fr.ird.observe.services.service.actions.synchro.referential.ng.ReferentialSynchronizeServiceProduceSqlsResult; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.actions.AbstractObserveAction; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchroModel; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchroUI; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchroUIHandler; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchronizeTaskListModel; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task.ReferentialSynchronizeTaskSupport; +import jaxx.runtime.swing.wizard.ext.WizardState; + +import java.awt.event.ActionEvent; +import java.util.Set; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 12/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class ApplyAction extends AbstractObserveAction { + + private static final long serialVersionUID = 1L; + + private final ReferentialSynchroUI ui; + + public ApplyAction(ReferentialSynchroUI ui) { + super(t("observe.action.apply"), UIHelper.getUIManagerActionIcon("accept")); + this.ui = ui; + } + + @Override + public void actionPerformed(ActionEvent e) { + + ui.getHandler().addAdminWorker("Application des modifications.", this::apply); + + } + + private WizardState apply() { + + ReferentialSynchroModel stepModel = ui.getStepModel(); + + ReferentialSynchroUIHandler handler = ui.getHandler(); + + ReferentialSynchronizeMode synchronizeMode = stepModel.getSynchronizeMode(); + boolean leftIsWrite = synchronizeMode.isLeftWrite(); + boolean rightIsWrite = synchronizeMode.isRightWrite(); + + Set<Class<? extends ReferentialDto>> referentialTypesInShell = stepModel.getLeftSource().newDataSourceService().getReferentialTypesInShell(); + + ReferentialSynchronizeServiceProduceSqlsRequest.Builder builder = + ReferentialSynchronizeServiceProduceSqlsRequest.builder(stepModel.getLeftTreeModel().getIdsOnlyExistingInThisSide(), + stepModel.getRightTreeModel().getIdsOnlyExistingInThisSide(), + referentialTypesInShell); + + ReferentialSynchronizeTaskListModel tasks = stepModel.getTasks(); + + for (ReferentialSynchronizeTaskSupport task : tasks) { + + String taskLabel = t("observe.actions.synchro.referential.task.prepare", task.getStripLabel()); + + handler.sendMessage(taskLabel); + + task.registerTask(builder); + + } + + ReferentialSynchronizeServiceProduceSqlsRequest produceSqlsRequests = builder.build(); + + ReferentialSynchronizeServiceEngine engine = stepModel.newReferentialSynchronizeServiceEngine(); + + ReferentialSynchronizeServiceProduceSqlsResult sqlsRequests = engine.produceSqlsRequests(produceSqlsRequests); + + engine.executeSqlRequests(sqlsRequests); + + return WizardState.SUCCESSED; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterAddTaskAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterAddTaskAction.java new file mode 100644 index 0000000..9a10836 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterAddTaskAction.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.action; + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchroUI; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task.AddReferentialSynchronizeTask; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node.ReferenceReferentialSynchroNodeSupport; + +import java.util.Collection; +import java.util.function.Predicate; + +/** + * Created on 12/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class RegisterAddTaskAction extends RegisterTasksActionSupport { + + private static final long serialVersionUID = 1L; + private transient Collection<ReferenceReferentialSynchroNodeSupport> nodes; + + public RegisterAddTaskAction(ReferentialSynchroUI ui, boolean left) { + super(ui, ReferentialSynchronizeResources.ADD, left, false); + } + + @Override + protected <R extends ReferentialDto> AddReferentialSynchronizeTask<R> createTask(boolean left, ReferentialReference<R> reference, ReferentialReference<R> replaceReference) { + return new AddReferentialSynchronizeTask<>(left, reference); + } + + @Override + protected Collection<ReferenceReferentialSynchroNodeSupport> getReferenceReferentialSynchroNodes(Predicate<ReferenceReferentialSynchroNodeSupport> predicate) { + return nodes; + } + + public void updateNodes() { + + this.nodes = super.getReferenceReferentialSynchroNodes(predicate); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterCopyTaskAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterCopyTaskAction.java new file mode 100644 index 0000000..cd1d783 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterCopyTaskAction.java @@ -0,0 +1,41 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.action; + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchroUI; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task.AddReferentialSynchronizeTask; + +/** + * Created on 12/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class RegisterCopyTaskAction extends RegisterTasksActionSupport { + + private static final long serialVersionUID = 1L; + + private final RegisterAddTaskAction addAction; + private final RegisterUpdateTaskAction updateAction; + + public RegisterCopyTaskAction(ReferentialSynchroUI ui, boolean left) { + super(ui, ReferentialSynchronizeResources.COPY, left, false); + addAction = new RegisterAddTaskAction(ui, left); + updateAction = new RegisterUpdateTaskAction(ui, left); + + } + + @Override + protected void createTasks() { + addAction.updateNodes(); + updateAction.updateNodes(); + addAction.createTasks(); + updateAction.createTasks(); + } + + @Override + protected <R extends ReferentialDto> AddReferentialSynchronizeTask<R> createTask(boolean left, ReferentialReference<R> reference, ReferentialReference<R> replaceReference) { + return new AddReferentialSynchronizeTask<>(left, reference); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterDeleteTaskAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterDeleteTaskAction.java new file mode 100644 index 0000000..db25d55 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterDeleteTaskAction.java @@ -0,0 +1,34 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.action; + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchroUI; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task.DeleteReferentialSynchronizeTask; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 12/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class RegisterDeleteTaskAction extends RegisterTasksActionSupport { + + private static final long serialVersionUID = 1L; + + public RegisterDeleteTaskAction(ReferentialSynchroUI ui, boolean left) { + super(ui, ReferentialSynchronizeResources.DELETE, left, true); + } + + @Override + protected String getReplaceTitle(ReferentialReference reference) { + return t("observe.actions.synchro.referential.replaceBeforeDelete.title", typeStr, referenceStr); + } + + @Override + protected <R extends ReferentialDto> DeleteReferentialSynchronizeTask<R> createTask(boolean left, ReferentialReference<R> reference, ReferentialReference<R> replaceReference) { + return new DeleteReferentialSynchronizeTask<>(left, reference, replaceReference); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterDesactivateTaskAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterDesactivateTaskAction.java new file mode 100644 index 0000000..49ccc49 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterDesactivateTaskAction.java @@ -0,0 +1,34 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.action; + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchroUI; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task.DesactivateReferentialSynchronizeTask; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 12/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class RegisterDesactivateTaskAction extends RegisterTasksActionSupport { + + private static final long serialVersionUID = 1L; + + public RegisterDesactivateTaskAction(ReferentialSynchroUI ui, boolean left, boolean replace) { + super(ui, ReferentialSynchronizeResources.DESACTIVATE, left, replace); + } + + @Override + protected String getReplaceTitle(ReferentialReference reference) { + return t("observe.actions.synchro.referential.replaceBeforeDesactivate.title", typeStr, referenceStr); + } + + @Override + protected <R extends ReferentialDto> DesactivateReferentialSynchronizeTask<R> createTask(boolean left, ReferentialReference<R> reference, ReferentialReference<R> replaceReference) { + return new DesactivateReferentialSynchronizeTask<>(left, reference, replaceReference); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterRevertTaskAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterRevertTaskAction.java new file mode 100644 index 0000000..826da7a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterRevertTaskAction.java @@ -0,0 +1,27 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.action; + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchroUI; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task.RevertReferentialSynchronizeTask; + +/** + * Created on 12/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class RegisterRevertTaskAction extends RegisterTasksActionSupport { + + private static final long serialVersionUID = 1L; + + public RegisterRevertTaskAction(ReferentialSynchroUI ui, boolean left) { + super(ui, ReferentialSynchronizeResources.REVERT, left, false); + } + + @Override + protected <R extends ReferentialDto> RevertReferentialSynchronizeTask<R> createTask(boolean left, ReferentialReference<R> reference, ReferentialReference<R> replaceReference) { + return new RevertReferentialSynchronizeTask<>(left, reference); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterSkipTaskAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterSkipTaskAction.java new file mode 100644 index 0000000..b3cab7b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterSkipTaskAction.java @@ -0,0 +1,27 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.action; + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchroUI; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task.SkipReferentialSynchronizeTask; + +/** + * Created on 12/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class RegisterSkipTaskAction extends RegisterTasksActionSupport { + + private static final long serialVersionUID = 1L; + + public RegisterSkipTaskAction(ReferentialSynchroUI ui, boolean left) { + super(ui, ReferentialSynchronizeResources.SKIP, left, false); + } + + @Override + protected <R extends ReferentialDto> SkipReferentialSynchronizeTask<R> createTask(boolean left, ReferentialReference<R> reference, ReferentialReference<R> replaceReference) { + return new SkipReferentialSynchronizeTask<>(left, reference); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterTasksActionSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterTasksActionSupport.java new file mode 100644 index 0000000..1fc3768 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterTasksActionSupport.java @@ -0,0 +1,190 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.action; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.actions.AbstractObserveAction; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialReplaceUI; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialReplaceUIHandler; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchroUI; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task.ReferentialSynchronizeTaskSupport; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.ReferentialSynchronizeTreeModel; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node.ReferenceReferentialSynchroNodeSupport; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import jaxx.runtime.context.JAXXInitialContext; +import org.apache.commons.lang3.NotImplementedException; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.i18n.I18n; + +import javax.swing.Action; +import javax.swing.JOptionPane; +import java.awt.event.ActionEvent; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import java.util.function.Predicate; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 12/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public abstract class RegisterTasksActionSupport extends AbstractObserveAction { + + /** Logger. */ + private static final Log log = LogFactory.getLog(RegisterTasksActionSupport.class); + + private static final long serialVersionUID = 1L; + protected final Predicate<ReferenceReferentialSynchroNodeSupport> predicate; + private final ReferentialSynchroUI ui; + private final boolean left; + private final boolean needReplace; + protected String typeStr; + protected String referenceStr; + + public RegisterTasksActionSupport(ReferentialSynchroUI ui, + ReferentialSynchronizeResources resource, + boolean left, + boolean needReplace) { + super(null, null); + String tip = resource.getActionTip(left); + if (tip != null) { + putValue(SHORT_DESCRIPTION, t(tip)); + } + String actionName = resource.getActionName(left); + if (actionName != null) { + putValue(Action.SMALL_ICON, UIHelper.getUIManagerActionIcon(actionName)); + } + this.ui = ui; + this.left = left; + this.needReplace = needReplace; + this.predicate = resource.getPredicate(); + String propertyName = resource.getPropertyName(left); + if (propertyName != null) { + ui.getModel().getReferentialSynchroModel().addPropertyChangeListener(propertyName, evt -> setEnabled((Boolean) evt.getNewValue())); + } + } + + protected abstract <R extends ReferentialDto> ReferentialSynchronizeTaskSupport<R> createTask(boolean left, ReferentialReference<R> reference, ReferentialReference<R> replaceReference); + + public boolean isLeft() { + return left; + } + + protected String getReplaceTitle(ReferentialReference reference) { + throw new NotImplementedException(""); + } + + @Override + public void actionPerformed(ActionEvent e) { + + ReferentialSynchronizeTreeModel treeModel = getTreeModel(); + + createTasks(); + + treeModel.clearSelection(); + + } + + protected void createTasks() { + createTasks(getTreeModel(), predicate); + } + + protected <R extends ReferentialDto> void createTasks(ReferentialSynchronizeTreeModel treeModel, Predicate<ReferenceReferentialSynchroNodeSupport> predicate) { + + Collection<ReferenceReferentialSynchroNodeSupport> removedNodes = new LinkedList<>(); + Collection<ReferentialSynchronizeTaskSupport> addedTasks = new LinkedList<>(); + + for (ReferenceReferentialSynchroNodeSupport node : getReferenceReferentialSynchroNodes(predicate)) { + + ReferentialReference<R> reference = node.getUserObject(); + ReferentialReference<R> replaceReference = null; + + if (needReplace) { + + Class<R> type = reference.getType(); + + List<ReferentialReference<R>> references = ui.getStepModel().getPossibleReplaceUniverse(left, type, reference); + + ReferentialReferenceDecorator<R> decorator = ObserveSwingApplicationContext.get().getDecoratorService().getReferentialReferenceDecorator(type); + + ReferentialReplaceUI<R> replaceUI = new ReferentialReplaceUI<>(new JAXXInitialContext() + .add(ReferentialReplaceUIHandler.CONTEXT_NAME, reference) + .add(ReferentialReplaceUIHandler.CONTEXT_NAME, references) + .add(ReferentialReplaceUIHandler.CONTEXT_NAME, decorator) + .add(this)); + + typeStr = t(DecoratorService.getEntityLabel(ObserveTreeHelper.TREE_NODE_PREFIX, type)); + referenceStr = ui.getHandler().getDecoratorService().getReferentialReferenceDecorator(type).toString(reference); + replaceUI.getMessage().setText(t("observe.actions.synchro.referential.replaceBefore.message", typeStr, referenceStr)); + + int response = UIHelper.askUser( + null, + t(getReplaceTitle(reference), typeStr, referenceStr), + replaceUI, + JOptionPane.WARNING_MESSAGE, + new Object[]{I18n.t("observe.choice.replace"), I18n.t("observe.choice.cancel")}, + 1); + + switch (response) { + case JOptionPane.CLOSED_OPTION: + case 1: + + break; + case 0: + replaceReference = replaceUI.getReplaceReference(); + break; + } + + if (log.isInfoEnabled()) { + log.info("replaceReference: " + replaceReference); + } + + if (replaceReference == null) { + if (log.isWarnEnabled()) { + log.warn("Skip this task, no replace referential reference selected"); + } + + continue; + } + + if (log.isInfoEnabled()) { + log.info("Selected replace referential reference: " + replaceReference); + } + + } + + ReferentialSynchronizeTaskSupport task = createTask(left, reference, replaceReference); + + if (log.isInfoEnabled()) { + log.info("Add " + task.getStripLabel()); + } + + ui.getHandler().sendMessage(task.getStripLabel()); + + removedNodes.add(node); + addedTasks.add(task); + + } + + treeModel.removeReferenceNodes(removedNodes); + ui.getStepModel().getTasks().addTasks(addedTasks); + } + + protected Collection<ReferenceReferentialSynchroNodeSupport> getReferenceReferentialSynchroNodes(Predicate<ReferenceReferentialSynchroNodeSupport> predicate) { + return getTreeModel().filterSelectedReferenceNodes(predicate); + } + + protected ReferentialSynchronizeTreeModel getTreeModel() { + return left ? ui.getStepModel().getLeftTreeModel() : ui.getStepModel().getRightTreeModel(); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterUpdateTaskAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterUpdateTaskAction.java new file mode 100644 index 0000000..e28fc3d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/action/RegisterUpdateTaskAction.java @@ -0,0 +1,43 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.action; + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchroUI; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task.UpdateReferentialSynchronizeTask; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node.ReferenceReferentialSynchroNodeSupport; + +import java.util.Collection; +import java.util.function.Predicate; + +/** + * Created on 12/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class RegisterUpdateTaskAction extends RegisterTasksActionSupport { + + private static final long serialVersionUID = 1L; + + private Collection<ReferenceReferentialSynchroNodeSupport> nodes; + + public RegisterUpdateTaskAction(ReferentialSynchroUI ui, boolean left) { + super(ui, ReferentialSynchronizeResources.UPDATE, left, false); + } + + @Override + protected <R extends ReferentialDto> UpdateReferentialSynchronizeTask<R> createTask(boolean left, ReferentialReference<R> reference, ReferentialReference<R> replaceReference) { + return new UpdateReferentialSynchronizeTask<>(left, reference); + } + + @Override + protected Collection<ReferenceReferentialSynchroNodeSupport> getReferenceReferentialSynchroNodes(Predicate<ReferenceReferentialSynchroNodeSupport> predicate) { + return nodes; + } + + public void updateNodes() { + this.nodes = super.getReferenceReferentialSynchroNodes(predicate); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/AddReferentialSynchronizeTask.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/AddReferentialSynchronizeTask.java new file mode 100644 index 0000000..8bb9191 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/AddReferentialSynchronizeTask.java @@ -0,0 +1,19 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task; + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; + +/** + * Created on 09/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class AddReferentialSynchronizeTask<R extends ReferentialDto> extends ReferentialSynchronizeTaskSupport<R> { + + public AddReferentialSynchronizeTask(boolean left, ReferentialReference<R> data) { + super(ReferentialSynchronizeResources.ADD, left, data); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/DeleteReferentialSynchronizeTask.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/DeleteReferentialSynchronizeTask.java new file mode 100644 index 0000000..916becc --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/DeleteReferentialSynchronizeTask.java @@ -0,0 +1,19 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task; + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; + +/** + * Created on 09/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class DeleteReferentialSynchronizeTask<R extends ReferentialDto> extends ReferentialSynchronizeTaskWithReplaceSupport<R> { + + public DeleteReferentialSynchronizeTask(boolean left, ReferentialReference<R> data, ReferentialReference<R> replaceData) { + super(ReferentialSynchronizeResources.DELETE, left, data, replaceData); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/DesactivateReferentialSynchronizeTask.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/DesactivateReferentialSynchronizeTask.java new file mode 100644 index 0000000..9833341 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/DesactivateReferentialSynchronizeTask.java @@ -0,0 +1,40 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task; + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 09/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class DesactivateReferentialSynchronizeTask<R extends ReferentialDto> extends ReferentialSynchronizeTaskWithReplaceSupport<R> { + + private final String withoutReplaceI18nKey; + + public DesactivateReferentialSynchronizeTask(boolean left, ReferentialReference<R> data, ReferentialReference<R> replaceData) { + super(ReferentialSynchronizeResources.DESACTIVATE, left, data, replaceData); + + withoutReplaceI18nKey = left + ? n("observe.actions.synchro.referential.task.desactivateFromLeft") + : n("observe.actions.synchro.referential.task.desactivateFromRight"); + } + + @Override + public String getLabel() { + if (replaceDataStr == null) { + + // sans remplacement + return t(withoutReplaceI18nKey, typeStr, dataStr); + + } else { + + return super.getLabel(); + } + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/ReferentialSynchronizeTaskSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/ReferentialSynchronizeTaskSupport.java new file mode 100644 index 0000000..abdd351 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/ReferentialSynchronizeTaskSupport.java @@ -0,0 +1,79 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.service.actions.synchro.referential.ng.ReferentialSynchronizeServiceProduceSqlsRequest; +import fr.ird.observe.services.service.actions.synchro.referential.ng.task.ReferentialSynchronizeTaskType; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; + +import javax.swing.Icon; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 03/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public abstract class ReferentialSynchronizeTaskSupport<R extends ReferentialDto> { + + protected final String dataStr; + protected final String typeStr; + protected final String i18nKey; + private final ReferentialReference<R> referential; + private final Icon icon; + private final boolean left; + private final ReferentialSynchronizeTaskType taskType; + + protected ReferentialSynchronizeTaskSupport(ReferentialSynchronizeResources resource, + boolean left, + ReferentialReference<R> referential) { + this.left = left; + this.referential = referential; + this.icon = resource.getIcon(left); + this.i18nKey = resource.getTaskLabel(left); + this.taskType = resource.getTaskType(); + this.dataStr = ObserveSwingApplicationContext.get().getDecoratorService().getReferentialReferenceDecorator(referential.getType()).toString(referential); + this.typeStr = t(DecoratorService.getEntityLabel(referential.getType())); + } + + public boolean isLeft() { + return left; + } + + public ReferentialSynchronizeTaskType getTaskType() { + return taskType; + } + + public String getLabel() { + return t(i18nKey, typeStr, dataStr); + } + + public String getStripLabel() { + return getLabel().replaceAll("<[^>]+>", ""); + } + + public Class<R> getType() { + return referential.getType(); + } + + public String getId() { + return referential.getId(); + } + + public ReferentialReference<R> getReferential() { + return referential; + } + + public Icon getIcon() { + return icon; + } + + public void registerTask(ReferentialSynchronizeServiceProduceSqlsRequest.Builder builder) { + builder.addTask(isLeft(), taskType, getType(), getId(), null); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/ReferentialSynchronizeTaskWithReplaceSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/ReferentialSynchronizeTaskWithReplaceSupport.java new file mode 100644 index 0000000..4b481f8 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/ReferentialSynchronizeTaskWithReplaceSupport.java @@ -0,0 +1,39 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.service.actions.synchro.referential.ng.ReferentialSynchronizeServiceProduceSqlsRequest; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 11/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + */ +public abstract class ReferentialSynchronizeTaskWithReplaceSupport<R extends ReferentialDto> extends ReferentialSynchronizeTaskSupport<R> { + + protected final String replaceDataStr; + private final ReferentialReference<R> replaceData; + + protected ReferentialSynchronizeTaskWithReplaceSupport(ReferentialSynchronizeResources resource, boolean left, ReferentialReference<R> data, ReferentialReference<R> replaceData) { + super(resource, left, data); + this.replaceData = replaceData; + this.replaceDataStr = replaceData == null ? null : ObserveSwingApplicationContext.get().getDecoratorService().getReferentialReferenceDecorator(replaceData.getType()).toString(replaceData); + } + + public String getReplaceId() { + return replaceData == null ? null : replaceData.getId(); + } + + @Override + public String getLabel() { + return t(i18nKey, typeStr, dataStr, replaceDataStr); + } + + public void registerTask(ReferentialSynchronizeServiceProduceSqlsRequest.Builder builder) { + builder.addTask(isLeft(), getTaskType(), getType(), getId(), getReplaceId()); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/RevertReferentialSynchronizeTask.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/RevertReferentialSynchronizeTask.java new file mode 100644 index 0000000..4bc07ab --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/RevertReferentialSynchronizeTask.java @@ -0,0 +1,19 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task; + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; + +/** + * Created on 09/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class RevertReferentialSynchronizeTask<R extends ReferentialDto> extends ReferentialSynchronizeTaskSupport<R> { + + public RevertReferentialSynchronizeTask(boolean left, ReferentialReference<R> data) { + super(ReferentialSynchronizeResources.REVERT, left, data); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/SkipReferentialSynchronizeTask.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/SkipReferentialSynchronizeTask.java new file mode 100644 index 0000000..2bd26f0 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/SkipReferentialSynchronizeTask.java @@ -0,0 +1,24 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task; + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.service.actions.synchro.referential.ng.ReferentialSynchronizeServiceProduceSqlsRequest; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; + +/** + * Created on 09/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class SkipReferentialSynchronizeTask<R extends ReferentialDto> extends ReferentialSynchronizeTaskSupport<R> { + + public SkipReferentialSynchronizeTask(boolean left, ReferentialReference<R> data) { + super(ReferentialSynchronizeResources.SKIP, left, data); + } + + @Override + public void registerTask(ReferentialSynchronizeServiceProduceSqlsRequest.Builder builder) { + // Skip! + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/UpdateReferentialSynchronizeTask.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/UpdateReferentialSynchronizeTask.java new file mode 100644 index 0000000..a96dbfd --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/task/UpdateReferentialSynchronizeTask.java @@ -0,0 +1,19 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.task; + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; + +/** + * Created on 09/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class UpdateReferentialSynchronizeTask<R extends ReferentialDto> extends ReferentialSynchronizeTaskSupport<R> { + + public UpdateReferentialSynchronizeTask(boolean left, ReferentialReference<R> data) { + super(ReferentialSynchronizeResources.UPDATE, left, data); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/ReferentialSynchronizeTreeCellRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/ReferentialSynchronizeTreeCellRenderer.java new file mode 100644 index 0000000..6bd5073 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/ReferentialSynchronizeTreeCellRenderer.java @@ -0,0 +1,122 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node.ReferenceReferentialSynchroNodeSupport; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node.ReferentialSynchroNodeSupport; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node.TypeReferentialSynchroNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.decorator.Decorator; + +import javax.swing.Icon; +import javax.swing.JTree; +import javax.swing.tree.DefaultTreeCellRenderer; +import java.awt.Color; +import java.awt.Component; + +import static org.nuiton.i18n.I18n.t; + +/** + * Le renderer pour décorer l'arbre de sélection des données. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.2 + */ +public class ReferentialSynchronizeTreeCellRenderer extends DefaultTreeCellRenderer { + + /** Logger */ + private static final Log log = LogFactory.getLog(ReferentialSynchronizeTreeCellRenderer.class); + + private static final long serialVersionUID = 1L; + + protected transient DecoratorService decoratorService; + + public ReferentialSynchronizeTreeCellRenderer() { + + setBackgroundNonSelectionColor(null); + setBackgroundSelectionColor(null); + setBackground(null); + + setTextNonSelectionColor(Color.BLACK); + setTextSelectionColor(Color.BLUE); + } + + public DecoratorService getDecoratorService() { + if (decoratorService == null) { + decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); + } + return decoratorService; + } + + @Override + public Component getTreeCellRendererComponent( + JTree tree, + Object value, + boolean sel, + boolean expanded, + boolean leaf, + int row, + boolean hasFocus) { + + if (!(value instanceof ReferentialSynchroNodeSupport)) { + return this; + } + + // get the icon to set for the node + ReferentialSynchroNodeSupport node = (ReferentialSynchroNodeSupport) value; + + String text = null; + Icon icon = null; + if (node instanceof TypeReferentialSynchroNode) { + TypeReferentialSynchroNode node1 = (TypeReferentialSynchroNode) node; + icon = node1.getIcon(); + text = "<html><body>" + t(DecoratorService.getEntityLabel(ObserveTreeHelper.TREE_NODE_PREFIX, node1.getUserObject())); + int childCount = node1.getChildCount(); + text += " <i>(" + childCount + ")</i>"; + } else if (node instanceof ReferenceReferentialSynchroNodeSupport) { + ReferenceReferentialSynchroNodeSupport node1 = (ReferenceReferentialSynchroNodeSupport) node; + + icon = node1.getIcon(); + ReferentialReference reference = node1.getUserObject(); + Decorator<?> decorator = getDecoratorService().getReferentialReferenceDecorator(reference.getType()); + text = "<html><body>" + decorator.toString(reference); + text += " <i>(" + reference.getVersion() + " - " + reference.getLastUpdateDate() + ")</i>"; + } + + Component comp = super.getTreeCellRendererComponent(tree, text, sel, expanded, leaf, row, hasFocus); + + setIcon(icon); + setToolTipText(text); + return comp; + } + + @Override + public Color getBackgroundNonSelectionColor() { + // Fixes http://forge.codelutin.com/issues/830 for jdk 7 + return Color.WHITE; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/ReferentialSynchronizeTreeModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/ReferentialSynchronizeTreeModel.java new file mode 100644 index 0000000..92993e5 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/ReferentialSynchronizeTreeModel.java @@ -0,0 +1,393 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.ImmutableSetMultimap; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node.ReferenceReferentialSynchroNodeSupport; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node.ReferentialSynchroNodeSupport; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node.RootReferentialSynchroNode; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node.TypeReferentialSynchroNode; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.event.TreeModelListener; +import javax.swing.event.TreeSelectionListener; +import javax.swing.tree.DefaultTreeModel; +import javax.swing.tree.DefaultTreeSelectionModel; +import javax.swing.tree.RowMapper; +import javax.swing.tree.TreeModel; +import javax.swing.tree.TreePath; +import javax.swing.tree.TreeSelectionModel; +import java.beans.PropertyChangeListener; +import java.io.Serializable; +import java.util.Collection; +import java.util.Enumeration; +import java.util.LinkedList; +import java.util.function.Predicate; + +/** + * Created on 10/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + */ +public class ReferentialSynchronizeTreeModel implements TreeSelectionModel, TreeModel, Serializable { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(ReferentialSynchronizeTreeModel.class); + + private final DefaultTreeSelectionModel treeSelectionModel; + private final DefaultTreeModel treeModel; + private final ImmutableSetMultimap<Class<? extends ReferentialDto>, String> idsOnlyExistOnThisSide; + + private boolean canAdd; + private boolean canUpdate; + private boolean canDelete; + private boolean canRevert; + private boolean valueIsAdjusting; + + public ReferentialSynchronizeTreeModel(RootReferentialSynchroNode root, + ImmutableSetMultimap<Class<? extends ReferentialDto>, String> idsOnlyExistOnThisSide) { + this.treeModel = new DefaultTreeModel(root); + this.idsOnlyExistOnThisSide = idsOnlyExistOnThisSide; + this.treeSelectionModel = new DefaultTreeSelectionModel(); + setSelectionMode(DISCONTIGUOUS_TREE_SELECTION); + } + + public ImmutableSetMultimap<Class<? extends ReferentialDto>, String> getIdsOnlyExistingInThisSide() { + return idsOnlyExistOnThisSide; + } + + + public synchronized void updateSelectedActions() { + + canAdd = canUpdate = canDelete = canRevert = false; + + for (TreePath selectionPath : getSelectionPaths()) { + ReferentialSynchroNodeSupport lastPathComponent = (ReferentialSynchroNodeSupport) selectionPath.getLastPathComponent(); + + if (lastPathComponent instanceof ReferenceReferentialSynchroNodeSupport) { + + ReferenceReferentialSynchroNodeSupport node = (ReferenceReferentialSynchroNodeSupport) lastPathComponent; + canAdd |= node.isCanAdd(); + canUpdate |= node.isCanUpdate(); + canDelete |= node.isCanDelete(); + canRevert |= node.isCanRevert(); + + } + + } + + } + + public Collection<ReferenceReferentialSynchroNodeSupport> filterSelectedReferenceNodes(Predicate<ReferenceReferentialSynchroNodeSupport> predicate) { + + ImmutableSet.Builder<ReferenceReferentialSynchroNodeSupport> builder = ImmutableSet.builder(); + + for (TreePath selectionPath : getSelectionPaths()) { + ReferentialSynchroNodeSupport lastPathComponent = (ReferentialSynchroNodeSupport) selectionPath.getLastPathComponent(); + if (lastPathComponent instanceof ReferenceReferentialSynchroNodeSupport) { + ReferenceReferentialSynchroNodeSupport node = (ReferenceReferentialSynchroNodeSupport) lastPathComponent; + if (predicate.test(node)) { + builder.add(node); + } + } + } + return builder.build(); + } + + public boolean isCanAdd() { + return canAdd; + } + + public boolean isCanUpdate() { + return canUpdate; + } + + public boolean isCanDelete() { + return canDelete; + } + + public boolean isCanRevert() { + return canRevert; + } + + public boolean isCanSkip() { + return getSelectionCount() > 0; + } + + public boolean isLeft() { + return getRoot().isLeft(); + } + + public void removeReferenceNode(ReferenceReferentialSynchroNodeSupport node) { + + TypeReferentialSynchroNode parent = node.getParent(); + treeModel.removeNodeFromParent(node); + if (parent.isLeaf()) { + treeModel.removeNodeFromParent(parent); + } else { + treeModel.reload(parent); + } + } + + @Override + public RootReferentialSynchroNode getRoot() { + return (RootReferentialSynchroNode) treeModel.getRoot(); + } + + @Override + public Object getChild(Object parent, int index) { + return treeModel.getChild(parent, index); + } + + @Override + public int getChildCount(Object parent) { + return treeModel.getChildCount(parent); + } + + @Override + public boolean isLeaf(Object node) { + return treeModel.isLeaf(node); + } + + @Override + public void valueForPathChanged(TreePath path, Object newValue) { + treeModel.valueForPathChanged(path, newValue); + } + + @Override + public int getIndexOfChild(Object parent, Object child) { + return treeModel.getIndexOfChild(parent, child); + } + + @Override + public void addTreeModelListener(TreeModelListener l) { + treeModel.addTreeModelListener(l); + } + + @Override + public void removeTreeModelListener(TreeModelListener l) { + treeModel.removeTreeModelListener(l); + } + + @Override + public int getSelectionMode() { + return treeSelectionModel.getSelectionMode(); + } + + @Override + public void setSelectionMode(int mode) { + treeSelectionModel.setSelectionMode(mode); + } + + @Override + public void addSelectionPath(TreePath path) { + addSelectionPaths(path); + } + + @Override + public void removeSelectionPath(TreePath path) { + removeSelectionPaths(path); + } + + @Override + public void addSelectionPaths(TreePath... paths) { + + valueIsAdjusting = true; + + try { + Collection<TreePath> collectedPaths = new LinkedList<>(); + + collectPaths(collectedPaths, paths); + + if (log.isDebugEnabled()) { + log.debug("path(s) to add: " + collectedPaths.size()); + } + treeSelectionModel.addSelectionPaths(collectedPaths.toArray(new TreePath[collectedPaths.size()])); + } finally { + + valueIsAdjusting = false; + + } + } + + @Override + public void removeSelectionPaths(TreePath... paths) { + + if (valueIsAdjusting) { + return; + } + + valueIsAdjusting = true; + + try { + Collection<TreePath> collectedPaths = new LinkedList<>(); + + collectPaths(collectedPaths, paths); + + if (log.isDebugEnabled()) { + log.debug("path(s) to remove: " + collectedPaths.size()); + } + treeSelectionModel.removeSelectionPaths(collectedPaths.toArray(new TreePath[collectedPaths.size()])); + } finally { + + valueIsAdjusting = false; + + } + + } + + @Override + public TreePath getSelectionPath() { + return treeSelectionModel.getSelectionPath(); + } + + @Override + public void setSelectionPath(TreePath path) { + + if (isPathSelected(path)) { + removeSelectionPaths(path); + } else { + addSelectionPaths(path); + } + + } + + @Override + public TreePath[] getSelectionPaths() { + return treeSelectionModel.getSelectionPaths(); + } + + @Override + public void setSelectionPaths(TreePath[] paths) { + treeSelectionModel.setSelectionPaths(paths); + } + + @Override + public int getSelectionCount() { + return treeSelectionModel.getSelectionCount(); + } + + @Override + public boolean isPathSelected(TreePath path) { + return treeSelectionModel.isPathSelected(path); + } + + @Override + public boolean isSelectionEmpty() { + return treeSelectionModel.isSelectionEmpty(); + } + + @Override + public void clearSelection() { + treeSelectionModel.clearSelection(); + } + + @Override + public RowMapper getRowMapper() { + return treeSelectionModel.getRowMapper(); + } + + @Override + public void setRowMapper(RowMapper newMapper) { + treeSelectionModel.setRowMapper(newMapper); + } + + @Override + public int[] getSelectionRows() { + return treeSelectionModel.getSelectionRows(); + } + + @Override + public int getMinSelectionRow() { + return treeSelectionModel.getMinSelectionRow(); + } + + @Override + public int getMaxSelectionRow() { + return treeSelectionModel.getMaxSelectionRow(); + } + + @Override + public boolean isRowSelected(int row) { + return treeSelectionModel.isRowSelected(row); + } + + @Override + public void resetRowSelection() { + treeSelectionModel.resetRowSelection(); + } + + @Override + public int getLeadSelectionRow() { + return treeSelectionModel.getLeadSelectionRow(); + } + + @Override + public TreePath getLeadSelectionPath() { + return treeSelectionModel.getLeadSelectionPath(); + } + + @Override + public void addPropertyChangeListener(PropertyChangeListener listener) { + treeSelectionModel.addPropertyChangeListener(listener); + } + + @Override + public void removePropertyChangeListener(PropertyChangeListener listener) { + treeSelectionModel.removePropertyChangeListener(listener); + } + + @Override + public void addTreeSelectionListener(TreeSelectionListener x) { + treeSelectionModel.addTreeSelectionListener(x); + } + + @Override + public void removeTreeSelectionListener(TreeSelectionListener x) { + treeSelectionModel.removeTreeSelectionListener(x); + } + + private void collectPaths(Collection<TreePath> collectedPaths, TreePath... paths) { + for (TreePath path : paths) { + + collectedPaths.add(path); + + Object node = path.getLastPathComponent(); + + if (node instanceof TypeReferentialSynchroNode) { + TypeReferentialSynchroNode node1 = (TypeReferentialSynchroNode) node; + + Enumeration children = node1.children(); + while (children.hasMoreElements()) { + ReferenceReferentialSynchroNodeSupport childNode = (ReferenceReferentialSynchroNodeSupport) children.nextElement(); + collectedPaths.add(path.pathByAddingChild(childNode)); + } + + } + + } + + } + + public void removeReferenceNodes(Collection<ReferenceReferentialSynchroNodeSupport> removedNodes) { + + valueIsAdjusting = true; + + try { + for (ReferenceReferentialSynchroNodeSupport removedNode : removedNodes) { + TypeReferentialSynchroNode typeNode = removedNode.getParent(); + if (typeNode.getChildCount() == 1) { + treeModel.removeNodeFromParent(typeNode); + } else { + treeModel.removeNodeFromParent(removedNode); + } + } + } finally { + valueIsAdjusting = false; + } + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/ReferentialSynchronizeTreeModelsBuilder.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/ReferentialSynchronizeTreeModelsBuilder.java new file mode 100644 index 0000000..9076bbd --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/ReferentialSynchronizeTreeModelsBuilder.java @@ -0,0 +1,171 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.ImmutableSetMultimap; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.ReferentialReferenceSet; +import fr.ird.observe.services.service.actions.synchro.referential.ReferentialSynchronizeMode; +import fr.ird.observe.services.service.actions.synchro.referential.diff.ReferentialSynchronizeDiff; +import fr.ird.observe.services.service.actions.synchro.referential.diff.ReferentialSynchronizeDiffState; +import fr.ird.observe.services.service.actions.synchro.referential.diff.ReferentialSynchronizeDiffs; +import fr.ird.observe.services.service.actions.synchro.referential.diff.ReferentialSynchronizeDiffsEngine; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node.AddedReferenceReferentialSynchroNode; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node.ReferenceReferentialSynchroNodeSupport; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node.RootReferentialSynchroNode; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node.TypeReferentialSynchroNode; +import fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node.UpdatedReferenceReferentialSynchroNode; +import org.apache.commons.lang3.tuple.Pair; + +import java.util.Objects; +import java.util.Optional; + +/** + * Created on 11/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + */ +public class ReferentialSynchronizeTreeModelsBuilder { + + private final ReferentialSynchronizeDiffsEngine engine; + private final RootReferentialSynchroNode leftRootNode; + private final RootReferentialSynchroNode rightRootNode; + private final ImmutableSetMultimap.Builder<Class<? extends ReferentialDto>, String> leftIdsBuilder = ImmutableSetMultimap.builder(); + private final ImmutableSetMultimap.Builder<Class<? extends ReferentialDto>, String> rightIdsBuilder = ImmutableSetMultimap.builder(); + + public ReferentialSynchronizeTreeModelsBuilder(ReferentialSynchronizeMode synchronizeMode, ReferentialSynchronizeDiffsEngine engine) { + Objects.nonNull(synchronizeMode); + Objects.nonNull(engine); + this.engine = engine; + this.leftRootNode = new RootReferentialSynchroNode(true, synchronizeMode.isLeftWrite()); + this.rightRootNode = new RootReferentialSynchroNode(false, synchronizeMode.isRightWrite()); + } + + public Pair<ReferentialSynchronizeTreeModel, ReferentialSynchronizeTreeModel> build() { + + ReferentialSynchronizeDiffs synchronizeDiffs = engine.build(); + + ImmutableSet<Class<? extends ReferentialDto>> referentialNames = synchronizeDiffs.getReferentialNames(); + + ReferentialSynchronizeDiff leftDiff = synchronizeDiffs.getLeftDiff(); + ReferentialSynchronizeDiff rightDiff = synchronizeDiffs.getRightDiff(); + + boolean rightCanWrite = rightRootNode.isCanWrite(); + boolean leftCanWrite = leftRootNode.isCanWrite(); + + CreateAddNode leftAddNode = new CreateAddNode(rightCanWrite, leftCanWrite, false); + CreateAddNode rightAddNode = new CreateAddNode(leftCanWrite, rightCanWrite, false); + CreateNode leftUpdateNode = new CreateUpdateNode(rightCanWrite, false, leftCanWrite); + CreateNode rightUpdateNode = new CreateUpdateNode(leftCanWrite, false, rightCanWrite); + + for (Class<? extends ReferentialDto> referentialName : referentialNames) { + + { + // Tous les référentiels ajoutés à gauche peuvent être copié à droite + Optional<ImmutableSet<ReferentialSynchronizeDiffState>> optionalDiffStates = leftDiff.getAddedReferentials(referentialName); + if (optionalDiffStates.isPresent()) { + addFromLeft(leftRootNode, optionalDiffStates.get(), referentialName, leftAddNode); + } + } + { + // Tous les référentiels mises à jour à gauche peuvent être copié à droite + Optional<ImmutableSet<ReferentialSynchronizeDiffState>> optionalDiffStates = leftDiff.getUpdatedReferentials(referentialName); + if (optionalDiffStates.isPresent()) { + addFromLeft(leftRootNode, optionalDiffStates.get(), referentialName, leftUpdateNode); + } + } + { + // Tous les référentiels ajoutés à droite peuvent être supprimé ou désactivés + Optional<ImmutableSet<ReferentialSynchronizeDiffState>> optionalDiffStates = rightDiff.getAddedReferentials(referentialName); + if (optionalDiffStates.isPresent()) { + addFromRight(rightRootNode, optionalDiffStates.get(), referentialName, rightAddNode); + } + } + { + // Tous les référentiels mises à jour à droite peuvent être remis en arrière + Optional<ImmutableSet<ReferentialSynchronizeDiffState>> optionalDiffStates = rightDiff.getUpdatedReferentials(referentialName); + if (optionalDiffStates.isPresent()) { + addFromRight(rightRootNode, optionalDiffStates.get(), referentialName, rightUpdateNode); + } + } + + } + + ReferentialSynchronizeTreeModel leftTreeModel = new ReferentialSynchronizeTreeModel(leftRootNode, leftAddNode.getIds()); + ReferentialSynchronizeTreeModel rightTreeModel = new ReferentialSynchronizeTreeModel(rightRootNode, rightAddNode.getIds()); + return Pair.of(leftTreeModel, rightTreeModel); + + } + + private <R extends ReferentialDto> void addFromLeft(RootReferentialSynchroNode rootNode, ImmutableSet<ReferentialSynchronizeDiffState> diffStates, Class<R> referentialName, CreateNode createNode) { + ReferentialReferenceSet<R> referenceSet = engine.getLeftReferentialReferenceSet(referentialName, diffStates); + ImmutableSet<ReferentialReference<R>> references = referenceSet.getReferences(); + if (!references.isEmpty()) { + TypeReferentialSynchroNode typeNode = rootNode.getOrAddTypeNode(referentialName); + for (ReferentialReference<R> reference : references) { + createNode.createNode(typeNode, reference); + } + + } + } + + private <R extends ReferentialDto> void addFromRight(RootReferentialSynchroNode rootNode, ImmutableSet<ReferentialSynchronizeDiffState> diffStates, Class<R> referentialName, CreateNode createNode) { + ReferentialReferenceSet<R> referenceSet = engine.getRightReferentialReferenceSet(referentialName, diffStates); + ImmutableSet<ReferentialReference<R>> references = referenceSet.getReferences(); + if (!references.isEmpty()) { + TypeReferentialSynchroNode typeNode = rootNode.getOrAddTypeNode(referentialName); + for (ReferentialReference<R> reference : references) { + createNode.createNode(typeNode, reference); + } + } + } + + private static abstract class CreateNode { + + protected final boolean canCopy; + protected final boolean canDelete; + protected final boolean canRevert; + + protected CreateNode(boolean canCopy, boolean canDelete, boolean canRevert) { + this.canCopy = canCopy; + this.canDelete = canDelete; + this.canRevert = canRevert; + } + + public abstract void createNode(TypeReferentialSynchroNode typeNode, ReferentialReference<?> reference); + + } + + private static class CreateAddNode extends CreateNode { + + private final ImmutableSetMultimap.Builder<Class<? extends ReferentialDto>, String> idsBuilder = ImmutableSetMultimap.builder(); + + protected CreateAddNode(boolean canCopy, boolean canDelete, boolean canRevert) { + super(canCopy, canDelete, canRevert); + } + + @Override + public void createNode(TypeReferentialSynchroNode typeNode, ReferentialReference<?> reference) { + ReferenceReferentialSynchroNodeSupport node = new AddedReferenceReferentialSynchroNode(reference, canCopy, false, canDelete, canRevert); + typeNode.add(node); + idsBuilder.put(reference.getType(), reference.getId()); + } + + public ImmutableSetMultimap<Class<? extends ReferentialDto>, String> getIds() { + return idsBuilder.build(); + } + } + + private static class CreateUpdateNode extends CreateNode { + + protected CreateUpdateNode(boolean canCopy, boolean canDelete, boolean canRevert) { + super(canCopy, canDelete, canRevert); + } + + @Override + public void createNode(TypeReferentialSynchroNode typeNode, ReferentialReference<?> reference) { + ReferenceReferentialSynchroNodeSupport node = new UpdatedReferenceReferentialSynchroNode(reference, false, canCopy, canDelete, canRevert); + typeNode.add(node); + } + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/node/AddedReferenceReferentialSynchroNode.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/node/AddedReferenceReferentialSynchroNode.java new file mode 100644 index 0000000..bee942c --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/node/AddedReferenceReferentialSynchroNode.java @@ -0,0 +1,20 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node; + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; + +/** + * Created on 11/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + */ +public class AddedReferenceReferentialSynchroNode extends ReferenceReferentialSynchroNodeSupport { + + private static final long serialVersionUID = 1L; + + public AddedReferenceReferentialSynchroNode(ReferentialReference<? extends ReferentialDto> referentialReference, boolean canAdd, boolean canUpdate, boolean canDelete, boolean canRevert) { + super(referentialReference, "synchroAdd", canAdd, canUpdate, canDelete, canRevert); + } + + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/node/ReferenceReferentialSynchroNodeSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/node/ReferenceReferentialSynchroNodeSupport.java new file mode 100644 index 0000000..c2e4672 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/node/ReferenceReferentialSynchroNodeSupport.java @@ -0,0 +1,61 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node; + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.UIHelper; + +/** + * Created on 09/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public abstract class ReferenceReferentialSynchroNodeSupport extends ReferentialSynchroNodeSupport { + + private static final long serialVersionUID = 1L; + + private final boolean canAdd; + private final boolean canUpdate; + private final boolean canDelete; + private final boolean canRevert; + + protected ReferenceReferentialSynchroNodeSupport(ReferentialReference<? extends ReferentialDto> referentialReference, + String iconName, + boolean canAdd, + boolean canUpdate, + boolean canDelete, + boolean canRevert) { + super(UIHelper.createActionIcon(iconName), referentialReference); + this.canAdd = canAdd; + this.canUpdate = canUpdate; + this.canDelete = canDelete; + this.canRevert = canRevert; + } + + public boolean isCanAdd() { + return canAdd; + } + + public boolean isCanUpdate() { + return canUpdate; + } + + public boolean isCanDelete() { + return canDelete; + } + + public boolean isCanRevert() { + return canRevert; + } + + @Override + public TypeReferentialSynchroNode getParent() { + return (TypeReferentialSynchroNode) super.getParent(); + } + + @Override + public ReferentialReference getUserObject() { + return (ReferentialReference) super.getUserObject(); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/node/ReferentialSynchroNodeSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/node/ReferentialSynchroNodeSupport.java new file mode 100644 index 0000000..ee480c6 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/node/ReferentialSynchroNodeSupport.java @@ -0,0 +1,38 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node; + +import javax.swing.Icon; +import javax.swing.tree.DefaultMutableTreeNode; + +/** + * Created on 09/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + */ +public abstract class ReferentialSynchroNodeSupport extends DefaultMutableTreeNode { + + private static final long serialVersionUID = 1L; + + private transient Icon icon; + + protected ReferentialSynchroNodeSupport(Icon icon, Object userObject) { + setUserObject(userObject); + this.icon = icon; + } + + public Icon getIcon() { + return icon; + } + + public boolean isLeft() { + return getRoot().isLeaf(); + } + + public boolean isRight() { + return !isLeft(); + } + + @Override + public ReferentialSynchroNodeSupport getParent() { + return (ReferentialSynchroNodeSupport) super.getParent(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/node/RootReferentialSynchroNode.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/node/RootReferentialSynchroNode.java new file mode 100644 index 0000000..89b3d92 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/node/RootReferentialSynchroNode.java @@ -0,0 +1,55 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node; + +import fr.ird.observe.services.dto.referential.ReferentialDto; + +import java.util.Enumeration; + +/** + * Created on 10/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class RootReferentialSynchroNode extends ReferentialSynchroNodeSupport { + + private static final long serialVersionUID = 1L; + + private final boolean left; + private final boolean canWrite; + + public RootReferentialSynchroNode(boolean left, boolean canWrite) { + super(null, null); + this.left = left; + this.canWrite = canWrite; + } + + @Override + public boolean isLeft() { + return left; + } + + public boolean isCanWrite() { + return canWrite; + } + + public <R extends ReferentialDto> TypeReferentialSynchroNode getOrAddTypeNode(Class<R> referentialName) { + TypeReferentialSynchroNode node = getChild(referentialName); + if (node == null) { + node = new TypeReferentialSynchroNode(referentialName); + add(node); + } + return node; + } + + public <R extends ReferentialDto> TypeReferentialSynchroNode getChild(Class<R> referentialName) { + Enumeration children = children(); + while (children.hasMoreElements()) { + TypeReferentialSynchroNode o = (TypeReferentialSynchroNode) children.nextElement(); + if (referentialName.equals(o.getUserObject())) { + return o; + } + } + return null; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/node/TypeReferentialSynchroNode.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/node/TypeReferentialSynchroNode.java new file mode 100644 index 0000000..ae4465b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/node/TypeReferentialSynchroNode.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node; + +import fr.ird.observe.services.dto.referential.ReferentialDto; + +import javax.swing.UIManager; +import java.util.Enumeration; + +/** + * Created on 09/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + */ +public class TypeReferentialSynchroNode extends ReferentialSynchroNodeSupport { + + private static final long serialVersionUID = 1L; + + public TypeReferentialSynchroNode(Class<? extends ReferentialDto> type) { + super(UIManager.getIcon("navigation.sub.referentiel-16"), type); + } + + @Override + public RootReferentialSynchroNode getParent() { + return (RootReferentialSynchroNode) super.getParent(); + } + + public <R extends ReferentialDto> ReferenceReferentialSynchroNodeSupport getChild(String id) { + Enumeration children = children(); + while (children.hasMoreElements()) { + ReferenceReferentialSynchroNodeSupport o = (ReferenceReferentialSynchroNodeSupport) children.nextElement(); + if (id.equals(o.getUserObject().getId())) { + return o; + } + } + return null; + } + + @Override + public Class<? extends ReferentialDto> getUserObject() { + return (Class) super.getUserObject(); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/node/UpdatedReferenceReferentialSynchroNode.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/node/UpdatedReferenceReferentialSynchroNode.java new file mode 100644 index 0000000..b14a02f --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/synchronize/referential/ng/tree/node/UpdatedReferenceReferentialSynchroNode.java @@ -0,0 +1,19 @@ +package fr.ird.observe.application.swing.ui.admin.synchronize.referential.ng.tree.node; + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; + +/** + * Created on 11/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + */ +public class UpdatedReferenceReferentialSynchroNode extends ReferenceReferentialSynchroNodeSupport { + + private static final long serialVersionUID = 1L; + + public UpdatedReferenceReferentialSynchroNode(ReferentialReference<? extends ReferentialDto> referentialReference, boolean canAdd, boolean canUpdate, boolean canDelete, boolean canRevert) { + super(referentialReference, "synchroUpdate", canAdd, canUpdate, canDelete, canRevert); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidateConfigUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidateConfigUI.jaxx new file mode 100644 index 0000000..d7cf9f1 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidateConfigUI.jaxx @@ -0,0 +1,184 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<!-- ************************************************************* --> +<!-- La configuration de l'import GPS --> +<!-- ************************************************************* --> + +<JPanel id="validateConfig"> + + <import> + fr.ird.observe.application.swing.ui.admin.AdminUIModel + fr.ird.observe.application.swing.validation.ValidationModelMode + + org.nuiton.validator.NuitonValidatorScope + + java.io.File + + javax.swing.JComboBox + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + </import> + + <ValidateUIHandler id='handler' + initializer='getContextValue(ValidateUIHandler.class)'/> + + <AdminUIModel id='model' initializer='getContextValue(AdminUIModel.class)'/> + + <ValidateModel id='validateModel' initializer='model.getValidateModel()'/> + + <ButtonGroup id='validateContentModel' + onStateChanged='validateModel.setModelMode((ValidationModelMode) validateContentModel.getSelectedValue())'/> + + <script><![CDATA[ +public void destroy() { + model = null; + validateModel = null; +} + +@Override +protected void finalize() throws Throwable { + super.finalize(); + destroy(); +} + +]]> + </script> + + <JPanel constraints='BorderLayout.NORTH' layout='{new BorderLayout()}'> + <Table id="validateDataConfig" constraints='BorderLayout.NORTH'> + + <!-- validation mode --> + <row> + <cell anchor="west"> + <JLabel id='validateModeLabel'/> + </cell> + <cell weightx='1' fill="horizontal"> + <Table fill='both' weightx='1'> + <row> + <cell> + <JRadioButton id="DATA"/> + </cell> + </row> + <row> + <cell> + <JRadioButton id="REFERENTIEL"/> + </cell> + </row> + <!--row> + <cell> + <JRadioButton id="ALL"/> + </cell> + </row--> + </Table> + </cell> + </row> + <row> + <cell anchor="west" columns="2"> + <JLabel id='credentialsInfo'/> + </cell> + </row> + + <!-- validation scopes --> + <row> + <cell anchor="west"> + <JLabel id='validateScopesLabel'/> + </cell> + <cell weightx='1' fill="horizontal"> + <Table id='validateScopes' fill='both' weightx='1'> + <row> + <cell> + <JCheckBox id='ERROR' + onItemStateChanged='getHandler().updateValidationScopes((JCheckBox)event.getSource())'/> + </cell> + </row> + <row> + <cell> + <JCheckBox id='WARNING' + onItemStateChanged='getHandler().updateValidationScopes((JCheckBox)event.getSource())'/> + </cell> + </row> + <row> + <cell> + <JCheckBox id='INFO' + onItemStateChanged='getHandler().updateValidationScopes((JCheckBox)event.getSource())'/> + </cell> + </row> + </Table> + </cell> + </row> + <!-- validation resume --> + <row> + <cell anchor="west" columns="2"> + <JLabel id='validateResume'/> + </cell> + </row> + <row> + <cell anchor="west" columns="2"> + <JLabel actionIcon='information' + text='observe.info.selected.validators'/> + </cell> + </row> + </Table> + + <Table id='validationReportConfig' fill='both' + constraints='BorderLayout.CENTER'> + <row> + <cell columns="2"> + <JCheckBox id='generateValidationReport' + onItemStateChanged='validateModel.setGenerateReport(((JCheckBox)event.getSource()).isSelected())'/> + </cell> + </row> + <row> + <cell> + <JLabel id="validationReportDirectoryLabel"/> + </cell> + <cell weightx='1' fill="horizontal"> + <JTextField id='validationReportDirectoryText' + onKeyReleased='getHandler().changeValidationReportDirectory(this, new File(((JTextField)event.getSource()).getText()))'/> + </cell> + <cell anchor="east"> + <JButton id="chooseValidationReportFileAction" + onActionPerformed="getHandler().chooseValidationReportFile(this)"/> + </cell> + </row> + <row> + <cell> + <JLabel id="validationReportFileLabel"/> + </cell> + <cell weightx='1' fill="horizontal" columns="2"> + <JTextField + id='validationReportFilenameText' + onKeyReleased='getHandler().changeValidationReportFilename(this, ((JTextField)event.getSource()).getText())'/> + </cell> + </row> + </Table> + + </JPanel> + <Table constraints='BorderLayout.SOUTH' weightx='1' weighty='1'> + <row> + <cell> + <JLabel/> + </cell> + </row> + </Table> + +</JPanel> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateConfigUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidateConfigUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateConfigUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidateConfigUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidateEntityListCellRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidateEntityListCellRenderer.java new file mode 100644 index 0000000..bdb449f --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidateEntityListCellRenderer.java @@ -0,0 +1,158 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin.validate; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.services.dto.AbstractReference; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.service.actions.validate.ValidateResultForDto; +import fr.ird.observe.services.service.actions.validate.ValidateResultForDtos; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.decorator.Decorator; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.DefaultListCellRenderer; +import javax.swing.JList; +import java.awt.Component; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.util.EnumMap; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import static org.nuiton.i18n.I18n.t; + +public class ValidateEntityListCellRenderer extends DefaultListCellRenderer implements PropertyChangeListener { + + private static final long serialVersionUID = 1L; + + /** Logger */ + private static final Log log = LogFactory.getLog(ValidateEntityListCellRenderer.class); + + protected final ValidateModel model; + + protected final Map<Object, String> renderCache; + + protected DecoratorService service; + + public ValidateEntityListCellRenderer(ValidateModel model) { + this.model = model; + renderCache = new HashMap<>(); + // on ecoute les modifications de messages sur le model + this.model.addPropertyChangeListener(ValidateModel.PROPERTY_MESSAGES, this); + } + + @Override + public void propertyChange(PropertyChangeEvent evt) { + + Map<?, ?> value = (Map<?, ?>) evt.getNewValue(); + if (log.isDebugEnabled()) { + log.debug("messages changed : " + + (value == null ? 0 : value.size()) + + ", rebuild render cache"); + } + synchronized (renderCache) { + renderCache.clear(); + if (model.getMessages() == null) { + return; + } + + for (Class<?> klass : model.getMessageTypes()) { + String type = t(DecoratorService.getEntityLabel(klass)); + renderCache.put(klass, type); + } + } + + } + + public DecoratorService getService() { + if (service == null) { + service = ObserveSwingApplicationContext.get().getDecoratorService(); + } + return service; + } + + @Override + public Component getListCellRendererComponent(JList list, + Object value, + int index, + boolean isSelected, + boolean cellHasFocus) { + if (value != null) { + DecoratorService decoratorService = getService(); + if (value instanceof Class<?>) { + value = renderCache.get(value); + } else { + value = valueFromRefDto(decoratorService, (AbstractReference) value); + } + } + return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); + } + + public Object valueFromRefDto(DecoratorService decoratorService, AbstractReference value) { + String s = renderCache.get(value); + if (s != null) { + return s; + } + + if (log.isDebugEnabled()) { + log.debug("compute render cache for " + value.getId()); + } + + ValidateResultForDto validateResultForDto = model.getMessages(value); + + EnumMap<NuitonValidatorScope, Integer> scopes = + ValidateResultForDtos.getScopesCount(validateResultForDto); + + StringBuilder buffer = new StringBuilder(); + + Decorator<?> decorator; + if (value instanceof ReferentialReference) { + decorator = decoratorService.getReferentialReferenceDecorator(value.getType()); + } else { + decorator = decoratorService.getDataReferenceDecorator(value.getType()); + } + + buffer.append(decorator.toString(value)); + buffer.append(" ("); + + Iterator<NuitonValidatorScope> itr = scopes.keySet().iterator(); + while (itr.hasNext()) { + NuitonValidatorScope scope = itr.next(); + int nb = scopes.get(scope); + String t = t(scope.getLabel()); + buffer.append(t).append(" : ").append(nb); + if (itr.hasNext()) { + buffer.append(", "); + } + } + buffer.append(")"); + s = buffer.toString(); + renderCache.put(value, s); + return s; + } + +} + diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidateModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidateModel.java new file mode 100644 index 0000000..a568896 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidateModel.java @@ -0,0 +1,261 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin.validate; + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.services.dto.AbstractReference; +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.services.service.actions.validate.ValidateResultForDto; +import fr.ird.observe.services.service.actions.validate.ValidateResultForDtoType; +import fr.ird.observe.services.service.actions.validate.ValidatorDto; +import fr.ird.observe.services.service.actions.validate.ValidatorDtos; +import fr.ird.observe.application.swing.ui.admin.AdminActionModel; +import fr.ird.observe.application.swing.ui.admin.AdminStep; +import fr.ird.observe.application.swing.validation.ValidationModelMode; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.validator.NuitonValidatorScope; + +import java.io.File; +import java.util.Date; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +/** + * Modele pour preparer une validation de donnees d'une base. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.3 + */ +public class ValidateModel extends AdminActionModel { + + public static final String PROPERTY_ALL_CONTEXT_NAMES = "allContextNames"; + + public static final String PROPERTY_CONTEXT_NAME = "contextName"; + + public static final String PROPERTY_SCOPES = "scopes"; + + public static final String PROPERTY_MODEL_MODE = "modelMode"; + + public static final String PROPERTY_GENERATE_REPORT = "generateReport"; + + public static final String PROPERTY_REPORT_FILE = "reportFile"; + + public static final String PROPERTY_MESSAGES = "messages"; + + /** Logger */ + private static final Log log = LogFactory.getLog(ValidateModel.class); + + /** les scopes a utiliser */ + protected final EnumSet<NuitonValidatorScope> scopes; + + /** le lastName du context de validation */ + protected String contextName; + + /** le type de modele a utiliser */ + protected ValidationModelMode modelMode; + + /** pour generer un rapport et le sauvegarder */ + protected boolean generateReport; + + /** le fichier où sauvegarder les résultats de la validation */ + protected File reportFile = new File(""); + + /** tout les validateur de la base */ + protected ImmutableSet<ValidatorDto> allValidators; + + /** les validateurs selectionnées */ + protected Set<ValidatorDto> validators; + + /** le dictionnaire des paths d'entites detectees */ + protected Map<Class<? extends IdDto>, ValidateResultForDtoType> messages; + + public ValidateModel() { + super(AdminStep.VALIDATE); + scopes = EnumSet.noneOf(NuitonValidatorScope.class); + messages = new TreeMap<>(); + } + + /** + * @return le lastName par defaut du fichier de sauvegarde de la base locale + * (expression calculée à partir de la date courante et du pattern + * {@link ObserveSwingApplicationConfig#REPORT_PATTERN}). + */ + public String getDefaultReportFilename() { + return String.format(ObserveSwingApplicationConfig.REPORT_PATTERN, new Date()); + } + + public String getContextName() { + return contextName; + } + + public void setContextName(String contextName) { + Object oldvalue = this.contextName; + this.contextName = contextName; + validators = null; + firePropertyChange(PROPERTY_CONTEXT_NAME, oldvalue, contextName); + } + + public ValidationModelMode getModelMode() { + return modelMode; + } + + public void setModelMode(ValidationModelMode modelMode) { + Object oldvalue = this.modelMode; + this.modelMode = modelMode; + validators = null; + firePropertyChange(PROPERTY_MODEL_MODE, oldvalue, modelMode); + } + + public EnumSet<NuitonValidatorScope> getScopes() { + return scopes; + } + + public boolean isGenerateReport() { + return generateReport; + } + + public void setGenerateReport(boolean generateReport) { + Object oldValue = this.generateReport; + this.generateReport = generateReport; + firePropertyChange(PROPERTY_GENERATE_REPORT, oldValue, generateReport); + } + + public File getReportFile() { + return reportFile; + } + + public void setReportFile(File reportFile) { + Object oldValue = this.reportFile; + this.reportFile = reportFile; + firePropertyChange(PROPERTY_REPORT_FILE, oldValue, reportFile); + } + + public void setAllValidators(ImmutableSet<ValidatorDto> allValidators) { + this.allValidators = allValidators; + } + + public Set<ValidatorDto> getValidators() { + if (validators == null) { + if (allValidators != null && getContextName() != null) { + validators = ValidatorDtos.filter( + allValidators, + getModelMode().isData(), + getModelMode().isReferential(), + getScopes(), + getContextName()); + } else { + validators = Sets.newHashSet(); + } + + } + return validators; + } + + public Map<Class<? extends IdDto>, ValidateResultForDtoType> getMessages() { + return messages; + } + + public void setMessages(Map<Class<? extends IdDto>, ValidateResultForDtoType> messages) { + Object oldValue = this.messages; + this.messages = messages; + firePropertyChange(PROPERTY_MESSAGES, oldValue, messages); + } + + public Set<Class<? extends IdDto>> getMessageTypes() { + Set<Class<? extends IdDto>> result; + + if (messages != null && !messages.isEmpty()) { + result = messages.keySet(); + } else { + result = Sets.newHashSet(); + } + + return result; + } + + public List<AbstractReference> getMessagesDto(Class dtoType) { + + List<AbstractReference> result = Lists.newArrayList(); + + if (messages != null) { + + ValidateResultForDtoType resultForDtoType = messages.get(dtoType); + + ImmutableSet<ValidateResultForDto> validateResultForDto = resultForDtoType.getValidateResultForDto(); + + for (ValidateResultForDto resultForDto : validateResultForDto) { + + result.add(resultForDto.getDto()); + } + } + return result; + } + + public ValidateResultForDto getMessages(AbstractReference referenceDto) { + + ValidateResultForDto result = null; + + if (messages != null) { + + ValidateResultForDtoType resultForDtoType = messages.get(referenceDto.getType()); + + result = resultForDtoType.getValidateResult(referenceDto); + + } + + return result; + } + + public void addScope(NuitonValidatorScope scope) { + scopes.add(scope); + validators = null; + firePropertyChange(PROPERTY_SCOPES, null, scopes); + } + + public void removeScope(NuitonValidatorScope scope) { + scopes.remove(scope); + validators = null; + firePropertyChange(PROPERTY_SCOPES, null, scopes); + } + + @Override + public void destroy() { + super.destroy(); + if (messages != null) { + setMessages(null); + } + if (validators != null) { + validators = null; + } + } + + public ImmutableSet<ValidatorDto> getAllValidators() { + return allValidators; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidateUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidateUI.jaxx new file mode 100644 index 0000000..69e554d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidateUI.jaxx @@ -0,0 +1,127 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<!-- ********************************************** --> +<!-- L'écran de validation des données observers --> +<!-- ********************************************** --> + +<fr.ird.observe.application.swing.ui.admin.AdminTabUI> + + <import> + fr.ird.observe.application.swing.ui.UIHelper + fr.ird.observe.application.swing.ui.admin.AdminStep + fr.ird.observe.application.swing.ui.admin.AdminTabUI + fr.ird.observe.application.swing.ui.admin.AdminUI + fr.ird.observe.application.swing.ui.admin.validate.ValidationMessageTableModel + + + jaxx.runtime.swing.wizard.ext.WizardState + jaxx.runtime.validator.swing.SimpleBeanValidatorMessageTableModel + + org.jdesktop.swingx.JXTitledPanel + + javax.swing.ListSelectionModel + + </import> + + <ValidateUIHandler id='handler' constructorParams='this'/> + + <ValidateModel id='stepModel' initializer='getModel().getValidateModel()'/> + + <DefaultListModel id='typeModel'/> + + <DefaultListModel id='refModel'/> + + <ValidationMessageTableModel id='messagesModel'/> + + <DefaultListSelectionModel id='typeSelectionModel' + onValueChanged='if (!event.getValueIsAdjusting() && !typeSelectionModel.isSelectionEmpty()) { getHandler().updateSelectedType(); }'/> + + <DefaultListSelectionModel id='refSelectionModel' + onValueChanged='if (!event.getValueIsAdjusting() && !refSelectionModel.isSelectionEmpty()) { getHandler().updateSelectedRef(); }'/> + + <script><![CDATA[ +public ValidateUI(AdminUI parentContext) { + super(AdminStep.VALIDATE, parentContext); +} + +@Override +public void initUI(AdminUI ui) { + getHandler().initTabUI(ui, this); +} + +@Override +public void updateState(WizardState newState) { + getHandler().updateState(this, newState); +} +]]> + </script> + + <JPanel id='PENDING_content'> + <Table constraints='BorderLayout.CENTER' fill='both' weightx='1' + weighty='1'> + <row> + <cell> + <JButton id='startButton' + onActionPerformed="getHandler().startAction()"/> + </cell> + </row> + </Table> + </JPanel> + + <JPanel id='NEED_FIX_content'> + + <JSplitPane id='splitpane' constraints='BorderLayout.CENTER'> + + <!-- up : entities view --> + <JXTitledPanel id='navigationView'> + <JSplitPane id='splitpane2'> + <JScrollPane> + <JList id='typeList'/> + </JScrollPane> + <JScrollPane> + <JList id='refList'/> + </JScrollPane> + </JSplitPane> + </JXTitledPanel> + + <!-- down : message view --> + <JXTitledPanel id='messageView'> + <JScrollPane> + <JTable id='messageTable'/> + </JScrollPane> + </JXTitledPanel> + + </JSplitPane> + + <JPanel constraints='BorderLayout.SOUTH' layout='{new BorderLayout()}'> + + <JLabel id='resumeLabel' constraints='BorderLayout.CENTER'/> + + <JPanel constraints='BorderLayout.SOUTH' layout='{new BorderLayout()}'> + <JButton id='saveReport' constraints='BorderLayout.CENTER' + onActionPerformed='getHandler().saveReport()'/> + </JPanel> + + </JPanel> + </JPanel> +</fr.ird.observe.application.swing.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidateUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidateUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidateUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidateUIHandler.java new file mode 100644 index 0000000..1b4b355 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidateUIHandler.java @@ -0,0 +1,603 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.admin.validate; + +import com.google.common.base.Charsets; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Iterables; +import com.google.common.collect.Maps; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.AbstractReference; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.services.service.actions.validate.ValidateDataRequest; +import fr.ird.observe.services.service.actions.validate.ValidateDataResult; +import fr.ird.observe.services.service.actions.validate.ValidateReferentialsRequest; +import fr.ird.observe.services.service.actions.validate.ValidateReferentialsResult; +import fr.ird.observe.services.service.actions.validate.ValidateResultForDto; +import fr.ird.observe.services.service.actions.validate.ValidateResultForDtoType; +import fr.ird.observe.services.service.actions.validate.ValidateResultForDtos; +import fr.ird.observe.services.service.actions.validate.ValidateService; +import fr.ird.observe.services.service.actions.validate.ValidationMessage; +import fr.ird.observe.services.service.actions.validate.ValidatorDto; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.admin.AdminStep; +import fr.ird.observe.application.swing.ui.admin.AdminTabUI; +import fr.ird.observe.application.swing.ui.admin.AdminTabUIHandler; +import fr.ird.observe.application.swing.ui.admin.AdminUI; +import fr.ird.observe.application.swing.ui.admin.AdminUIModel; +import fr.ird.observe.application.swing.ui.admin.config.ConfigUI; +import fr.ird.observe.application.swing.ui.admin.config.SelectDataUI; +import fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel; +import fr.ird.observe.application.swing.ui.util.ObserveValidationMessageTableRenderer; +import fr.ird.observe.application.swing.validation.ValidationModelMode; +import jaxx.runtime.SwingUtil; +import jaxx.runtime.context.JAXXInitialContext; +import jaxx.runtime.swing.wizard.ext.WizardState; +import org.apache.commons.io.FileUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.decorator.Decorator; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.ComboBoxModel; +import javax.swing.DefaultComboBoxModel; +import javax.swing.DefaultListModel; +import javax.swing.JCheckBox; +import javax.swing.JTable; +import javax.swing.RowSorter; +import javax.swing.SortOrder; +import java.io.File; +import java.io.IOException; +import java.util.Collections; +import java.util.Date; +import java.util.EnumSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +//import jaxx.runtime.validator.swing.SwingValidator; + +/** + * Le controleur des onglets. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ValidateUIHandler extends AdminTabUIHandler { + + public static final String[] EMPTY_STRING_ARRAY = new String[]{}; + + public static final String LINE = + "--------------------------------------------------------------------------------"; + + /** Logger */ + private static final Log log = LogFactory.getLog(ValidateUIHandler.class); + + protected ObserveSwingDataSource source; + + protected Decorator<TripSeineDto> dTrip; + + protected Decorator<ProgramDto> dProgram; + + public ValidateUIHandler(AdminTabUI ui) { + super(ui); + } + + public void initTabUI(AdminUI ui, ValidateUI tabUI) { + + super.initTabUI(ui, tabUI); + + if (log.isDebugEnabled()) { + log.debug(" specialized for [" + tabUI.getStep() + "] for main ui " + ui.getClass().getName() + "@" + System.identityHashCode(ui)); + } + + JTable messageTable = tabUI.getMessageTable(); + + messageTable.setDefaultRenderer(Object.class, new ObserveValidationMessageTableRenderer()); + messageTable.getRowSorter().setSortKeys( + Collections.singletonList(new RowSorter.SortKey(0, SortOrder.ASCENDING))); + SwingUtil.setI18nTableHeaderRenderer( + messageTable, + n("validator.scope.header"), + n("validator.scope.header.tip"), + n("validator.field.header"), + n("validator.field.header.tip"), + n("validator.message.header"), + n("validator.message.header.tip")); + SwingUtil.fixTableColumnWidth(messageTable, 0, 25); + + ValidateEntityListCellRenderer listRenderer = + new ValidateEntityListCellRenderer(tabUI.getStepModel()); + tabUI.getTypeList().setCellRenderer(listRenderer); + tabUI.getRefList().setCellRenderer(listRenderer); + + tabUI.getStartButton().setText(t("observe.actions.synchro.launch.operation", t(tabUI.getStep().getOperationLabel()))); + + // initialisation de l'ui de configuration + if (log.isInfoEnabled()) { + log.info("Init extra configuration for " + tabUI.getName()); + } + + ConfigUI configUI = (ConfigUI) ui.getStepUI(AdminStep.CONFIG); + JAXXInitialContext tx = new JAXXInitialContext().add(configUI).add(this); + ValidateConfigUI extraConfig = new ValidateConfigUI(tx); + configUI.getExtraConfig().add(extraConfig); + + final SelectDataUI selectTabUI = (SelectDataUI) ui.getStepUI(AdminStep.SELECT_DATA); + + getModel().getValidateModel().addPropertyChangeListener(ValidateModel.PROPERTY_MODEL_MODE, evt -> { + ValidationModelMode value = (ValidationModelMode) evt.getNewValue(); + if (value == null) { + // rien a faire pour le moment... + return; + } + DataSelectionModel selectDataModel; + selectDataModel = selectTabUI.getSelectDataModel(); + if (log.isDebugEnabled()) { + log.debug("validation model changed to " + value); + } + switch (value) { + case REFERENTIEL: + + selectDataModel.setUseData(false); + selectDataModel.setUseReferentiel(true); + break; + case DATA: + selectDataModel.setUseData(true); + selectDataModel.setUseReferentiel(false); + break; + case ALL: + selectDataModel.setUseData(true); + selectDataModel.setUseReferentiel(true); + break; + } + //updateModel(); + }); + + selectTabUI.getModel().addPropertyChangeListener(AdminUIModel.SELECTION_MODEL_CHANGED_PROPERTY_NAME, evt -> { + AdminUIModel model1 = (AdminUIModel) evt.getSource(); + if (!model1.containsStep(selectTabUI.getStep())) { + // avoid multi-cast + return; + } + DataSelectionModel value = (DataSelectionModel) evt.getNewValue(); + if (log.isInfoEnabled()) { + log.info("selection model changed to " + value); + } + updateSelectionModel(selectTabUI); + }); + + ImmutableSet<ValidatorDto> validators = ObserveSwingApplicationContext.get().getValidators(); + + ValidateModel stepModel = model.getValidateModel(); + + stepModel.setAllValidators(validators); + } + + public void updateState(ValidateUI tabUI, WizardState newState) { + + super.updateState(tabUI, newState); + + if (newState == WizardState.NEED_FIX) { + updateTypes(); + tabUI.resumeLabel.setText(t("observe.actions.validate.save.reportFile", tabUI.getStepModel().getReportFile())); + String actionText; + if (tabUI.getStepModel().isGenerateReport()) { + actionText = t("observe.actions.validate.save"); + } else { + actionText = t("observe.actions.validate.continue.with.no.save.report"); + } + tabUI.saveReport.setText(actionText); + return; + } + if (newState == WizardState.RUNNING) { + tabUI.typeList.clearSelection(); + tabUI.refList.clearSelection(); + tabUI.messageTable.clearSelection(); + tabUI.typeModel.clear(); + tabUI.refModel.clear(); + tabUI.messagesModel.clear(); + } + if (newState == WizardState.SUCCESSED) { + } + } + + public void updateTypes() { + + ValidateUI tabUI = (ValidateUI) ui; + + DefaultListModel typeModel = tabUI.typeModel; + tabUI.typeSelectionModel.clearSelection(); + typeModel.clear(); + + Set<Class<? extends IdDto>> messageTypes = tabUI.getStepModel().getMessageTypes(); + + List<Class<? extends IdDto>> classes = getDecoratorService().sortTypes(messageTypes); + + for (Class<? extends IdDto> e : classes) { + + typeModel.addElement(e); + + } + + tabUI.typeList.setSelectedIndex(0); + } + + public void updateSelectedType() { + + + ValidateUI tabUI = (ValidateUI) ui; + + getModel().setBusy(true); + // on nettoye le modele des refs + try { + tabUI.refSelectionModel.clearSelection(); + tabUI.refModel.clear(); + + Object o = tabUI.typeList.getSelectedValue(); + if (log.isInfoEnabled()) { + log.info("new selected type = " + o); + } + if (o == null) { + return; + } + + Class<?> type = (Class<?>) o; + + List<AbstractReference> refs = tabUI.getStepModel().getMessagesDto(type); + for (AbstractReference ref : Iterables.limit(refs, 100)) { + if (log.isDebugEnabled()) { + log.debug("add ref = " + ref); + } + tabUI.refModel.addElement(ref); + } + tabUI.refList.setSelectedIndex(0); + } finally { + getModel().setBusy(false); + } + + } + + public void updateSelectedRef() { + + + ValidateUI tabUI = (ValidateUI) ui; + + // on nettoye le modele des messages + tabUI.messageTable.clearSelection(); + tabUI.messagesModel.clear(); + + Object o = tabUI.refList.getSelectedValue(); + + if (log.isDebugEnabled()) { + log.debug("new selected ref = " + o); + } + + if (o == null) { + return; + } + + AbstractReference ref = (AbstractReference) o; + + if (log.isDebugEnabled()) { + log.debug(ref); + } + + ValidateResultForDto resultForDto = tabUI.getStepModel().getMessages(ref); + + ImmutableSet<ValidationMessage> messages = resultForDto.getMessages(); + + tabUI.messagesModel.setMessages(messages); + + + } + + public void startAction() { + + addAdminWorker(((ValidateUI) ui).getStartButton().getToolTipText(), this::doAction); + } + + public WizardState doAction() throws Exception { + if (log.isDebugEnabled()) { + log.debug(this); + } + + WizardState init = initDB(); + + if (init != null) { + // une erreur ou une annulation + return init; + } + + launchValidation(); + + Map<Class<? extends IdDto>, ValidateResultForDtoType> messages = model.getValidateModel().getMessages(); + if (messages == null || messages.isEmpty()) { + + // pas de validation ou bien pas d'erreurs rencontrées + + sendMessage(t("observe.actions.validation.message.nothing.to.do")); + sendMessage(t("observe.actions.validation.message.operation.done", new Date())); + + return WizardState.SUCCESSED; + } + + sendMessage( + t("observe.actions.validation.message.operation.needFix", new Date())); + + return WizardState.NEED_FIX; + } + + protected WizardState initDB() throws Exception { + + + // on recupere la source de données + source = model.getSafeLocalSource(false); + + DecoratorService decoratorService = getDecoratorService(); + + dTrip = decoratorService.getDecoratorByType(TripSeineDto.class); + + dProgram = decoratorService.getDecoratorByType(ProgramDto.class); + + openSource(source); + + // recuperation des validateurs du modele + + ValidateModel validationModel = model.getValidateModel(); + Set<ValidatorDto> validators = validationModel.getValidators(); + + sendMessage(t("observe.actions.validation.message.use.storage", + source.getLabel())); + + sendMessage(t("observe.actions.validation.message.prepare.validators")); + + if (!validators.isEmpty()) { + + // des validateurs ont été trouvés + + for (ValidatorDto v : validators) { + String label = t(DecoratorService.getEntityLabel(v.getDtoType())); + sendMessage(t("observe.actions.validation.message.detected", label)); + } + } else { + sendMessage(t("observe.message.no.validation.detected")); + } + + return null; + } + + public void launchValidation() throws Exception { + + // on vide les anciens messages + ValidateModel stepModel = model.getValidateModel(); + stepModel.setMessages(null); + + DataSelectionModel dataModel = model.getSelectionDataModel(); + + ObserveSwingDataSource dataSourceToValidate = model.getLocalSource(); + + if (!dataSourceToValidate.isOpen()) { + dataSourceToValidate.open(); + } + + ValidateService validateService = dataSourceToValidate.newValidateService(); + + Map<Class<? extends IdDto>, ValidateResultForDtoType> messages = Maps.newHashMap(); + + if (dataModel.isUseReferentiel()) { + + // validation des referentiels selectionnes + ValidateReferentialsRequest request = new ValidateReferentialsRequest(); + + request.setReferentialTypes(ImmutableSet.copyOf(dataModel.getSelectedReferentiel())); + request.setScopes(ImmutableSet.copyOf(stepModel.getScopes())); + request.setValidationContext(stepModel.getContextName()); + + ValidateReferentialsResult result = validateService.validateReferentials(request); + + messages.putAll(result.getResultByType()); + } + + if (dataModel.isUseData()) { + + // validation des donnees observateur selectionnee + ValidateDataRequest request = new ValidateDataRequest(); + + request.setDataIds(ImmutableSet.copyOf(dataModel.getSelectedData().stream() + .map(DataReference.ID_FUNCTION) + .collect(Collectors.toSet()))); + request.setScopes(ImmutableSet.copyOf(stepModel.getScopes())); + request.setValidationContext(stepModel.getContextName()); + + ValidateDataResult result = validateService.validateData(request); + + messages.putAll(result.getResultByType()); + } + + dataSourceToValidate.close(); + + stepModel.setMessages(messages); + + } + + public void saveReport() { + WizardState finalState = null; + ValidateModel validationModel = model.getValidateModel(); + try { + if (validationModel.isGenerateReport()) { + + sendMessage( + t("observe.actions.validation.message.save.report", validationModel.getReportFile())); + + generateReportFile(validationModel); + } else { + sendMessage( + t("observe.actions.validation.message.not.save.report")); + } + finalState = WizardState.SUCCESSED; + } catch (Exception e) { + validationModel.setError(e); + finalState = WizardState.FAILED; + } finally { + model.setStepState(AdminStep.VALIDATE, finalState); + } + } + + //FIXME A remplacer par une template + public void generateReportFile(ValidateModel validationModel) throws IOException { + File reportFile = validationModel.getReportFile(); + if (log.isInfoEnabled()) { + log.info("save report in " + reportFile); + } + + DecoratorService service = getDecoratorService(); + StringBuilder builder = new StringBuilder(); + builder.append(LINE).append('\n'); + + builder.append(t("observe.actions.validate.report.title", new Date())).append('\n'); + builder.append(t("observe.actions.validate.report.scopes", validationModel.getScopes())).append('\n'); + builder.append(t("observe.actions.validate.report.contextName", validationModel.getContextName())).append('\n'); + + Map<Class<? extends IdDto>, ValidateResultForDtoType> messages = validationModel.getMessages(); + + builder.append(t("observe.actions.validate.report.entities.with.messages", messages.size())).append('\n'); + builder.append(LINE).append('\n').append('\n'); + + for (ValidateResultForDtoType validateResultForDtoType : messages.values()) { + + ImmutableSet<ValidateResultForDto> validateResultForDtos = validateResultForDtoType.getValidateResultForDto(); + for (ValidateResultForDto validateResultForDto : validateResultForDtos) { + + AbstractReference referenceDto = validateResultForDto.getDto(); + + String refStr = service.decorate(referenceDto); + + Set<ValidationMessage> refMessages = validateResultForDto.getMessages(); + + EnumSet<NuitonValidatorScope> scopes = ValidateResultForDtos.getScopes(validateResultForDto); + + builder.append(t("observe.actions.validate.report.entity", referenceDto.getId(), refStr, refMessages.size(), scopes)).append('\n'); + for (NuitonValidatorScope scope : scopes) { + + List<ValidationMessage> messagesByScope = ValidateResultForDtos.scopeMessageFilter(scope, validateResultForDto); + + for (ValidationMessage message : messagesByScope) { + + builder.append(message).append('\n'); + + } + + builder.append('\n'); + } + + } + builder.append(LINE).append('\n').append('\n'); + } + + String content = builder.toString(); + if (log.isInfoEnabled()) { + log.info(content); + } + FileUtils.write(reportFile, content, Charsets.UTF_8.name()); + } + + + // ------------------------------------------------------------------------ + // -- ValidateConfgUI methods + // ------------------------------------------------------------------------ + + public void updateValidationScopes(JCheckBox checkBox) { + NuitonValidatorScope scope = getValidatorScope(checkBox); + ValidateModel validateModel = getModel().getValidateModel(); + if (checkBox.isSelected()) { + // ajout du scope + validateModel.addScope(scope); + } else { + // supprime le scope + validateModel.removeScope(scope); + } + } + + public ComboBoxModel updateComboModel(Object... datas) { + if (datas == null) { + return new DefaultComboBoxModel(); + } + return new DefaultComboBoxModel(datas); + } + + public String updateValidatorResumeLabel(boolean valid) { + + ValidateModel validateModel = getModel().getValidateModel(); + + if (validateModel == null) { + return null; + } + return t("observe.actions.validate.selected.validators", validateModel.getValidators().size()); + } + + public AdminStep getObjectOperation(JCheckBox checkBox) { + return AdminStep.valueOf(checkBox.getName()); + } + + public NuitonValidatorScope getValidatorScope(JCheckBox checkBox) { + return (NuitonValidatorScope) checkBox.getClientProperty("value"); + } + + public boolean isScopeSelected(Set<NuitonValidatorScope> scopes, JCheckBox checkBox) { + NuitonValidatorScope scope = getValidatorScope(checkBox); + return scopes.contains(scope); + } + + public boolean isObjectOperationSelected(Set<AdminStep> objectOperations, JCheckBox checkBox) { +// AdminStep scope = getObjectOperation(checkBox); + return objectOperations.contains(getObjectOperation(checkBox)); + } + + public void chooseValidationReportFile(ValidateConfigUI configUI) { + File f = UIHelper.chooseDirectory( + configUI, + t("observe.actions.validate.title.choose.report.directory"), + t("observe.actions.validate.choose.report.directory"), + new File(configUI.validationReportDirectoryText.getText()) + ); + changeValidationReportDirectory(configUI, f); + } + + public void changeValidationReportDirectory(ValidateConfigUI configUI, File f) { + getModel().getValidateModel().setReportFile(new File(f, configUI.validationReportFilenameText.getText())); + } + + public void changeValidationReportFilename(ValidateConfigUI configUI, String filename) { + getModel().getValidateModel().setReportFile(new File(configUI.validationReportDirectoryText.getText(), filename)); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidationMessageTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidationMessageTableModel.java new file mode 100644 index 0000000..eec18b2 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/admin/validate/ValidationMessageTableModel.java @@ -0,0 +1,115 @@ +package fr.ird.observe.application.swing.ui.admin.validate; + +/*- + * #%L + * ObServe :: Application Swing + * %% + * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import fr.ird.observe.services.service.actions.validate.ValidationMessage; +import jaxx.runtime.SwingUtil; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.table.AbstractTableModel; +import java.util.Collection; +import java.util.List; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class ValidationMessageTableModel extends AbstractTableModel { + + private static final long serialVersionUID = 1L; + + public static final String[] columnNames = + {"validator.scope", "validator.field", "validator.message"}; + + public static final Class<?>[] columnClasses = + {NuitonValidatorScope.class, String.class, String.class}; + + protected final List<ValidationMessage> messages = Lists.newArrayList(); + + @Override + public int getRowCount() { + return messages.size(); + } + + @Override + public int getColumnCount() { + return columnNames.length; + } + + @Override + public boolean isCellEditable(int row, int column) { + // cells are never editable in this model + return false; + } + + @Override + public Class<?> getColumnClass(int columnIndex) { + SwingUtil.ensureColumnIndex(this, columnIndex); + return columnClasses[columnIndex]; + } + + @Override + public String getColumnName(int column) { + SwingUtil.ensureColumnIndex(this, column); + return columnNames[column]; + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + + ValidationMessage message = messages.get(rowIndex); + + Object value; + + switch (columnIndex) { + case 0: + value = message.getScope(); + break; + case 1: + value = message.getFieldName(); + break; + case 2: + value = message.getMessage(); + break; + default: + value = null; + } + + return value; + } + + public void setMessages(Collection<ValidationMessage> messages) { + this.messages.clear(); + this.messages.addAll(messages); + fireTableDataChanged(); + } + + public void clear() { + messages.clear(); + fireTableDataChanged(); + } + + public ValidationMessage getRow(int row) { + return messages.get(row); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/Common.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/Common.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/Common.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/Common.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ContentMode.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ContentMode.java new file mode 100644 index 0000000..245846a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ContentMode.java @@ -0,0 +1,38 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content; + +/** + * Pour caractériser le mode d'un écran. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public enum ContentMode { + + /** pour un écran de création d'une nouvelle donnée */ + CREATE, + /** pour un écran de modification d'une donée */ + UPDATE, + /** pour un écran en lecture seul */ + READ +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ContentUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ContentUI.jaxx new file mode 100644 index 0000000..866a840 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ContentUI.jaxx @@ -0,0 +1,160 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<org.jdesktop.swingx.JXTitledPanel + abstract='true' genericType='E extends IdDto' implements="fr.ird.observe.application.swing.ui.content.ObserveContentUI<E>" + title='{getHandler().updateTitle(getContentTitle())}' + contentContainer='{contentContainer}' + leftDecoration='{titleLeft}' + rightDecoration='{titleRightToolBar}' + _READIcon='SwingUtil.getUIManagerActionIcon("mode-read")' + _CREATEIcon='SwingUtil.getUIManagerActionIcon("mode-create")' + _UPDATEIcon='SwingUtil.getUIManagerActionIcon("mode-update")' + _READTip='t("observe.content.mode.read.tip")' + _CREATERip='t("observe.content.mode.create.tip")' + _UPDATETip='t("observe.content.mode.update.tip")'> + + <import> + fr.ird.observe.application.swing.ObserveSwingApplicationContext + fr.ird.observe.application.swing.db.DataContext + fr.ird.observe.application.swing.db.ObserveSwingDataSource + fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig + fr.ird.observe.application.swing.ui.actions.shared.GoUpUIAction + fr.ird.observe.application.swing.ui.actions.shared.GoDownUIAction + fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper + + fr.ird.observe.services.dto.IdDto + + org.jdesktop.jxlayer.JXLayer + + jaxx.runtime.swing.BlockingLayerUI + jaxx.runtime.validator.swing.SwingValidatorMessageTableModel + + javax.swing.JComboBox + javax.swing.JList + javax.swing.UIManager + </import> + + <ObserveSwingApplicationConfig id='config' initializer='ObserveSwingApplicationContext.get().getConfig()'/> + + <SwingValidatorMessageTableModel id='errorTableModel' initializer='getContextValue(SwingValidatorMessageTableModel.class)'/> + + <!--FIXME a supprimer a la fin de la migration de service --> + <ObserveSwingDataSource id='dataSource' initializer='ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource()'/> + + <DataContext id='dataContext' javaBean='ObserveSwingApplicationContext.get().getDataContext()'/> + + <ObserveTreeHelper id='treeHelper' initializer='getContextValue(ObserveTreeHelper.class)'/> + + <ContentUIModel id='model' genericType='E' initializer='ContentUIModel.newModel(this)'/> + + <ContentUIHandler id='handler' genericType='E' initializer='ContentUIHandler.newHandler(this)'/> + + <IdDto id='bean' initializer='model.getBean()'/> + + <!-- icon of the content --> + <Icon id='contentIcon' javaBean='null'/> + + <String id='contentTitle' javaBean='null'/> + + <BlockingLayerUI id='blockLayerUI'/> + + <script><![CDATA[ +public Object getSelectedBean(JComboBox combo) { + return combo.getSelectedItem(); +} + +public Object getSelectedBean(JList list) { + return list.getSelectedValue(); +} + +public void init() { + getHandler().initUI(); +} + +public void open() { + getHandler().openUI(); +} + +public boolean close() { + return getHandler().closeUI(); +} + +public void startEdit(E o) { + getHandler().startEditUI(); +} + +public void restartEdit() { + getHandler().restartEditUI(); +} + +public void stopEdit() { + getHandler().stopEditUI(); +} + +public void resetEdit() { + getHandler().resetEditUI(); +} + +public void save(boolean refresh) { + getHandler().saveUI(refresh); +} + +public void delete() { + getHandler().deleteUI(); +} + +]]> + </script> + + <JLabel id='titleLeft'/> + + <JToolBar id='titleRightToolBar'> + + <JXLayer id="actionUpPane"> + <JButton id='actionUp'/> + </JXLayer> + + <JXLayer id="actionDownPane"> + <JButton id='actionDown'/> + </JXLayer> + + <JLabel id='titleRight'/> + </JToolBar> + + <JPanel id='contentContainer'> + + <JXLayer UI='{blockLayerUI}' constraints='BorderLayout.CENTER'> + + <JPanel id='body'/> + + </JXLayer> + + <Table id='actions' constraints='BorderLayout.SOUTH'/> + + </JPanel> + + <JPanel id="invisible" visible='false'> + + </JPanel> + +</org.jdesktop.swingx.JXTitledPanel> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ContentUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ContentUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ContentUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ContentUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ContentUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ContentUIHandler.java new file mode 100644 index 0000000..aad239d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ContentUIHandler.java @@ -0,0 +1,1122 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content; + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import fr.ird.observe.application.swing.ObserveOpenDataManager; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.ObserveSwingTechnicalException; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.decoration.decorators.DataReferenceDecorator; +import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.AbstractObserveDto; +import fr.ird.observe.services.dto.DataDto; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.services.dto.reference.request.ReferenceSetRequestDefinition; +import fr.ird.observe.services.dto.reference.request.ReferenceSetRequestDefinitions; +import fr.ird.observe.services.dto.reference.request.ReferenceSetRequestKeyDefinition; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.ReferentialReferenceSet; +import fr.ird.observe.services.dto.referential.ReferentialReferences; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.actions.shared.AbstractUIAction; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIHandler; +import fr.ird.observe.application.swing.ui.tree.AbstractObserveTreeCellRenderer; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import fr.ird.observe.application.swing.validation.ValidationContext; +import jaxx.runtime.JAXXContext; +import jaxx.runtime.swing.JAXXButtonGroup; +import jaxx.runtime.swing.editor.bean.BeanComboBox; +import jaxx.runtime.swing.editor.bean.BeanListHeader; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; +import jaxx.runtime.validator.swing.SwingValidatorUtil; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.lang3.reflect.ConstructorUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.decorator.Decorator; +import org.nuiton.decorator.DecoratorUtil; +import org.nuiton.decorator.JXPathDecorator; +import org.nuiton.jaxx.widgets.gis.absolute.CoordinatesEditor; +import org.nuiton.jaxx.widgets.select.FilterableDoubleList; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.AbstractButton; +import javax.swing.ActionMap; +import javax.swing.Icon; +import javax.swing.JComponent; +import javax.swing.JOptionPane; +import javax.swing.JToolBar; +import javax.swing.UIManager; +import java.awt.Component; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import static org.nuiton.i18n.I18n.t; + +/** + * Le controleur d'un écran d'édition. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public abstract class ContentUIHandler<E extends IdDto> { + + /** Logger */ + static private final Log log = LogFactory.getLog(ContentUIHandler.class); + + protected final String prefix; + + private final DataContextType parentType; + + private final DataContextType type; + + private final Icon errorIcon; + + /** l'interface graphique que le controleur utilise */ + protected final ObserveContentUI<E> ui; + + public static <E extends IdDto> ContentUIHandler<E> newHandler(ObserveContentUI<E> ui) { + + String uiName = ui.getClass().getName(); + String modelName = uiName + "Handler"; + + try { + + Class<ContentUIHandler<E>> handlerClass = (Class<ContentUIHandler<E>>) Class.forName(modelName); + ContentUIHandler<E> handler = ConstructorUtils.invokeConstructor(handlerClass, ui); + return handler; + + } catch (Exception e) { + throw new ObserveSwingTechnicalException("Could not create handler for ui: " + ui, e); + } + + } + + public static ObserveTreeHelper getTreeHelper(JAXXContext context) { + return context.getContextValue(ObserveTreeHelper.class); + } + + /** + * @param ui the current ui to close + * @return {@code true} if ui can be safelty closed, {@code false} + * otherwise. + */ + public static boolean checkEdit(ObserveContentUI<?> ui) { + + ContentUIModel<? extends AbstractObserveDto> model = ui.getModel(); + + if (model.isCreatingMode()) { + + // on peut quitter le mode creation si le modele est non modifie et valide + if (!(model.isEnabled() && model.isEditing() && (model.isModified() || !model.isValid()))) { + if (model.isEditing()) { + ui.stopEdit(); + } + // ui was not in edit mode, nor modified in edit mode, so can + // safely quit + return true; + } + } else { + + // on peut quiiter le mode mise a jour si le modele est non modifie + if (!(model.isEnabled() && model.isEditing() && model.isModified())) { + if (model.isEditing()) { + ui.stopEdit(); + } + // ui was not in edit mode, nor modified in edit mode, so can + // safely quit + return true; + } + } + + if (log.isDebugEnabled()) { + log.debug("previousUI is in edit mode"); + } + + boolean wasClosed = true; + + if (! ui.getDataSource().isExpired()) { + if (model.isValid()) { + // ask user if wants to save + int reponse = UIHelper.askUser( + (JComponent) ui, + t("observe.title.need.confirm"), + t("observe.message.quit.valid.edit"), + JOptionPane.WARNING_MESSAGE, + new Object[]{ + t("observe.choice.save"), + t("observe.choice.doNotSave"), + t("observe.choice.cancel")}, + 0); + if (log.isDebugEnabled()) { + log.debug("response : " + reponse); + } + + switch (reponse) { + case JOptionPane.CLOSED_OPTION: + case 2: + wasClosed = false; + break; + case 0: + // will save ui + ui.save(false); + break; + case 1: + // wil reset ui + ui.resetEdit(); + break; + } + + } else { + // ask user if wants to quit without saving since edit is not valid + int reponse = UIHelper.askUser( + (JComponent) ui, + t("observe.title.need.confirm"), + t("observe.message.quit.invalid.edit"), + JOptionPane.ERROR_MESSAGE, + new Object[]{ + t("observe.choice.continue"), + t("observe.choice.cancel")}, + 0); + if (log.isDebugEnabled()) { + log.debug("response : " + reponse); + } + switch (reponse) { + case JOptionPane.CLOSED_OPTION: + case 1: + wasClosed = false; + break; + case 0: + // wil reset ui + ui.resetEdit(); + break; + } + } + } + if (wasClosed) { + ui.stopEdit(); + } + return wasClosed; + } + + public static void addMessage(ObserveContentUI<?> ui, NuitonValidatorScope scope, String fieldName, String message) { + SwingValidatorMessageTableModel model = ui.getErrorTableModel(); + model.addMessages((JComponent) ui, fieldName, scope, message); + } + + public static void removeAllMessages(ContentUI<?> ui, NuitonValidatorScope scope, String fieldName) { + SwingValidatorMessageTableModel model = ui.getErrorTableModel(); + model.removeMessages(ui, fieldName, scope); + } + + public static void removeAllMessages(ObserveContentUI<?> ui) { + SwingValidatorMessageTableModel model = ui.getErrorTableModel(); + model.removeMessages((JComponent) ui, null); + } + + public ContentUIHandler(ObserveContentUI<E> ui, DataContextType parentType, DataContextType type) { + this.ui = ui; + this.parentType = parentType; + this.type = type; + prefix = "[" + ui.getClass().getSimpleName() + "] "; + if (log.isDebugEnabled()) { + log.debug("New handler [" + this + "] for ui " + prefix); + } + errorIcon = UIManager.getIcon("action.error"); + } + + public ObserveContentUI<E> getUi() { + return ui; + } + + public ContentUIModel<E> getModel() { + return getUi().getModel(); + } + + public Class<E> getBeanType() { + Class<E> mainEntityClass = getModel().getBeanType(); + return mainEntityClass; + } + + public E getBean() { + ContentUIModel<E> model = getModel(); + E bean = model.getBean(); + return bean; + } + + public DecoratorService getDecoratorService() { + DecoratorService result = ObserveSwingApplicationContext.get().getDecoratorService(); + return result; + } + + public void initUI() { + + final ContentUIInitializer<E, ObserveContentUI<E>> uiInitializer = new ContentUIInitializer<>(ui); + uiInitializer.initUI(); + + getModel().addPropertyChangeListener(ContentUIModel.PROPERTY_FORM, evt -> updateUiWithReferenceSetsFromModel()); + + } + + public void openUI() { + + boolean canWrite = computeCanWrite(getDataSource()); + + getModel().setCanWrite(canWrite); + + //FIXME chemit 20100913 : il vaudrait le faire uniquement lors de l'édition + // chaque arrive sur un ecran invalide le cache de validation + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ValidationContext context = applicationContext.getValidationContext(); + context.cleanCache(); + + if (log.isDebugEnabled()) { + log.debug("ui " + ui.getClass()); + } + // suppression des messages de validation + removeAllMessages(ui); + ObserveTreeHelper treeHelper = getTreeHelper(ui); + AbstractObserveTreeCellRenderer render = + treeHelper.getTreeCellRenderer(); + ObserveNode node = treeHelper.getSelectedNode(); + if (ContentReferenceUIHandler.class.isAssignableFrom(getClass())) { + node = node.getParent(); + } + ui.setContentIcon(render.getNavigationIcon(node)); + + updateActions(); + } + + public Icon getErrorIconIfFalse(boolean valid) { + Icon icon = null; + if (!valid) { + icon = errorIcon; + } + return icon; + } + + public void startEditUI(String... binding) { + + E editBean = getBean(); + + prepareValidationContext(); + + // reset all validators + SwingValidatorUtil.setValidatorBean(ui, null); + // mark ui as editing + getModel().setEditing(true); + + // attach validators + SwingValidatorUtil.setValidatorBean(ui, editBean); + if (binding.length > 0) { + + // force widget binding + UIHelper.processDataBinding(ui, binding); + } + UIHelper.processDataBinding(ui, "reset.enabled", "save.enabled"); + } + + public void stopEditUI() { + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ValidationContext context = applicationContext.getValidationContext(); + context.cleanCache(); + + ContentUIModel<E> model = getModel(); + + // mark ui as not editing + model.setEditing(false); + + // mark ui as valid while not editing + model.setValid(true); + + // mark ui as not modified + model.setModified(false); + + // removed initial edit object from context + ui.removeContextValue(model.getBeanType(), "edit"); + + // dettach all validators + SwingValidatorUtil.setValidatorBean(ui, null); + } + + public void resetEditUI() { + + // on arrete l'edition + stopEditUI(); + + // suppression des messages de validation + removeAllMessages(ui); + + // on re-ouvre l'écran d'édition + try { + openUI(); + } catch (Exception ex) { + UIHelper.handlingError(ex); + stopEditUI(); + } + } + + public void restartEditUI() { + + ContentUIModel<E> model = getModel(); + + if (!model.isEditable()) { + + // l'ecran n'est pas éditable, on ne re-ouvre pas + // on quite de suite + return; + } + if (log.isInfoEnabled()) { + log.info(prefix + "Will restart edit " + getUi().getClass().getName()); + } + + // on ne peut redemarrer une edition que si la donnee + // est exactement une entites (pas possible sur une liste) + ObserveTreeHelper treeHelper = getTreeHelper(ui); +// ObserveNode node = treeHelper.getSelectedNode(); + + removeAllMessages(ui); + +// treeHelper.refreshNode(node, true); + treeHelper.reloadSelectedNode(false, true); + + model.setMode(ContentMode.UPDATE); + + // redemarrage de l'édition + ui.startEdit(null); + + updateActions(); + } + + public final void saveUI(boolean refresh) { + boolean ok = false; + try { + ok = doSave(getBean()); + + } catch (Exception e) { + UIHelper.handlingError(e); + } finally { + if (ok) { + afterSave(refresh); + } + } + } + + public final boolean closeUI() { + boolean b = checkEdit(ui); + if (log.isDebugEnabled()) { + log.debug("Can close " + ui.getClass() + " : " + b); + } + if (b) { + closeSafeUI(); + } + return b; + } + + public final void deleteUI() { + boolean ok = false; + ui.stopEdit(); + removeAllMessages(ui); + + try { + ok = doDelete(getBean()); + + } catch (Exception e) { + UIHelper.handlingError(e); + } finally { + if (ok) { + afterDelete(); + } + } + } + + public <C extends DataDto> void gotoChild(DataReference<C> entity) { + if (entity == null) { + + // rien a faire + return; + } + ObserveTreeHelper treeHelper = getTreeHelper(ui); + ObserveNode parentNode = treeHelper.getSelectedNode(); + String id = entity.getId(); + ObserveNode node = treeHelper.findNode(parentNode, id); + if (log.isInfoEnabled()) { + log.info("will go to node " + node + " for " + id); + } + treeHelper.selectNode(node); + } + + public void addChild(Class<?> type) { + ObserveTreeHelper treeHelper = getTreeHelper(ui); + ObserveNode parentNode = treeHelper.getSelectedNode(); + treeHelper.addUnsavedNode(parentNode, type); + } + + public <E> List<E> updateList(BeanListHeader<E> list, List<E> data, String message) { + if (data != null && !data.isEmpty()) { + if (log.isDebugEnabled()) { + log.debug(list.getName() + " - " + data.size()); + } + Decorator<E> decorator = list.getHandler().getDecorator(); + DecoratorUtil.sort((JXPathDecorator<E>) decorator, data, 0); + return data; + } else { + List<E> result = new ArrayList<>(); + return result; + } + } + + public void openLink(String url) { + + try { + + UIHelper.openLink(url); + } catch (Exception e) { + UIHelper.handlingError(e); + } + } + + public String updateTitle(String title) { + if (ContentReferenceUIHandler.class.isAssignableFrom(getClass())) { + return DecoratorService.getEntityLabel(getBeanType()); + } + return title; + } + + protected void loadReferentialReferenceSetsInModel(Form<E> form) { + + String requestName = form.getReferentialReferenceSetsRequestName(); + + if (requestName != null) { + + loadReferentialReferenceSetsInModel(requestName); + + } + + } + + protected void loadReferentialReferenceSetsInModel(String requestName) { + + ImmutableMap.Builder<String, ReferentialReferenceSet<?>> modelReferentialReferenceSets = ImmutableMap.builder(); + + if (log.isInfoEnabled()) { + log.info("Update referential reference sets for: " + requestName); + } + + // mettre à jour le cache de référentiel + ImmutableMap<Class<?>, ReferentialReferenceSet<?>> referentialReferenceSetsByType = getDataSource().updateReferentialReferenceSetsCache(requestName); + + // calculer les listes de référentiels à utiliser dans le modèle + + ReferenceSetRequestDefinition requestDefinition = ReferenceSetRequestDefinitions.get(requestName); + + for (ReferenceSetRequestKeyDefinition propertyDefinition : requestDefinition.getPropertyDefinitions()) { + + if (!propertyDefinition.isReferential()) { + continue; + } + + String propertyName = propertyDefinition.getName(); + ReferentialReferenceSet referentialReferenceSet = referentialReferenceSetsByType.get(propertyDefinition.getType()); + ReferentialReferenceSet filteredReferentialReferenceSet = filterReferentialReferenceSet(propertyDefinition, referentialReferenceSet); + + modelReferentialReferenceSets.put(propertyName, filteredReferentialReferenceSet); + + } + + getModel().setReferentialReferenceSets(modelReferentialReferenceSets.build()); + + } + + protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { + + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), original size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + // by default always remove obsolete references + List<ReferentialReference<D>> referentialReferences = ReferentialReferences.filterEnabled(incomingReferences); + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), without diabled size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + return referentialReferences; + + } + + /** + * Calcule le mode de l'écran. + * + * @param dataContext le context de données + * @return {@code null} si l'écran est éditable, autrement le mode + * restreint READ @param dataContext le context de données + */ + protected abstract ContentMode getContentMode(DataContext dataContext); + + /** + * Pour calculer la propriete {@code canWrite} du modèle. + * + * @param dataSsource la base source de l'ui + * @return {@code true} si on peut écrire (donc éditer), {@code false} autrement. + */ + protected abstract boolean computeCanWrite(ObserveSwingDataSource dataSsource); + + protected final String getSelectedParentId() { + String s = null; + if (parentType != null) { + s = parentType.getSelectedId(getDataContext()); + } + return s; + } + + protected final String getSelectedId() { + String s = null; + if (type != null) { + s = type.getSelectedId(getDataContext()); + } + return s; + } + + protected DataContext getDataContext() { + DataContext dataContext = ui.getDataContext(); + return dataContext; + } + + protected ObserveSwingDataSource getDataSource() { + return ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); + } + + protected ObserveOpenDataManager getOpenDataManager() { + ObserveOpenDataManager openDataManager = ObserveSwingApplicationContext.get().getOpenDataManager(); + return openDataManager; + } + + protected boolean doSave(E bean) throws Exception { + return false; + } + + protected void afterSave(boolean refresh) { + + // mettre les validateurs en mode non modifié + SwingValidatorUtil.setValidatorChanged(ui, false); + } + + protected void closeSafeUI() { + + removeAllMessages(ui); + ContentUIModel<E> model = getModel(); + + boolean create = model.isCreatingMode(); + if (create && model.isEditable()) { + // remove node + ObserveTreeHelper treehelper = getTreeHelper(ui); + ObserveNode node = treehelper.getSelectedNode(); + + ObserveNode parentNode = node.getParent(); + if (parentNode != null) { + // node still attached, so remove it + treehelper.removeNode(node); + treehelper.selectNode(parentNode); + } + } + + } + + protected boolean doDelete(E bean) { + return false; + } + + protected boolean askToDelete(E bean) { + boolean accept = + UIHelper.confirmForEntityDelete(ui, getBeanType(), bean); + + return !accept; + } + + protected void afterDelete() { + ui.stopEdit(); + removeAllMessages(ui); + if (!(getBean() instanceof ReferentialDto)) { + + ObserveTreeHelper treeHelper = getTreeHelper(ui); + ObserveNode node = treeHelper.getSelectedNode(); + ObserveNode parentNode = treeHelper.removeNode(node); + treeHelper.selectNode(parentNode); + } + } + + protected void addInfoMessage(String message) { + addMessage(ui, + NuitonValidatorScope.INFO, + getEntityLabel(getModel().getBeanType()), + t(message) + ); + } + + protected String getEntityLabel(Class<?> klass) { + String result = DecoratorService.getEntityLabel(klass); + return result; + } + + protected void prepareValidationContext() { + + // reset validation cache + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ValidationContext context = applicationContext.getValidationContext(); + context.cleanCache(); + } + + protected final ContentMode computeContentMode() { + ContentMode mode; + + if (!getModel().isCanWrite()) { + if (ReferentialDto.class.isAssignableFrom(getBeanType())) { + addInfoMessage(t("observe.message.referentiel.no.editable")); + } else { + addInfoMessage(t("observe.message.can.not.write.data")); + } + mode = ContentMode.READ; + } else { + + // ask specified handler which mode to use + mode = getContentMode(getDataContext()); + } + return mode; + } + + protected final String getValidatorContextName(ContentMode mode) { + String contextName = + mode == ContentMode.CREATE ? "ui-create" : "ui-update"; + return contextName; + } + + protected void updateActions() { + + updateToolbarActions(); + + ActionMap actionMap = ObserveSwingApplicationContext.get().getActionMap(); + + for (String name : ui.get$objectMap().keySet()) { + Object o = ui.getObjectById(name); + + if (o instanceof AbstractButton) { + + AbstractButton button = (AbstractButton) o; + + String actionId = (String) button.getClientProperty(ContentUIInitializer.OBSERVE_ACTION); + + if (actionId == null) { + continue; + } + AbstractUIAction action = (AbstractUIAction) actionMap.get(actionId); + + if (log.isDebugEnabled()) { + log.debug("update common action " + actionId); + } + + action.updateAction(ui, button); + } + } + } + + protected void updateToolbarActions() { + ObserveContentUI<E> ui = getUi(); + JToolBar toolBar = ui.getTitleRightToolBar(); + Component[] components = toolBar.getComponents(); + for (Component component : components) { + if (component instanceof JComponent) { + JComponent jcompo = (JComponent) component; + if (jcompo.getClientProperty("original") != null) { + + // on conserve ce component + continue; + } + } + + toolBar.remove(component); + } + } + + protected Icon updateModeIcon(ContentMode mode) { + Icon icon = null; + if (mode != null) { + icon = (Icon) ((JComponent) ui).getClientProperty(mode.name() + "Icon"); + } + return icon; + } + + protected String updateModeTip(ContentMode mode) { + String tip = null; + if (mode != null) { + tip = (String) ((JComponent) ui).getClientProperty(mode.name() + "Tip"); + } + return tip; + } + + protected void setContentMode(ContentMode newMode) { + // pour reforcer le binding sur le mode + // cela est nécessaire car le mode peut-être positionné avant d'arriver + // sur le bon noeud et donc les calculs d'accessibilité de certaines + // actions ne sont pas corrects (par exemple action goDown) + getModel().setMode(null); + getModel().setMode(newMode); + } + + //FIXME Do it in jaxx + protected void resetQuadrant(CoordinatesEditor editor) { + + editor.setQuadrant(null); + JAXXButtonGroup quadrantBG = editor.getQuadrantBG(); + + quadrantBG.setSelectedValue(null); + quadrantBG.setSelectedButton(null); + + quadrantBG.remove(editor.getQuadrant1()); + quadrantBG.remove(editor.getQuadrant2()); + quadrantBG.remove(editor.getQuadrant3()); + quadrantBG.remove(editor.getQuadrant4()); + + editor.getQuadrant1().setSelected(false); + editor.getQuadrant2().setSelected(false); + editor.getQuadrant3().setSelected(false); + editor.getQuadrant4().setSelected(false); + + quadrantBG.add(editor.getQuadrant1()); + quadrantBG.add(editor.getQuadrant2()); + quadrantBG.add(editor.getQuadrant3()); + quadrantBG.add(editor.getQuadrant4()); + + } + + /** + * Pour mettre à jour les composants graphiques avec les référentiels chargés dans le modèle + */ + protected void updateUiWithReferenceSetsFromModel() { + + for (String name : ui.get$objectMap().keySet()) { + Object o = ui.getObjectById(name); + + if (o == null) { + continue; + } + + if (o instanceof BeanComboBox) { + + BeanComboBox beanComboBox = (BeanComboBox) o; + + Class dtoClass = getDtoClass(beanComboBox); + if (ReferentialDto.class.isAssignableFrom(dtoClass)) { + updateReferentialBeanComboBox(dtoClass, beanComboBox); + } else { + updateDataBeanComboBox(dtoClass, beanComboBox); + } + + continue; + } + + if (o instanceof BeanListHeader) { + + BeanListHeader beanListHeader = (BeanListHeader) o; + + Class dtoClass = getDtoClass(beanListHeader); + if (ReferentialDto.class.isAssignableFrom(dtoClass)) { + updateReferentialBeanListHeader(dtoClass, beanListHeader); + } else { + updateDataBeanListHeader(dtoClass, beanListHeader); + } + + continue; + } + + if (o instanceof FilterableDoubleList) { + + FilterableDoubleList filterableDoubleList = (FilterableDoubleList) o; + + Class dtoClass = getDtoClass(filterableDoubleList); + if (ReferentialDto.class.isAssignableFrom(dtoClass)) { + updateReferentialFilterableDoubleList(dtoClass, filterableDoubleList); + } else { + updateDataFilterableDoubleList(dtoClass, filterableDoubleList); + } + + } + + } + + } + + protected <R extends DataDto> void updateDataFilterableDoubleList(Class<R> dtoClass, FilterableDoubleList<DataReference<R>> list) { + + List<DataReference<R>> data; + + if (getModel().getForm() == null) { + data = Collections.emptyList(); + } else { + + Set<DataReference<R>> referenceSetDto = getModel().getDataReferences(list.getModel().getProperty()); + data = new ArrayList<>(referenceSetDto); + + } + + // sort data from first decorator context + DataReferenceDecorator<R> decorator = getDataReferenceDecorator(dtoClass); + DecoratorUtil.sort(decorator, data, 0); + + //FIXME A finir (bien vérifier que la sélection n'est plus dans l'univers) + List<DataReference<R>> selected = list.getModel().getSelected(); + list.setUniverse(data); + list.setSelected(selected); + + list.putClientProperty("data", data); + } + + protected <R extends ReferentialDto> void updateReferentialFilterableDoubleList(Class<R> dtoClass, FilterableDoubleList<ReferentialReference<R>> list) { + + Boolean forceLoadComboBox = (Boolean) list.getClientProperty(ObserveContentUI.CLIENT_PROPERTY_FORCE_LOAD); + + List<ReferentialReference<R>> data; + + if (BooleanUtils.isNotTrue(forceLoadComboBox) && getModel().getForm() == null) { + data = Collections.emptyList(); + } else { + + Set<ReferentialReference<R>> referenceSetDto = getModel().getReferentialReferences(list.getModel().getProperty()); + data = new ArrayList<>(referenceSetDto); + + } + + // sort data from first decorator context + ReferentialReferenceDecorator<R> decorator = getReferentialReferenceDecorator(dtoClass); + DecoratorUtil.sort(decorator, data, 0); + + //FIXME A finir (bien vérifier que la sélection n'est plus dans l'univers) + List<ReferentialReference<R>> selected = list.getModel().getSelected(); + list.setUniverse(data); + list.setSelected(selected); + + list.putClientProperty("data", data); + } + + protected <R extends ReferentialDto> void updateReferentialBeanListHeader(Class<R> dtoClass, BeanListHeader<ReferentialReference<R>> list) { + + Boolean noLoad = (Boolean) list.getClientProperty(ObserveContentUI.CLIENT_PROPERTY_LIST_NO_LOAD); + + List<ReferentialReference<R>> data; + + String propertyName = list.getName(); + + if (!"referentialListHeader".equals(propertyName) && (BooleanUtils.isTrue(noLoad) || getModel().getForm() == null)) { + + if (log.isInfoEnabled()) { + log.info(String.format("Skip loading of BeanListHeader [%s-%s] (listNoLoad property found or form is null)", dtoClass.getSimpleName(), propertyName)); + } + data = Collections.emptyList(); + + } else { + + Set<ReferentialReference<R>> referenceSetDto = getModel().getReferentialReferences(propertyName); + data = new ArrayList<>(referenceSetDto); + + } + + // sort data from first decorator context + ReferentialReferenceDecorator<R> decorator = getReferentialReferenceDecorator(dtoClass); + DecoratorUtil.sort(decorator, data, 0); + + list.setData(data); + list.putClientProperty("data", data); + list.getList().setListData(data.toArray()); + + } + + protected <R extends DataDto> void updateDataBeanListHeader(Class<R> dtoClass, BeanListHeader<DataReference<R>> list) { + + Boolean noLoad = (Boolean) list.getClientProperty(ObserveContentUI.CLIENT_PROPERTY_LIST_NO_LOAD); + + List<DataReference<R>> data; + + String propertyName = list.getName(); + + if (BooleanUtils.isTrue(noLoad) || getModel().getForm() == null) { + + if (log.isInfoEnabled()) { + log.info(String.format("Skip loading of BeanListHeader [%s-%s] (listNoLoad property found or form is null)", dtoClass.getSimpleName(), propertyName)); + } + data = Collections.emptyList(); + + } else { + + Set<DataReference<R>> referenceSetDto = getModel().getDataReferences(propertyName); + data = new ArrayList<>(referenceSetDto); + + } + + // sort data from first decorator context + DataReferenceDecorator<R> decorator = getDataReferenceDecorator(dtoClass); + DecoratorUtil.sort(decorator, data, 0); + + list.setData(data); + list.putClientProperty("data", data); + + } + + protected <R extends ReferentialDto> void updateReferentialBeanComboBox(Class<R> dtoClass, BeanComboBox<ReferentialReference<R>> comboBox) { + + Boolean noLoad = (Boolean) comboBox.getClientProperty(ObserveContentUI.CLIENT_PROPERTY_LIST_NO_LOAD); + Boolean forceLoadComboBox = (Boolean) comboBox.getClientProperty(ObserveContentUI.CLIENT_PROPERTY_FORCE_LOAD); + String propertyName = comboBox.getProperty(); + + List<ReferentialReference<R>> data; + + if (BooleanUtils.isNotTrue(forceLoadComboBox) && (BooleanUtils.isTrue(noLoad) || getModel().getForm() == null ) ) { + + if (log.isInfoEnabled()) { + log.info(String.format("Skip loading of comboBox [%s-%s] (listNoLoad property found or form is null)", dtoClass.getSimpleName(), propertyName)); + } + data = Collections.emptyList(); + + } else { + + Optional<Set<ReferentialReference<R>>> optionalReferenceSetDto = getModel().tryToGetReferentialReferenceSet(propertyName); + + if (optionalReferenceSetDto.isPresent()) { + + Set<ReferentialReference<R>> references = optionalReferenceSetDto.get(); + data = Lists.newArrayList(references); + + } else { + + data = Collections.emptyList(); + + } + + } + + if (log.isInfoEnabled()) { + log.info(String.format("comboBox [%s-%s] : %d", dtoClass.getSimpleName(), propertyName, data.size())); + } + + comboBox.setData(data); + + } + + protected <R extends DataDto> void updateDataBeanComboBox(Class<R> dtoClass, BeanComboBox<DataReference<R>> comboBox) { + + Boolean noLoad = (Boolean) comboBox.getClientProperty(ObserveContentUI.CLIENT_PROPERTY_LIST_NO_LOAD); + String propertyName = comboBox.getProperty(); + + List<DataReference<R>> data; + + if (BooleanUtils.isTrue(noLoad) || getModel().getForm() == null) { + + if (log.isInfoEnabled()) { + log.info(String.format("Skip loading of comboBox [%s-%s] (listNoLoad property found or form is null)", dtoClass.getSimpleName(), propertyName)); + } + data = Collections.emptyList(); + + } else { + + Optional<Set<DataReference<R>>> optionalReferenceSetDto = getModel().tryToGetDataReferenceSet(propertyName); + + if (optionalReferenceSetDto.isPresent()) { + + Set<DataReference<R>> references = optionalReferenceSetDto.get(); + data = Lists.newArrayList(references); + + } else { + data = Collections.emptyList(); + } + + } + + if (log.isInfoEnabled()) { + log.info(String.format("entity comboBox [%s-%s] : %d", dtoClass.getSimpleName(), propertyName, data.size())); + } + + comboBox.setData(data); + } + + protected <R extends IdDto> Class<R> getDtoClass(JComponent list) { + Object clientProperty = list.getClientProperty(ObserveContentUI.CLIENT_PROPERTY_ENTITY_CLASS); + return (Class<R>) clientProperty; + } + + protected <R extends DataDto> DataReferenceDecorator<R> getDataReferenceDecorator(Class<R> dtoType) { + return getDecoratorService().getDataReferenceDecorator(dtoType); + } + + protected <R extends ReferentialDto> ReferentialReferenceDecorator<R> getReferentialReferenceDecorator(Class<R> dtoType) { + return getDecoratorService().getReferentialReferenceDecorator(dtoType); + } + + private <D extends ReferentialDto> ReferentialReferenceSet<D> filterReferentialReferenceSet(ReferenceSetRequestKeyDefinition<D> propertyDefinition, + ReferentialReferenceSet<D> incomingReferentialReferenceSet) { + + Class<D> dtoType = propertyDefinition.getType(); + String propertyName = propertyDefinition.getName(); + + LinkedList<ReferentialReference<D>> incomingReferences = Lists.newLinkedList(incomingReferentialReferenceSet.getReferences()); + + Iterable<ReferentialReference<D>> filtredReferentialReferences = filterReferentialReferences(dtoType, propertyName, incomingReferences); + + ImmutableSet<ReferentialReference<D>> references1 = ImmutableSet.copyOf(filtredReferentialReferences); + ReferentialReferenceSet<D> filtredReferentialReferenceSet = ReferentialReferenceSet.of(dtoType, references1, incomingReferentialReferenceSet.getLastUpdate()); + return filtredReferentialReferenceSet; + + } + + +// protected static class LogPropertyChanges implements PropertyChangeListener { +// +// private final ImmutableSet<String> propertyNames; +// +// public LogPropertyChanges(ImmutableSet<String> propertyNames) { +// this.propertyNames = propertyNames; +// } +// +// @Override +// public void propertyChange(PropertyChangeEvent evt) { +// +// if (propertyNames.contains(evt.getPropertyName())) { +// if (log.isInfoEnabled()) { +// log.info(String.format("Property %s changed (%s → %s)", evt.getPropertyName(), evt.getOldValue(), evt.getNewValue())); +// } +// +// } +// +// } +// +// } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ContentUIInitializer.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ContentUIInitializer.java new file mode 100644 index 0000000..13dffdb --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ContentUIInitializer.java @@ -0,0 +1,853 @@ +package fr.ird.observe.application.swing.ui.content; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.Lists; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.decoration.decorators.DataReferenceDecorator; +import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; +import fr.ird.observe.services.dto.AbstractReference; +import fr.ird.observe.services.dto.DataDto; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.util.I18nEnumUtil; +import fr.ird.observe.application.swing.ui.actions.shared.AbstractUIAction; +import fr.ird.observe.application.swing.ui.util.BooleanEditor; +import fr.ird.observe.application.swing.ui.util.tripMap.ObserveMapPane; +import fr.ird.observe.application.swing.validation.ObserveSwingValidator; +import jaxx.runtime.JAXXValidator; +import jaxx.runtime.SwingUtil; +import jaxx.runtime.swing.JAXXWidgetUtil; +import jaxx.runtime.swing.OneClicListSelectionModel; +import jaxx.runtime.swing.editor.EnumEditor; +import jaxx.runtime.swing.editor.NumberEditor; +import jaxx.runtime.swing.editor.bean.BeanComboBox; +import jaxx.runtime.swing.editor.bean.BeanListHeader; +import jaxx.runtime.swing.editor.bean.BeanUIUtil; +import jaxx.runtime.swing.editor.cell.NumberCellEditor; +import jaxx.runtime.swing.renderer.DecoratorListCellRenderer; +import jaxx.runtime.swing.renderer.EnumEditorRenderer; +import jaxx.runtime.validator.swing.SwingValidatorUtil; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.jdesktop.swingx.JXDatePicker; +import org.jdesktop.swingx.JXMonthView; +import org.jdesktop.swingx.autocomplete.ComboBoxCellEditor; +import org.jdesktop.swingx.autocomplete.ObjectToStringConverter; +import org.nuiton.decorator.Decorator; +import org.nuiton.jaxx.application.bean.JavaBeanObjectUtil; +import org.nuiton.jaxx.widgets.datetime.DateTimeEditor; +import org.nuiton.jaxx.widgets.datetime.TimeEditor; +import org.nuiton.jaxx.widgets.gis.absolute.CoordinatesEditor; +import org.nuiton.jaxx.widgets.select.FilterableDoubleList; +import org.nuiton.util.DateUtil; + +import javax.swing.AbstractButton; +import javax.swing.ActionMap; +import javax.swing.JCheckBox; +import javax.swing.JComboBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JScrollBar; +import javax.swing.JSpinner; +import javax.swing.JTable; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.ListCellRenderer; +import javax.swing.SwingUtilities; +import javax.swing.border.LineBorder; +import javax.swing.table.TableCellEditor; +import java.awt.Color; +import java.awt.Component; +import java.awt.Dimension; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.ItemEvent; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Date; +import java.util.EnumSet; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +import static org.nuiton.i18n.I18n.t; + +/** + * To initialize ui. + * + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.7 + */ +public class ContentUIInitializer<E extends IdDto, UI extends ObserveContentUI<E>> { + + public static final String OBSERVE_ACTION = "observeAction"; + + public static final String CLIENT_PROPERTY_PROPERTY_NAME = "propertyName"; + + public static final String CLIENT_PROPERTY_RESET_PROPERTY_NAME = "resetPropertyName"; + + public static final String CLIENT_PROPERTY_NOT_BLOCKING = "notBlocking"; + + /** Logger. */ + private static final Log log = LogFactory.getLog(ContentUIInitializer.class); + + protected final UI ui; + + protected final DecoratorService decoratorService; + + public ContentUIInitializer(UI ui) { + this.ui = ui; + this.decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); + } + + public static TableCellEditor newFloatColumnEditor(JTable table) { + + NumberCellEditor<Float> editor = JAXXWidgetUtil.newNumberTableCellEditor(Float.class, false); + editor.getNumberEditor().setSelectAllTextOnError(true); + editor.getNumberEditor().getTextField().setBorder(new LineBorder(Color.GRAY, 2)); + editor.getNumberEditor().setNumberPattern("\\d{0,6}(\\.\\d{0,4})?"); + return editor; + + } + + public static TableCellEditor newIntegerColumnEditor(JTable table) { + + NumberCellEditor<Integer> editor = JAXXWidgetUtil.newNumberTableCellEditor(Integer.class, false); + editor.getNumberEditor().setSelectAllTextOnError(true); + editor.getNumberEditor().getTextField().setBorder(new LineBorder(Color.GRAY, 2)); + editor.getNumberEditor().setNumberPattern("\\d{0,4}?"); + return editor; + + } + + public static <B> ComboBoxCellEditor newDataColumnEditor(List<B> data, Decorator<B> decorator) { + + JComboBox<B> comboBox = new JComboBox<>(); + + return newDataColumnEditor(comboBox, data, decorator); + + } + + public static <B> ComboBoxCellEditor newDataColumnEditor(JComboBox<B> comboBox, List<B> data, Decorator<B> decorator) { + + ListCellRenderer<B> renderer = new DecoratorListCellRenderer(decorator); + comboBox.setRenderer(renderer); + + prepareComboBoxData(comboBox, data); + + ObjectToStringConverter converter = BeanUIUtil.newDecoratedObjectToStringConverter(decorator); + BeanUIUtil.decorate(comboBox, converter); + ComboBoxCellEditor editor = new ComboBoxCellEditor(comboBox); + return editor; + + } + + public static <B> void prepareComboBoxData(JComboBox comboBox, List<B> data) { + List<B> dataToList = Lists.newArrayList(data); + + // add a null value at first position + if (!dataToList.isEmpty() && dataToList.get(0) != null) { + dataToList.add(0, null); + } + SwingUtil.fillComboBox(comboBox, dataToList, null); + } + + protected E getBean() { + + E bean = ui.getModel().getBean(); + return bean; + + } + + protected Form<E> getFormDto() { + return ui.getModel().getForm(); + } + + public void initUI() { + + if (log.isDebugEnabled()) { + log.debug("ui " + getClass()); + } + + ActionMap actionMap = ObserveSwingApplicationContext.get().getActionMap(); + + // initialisation des éditeurs + + Set<String> doNotBlockComponentIds = new HashSet<>(); + + for (String name : ui.get$objectMap().keySet()) { + Object o = ui.getObjectById(name); + + if (o == null) { + continue; + } + + if (o instanceof JComponent) { + + init((JComponent) o, doNotBlockComponentIds); + } + + if (o instanceof JCheckBox) { + init((JCheckBox) o); + } + + if (o instanceof AbstractButton) { + init(actionMap, (AbstractButton) o); + continue; + } + + if (o instanceof NumberEditor) { + init((NumberEditor) o); + continue; + } + + if (o instanceof BeanComboBox<?>) { + init((BeanComboBox<?>) o); + continue; + } + + if (o instanceof BeanListHeader<?>) { + init((BeanListHeader) o); + continue; + } + + if (o instanceof FilterableDoubleList<?>) { + init((FilterableDoubleList<?>) o); + continue; + } + + if (o instanceof JXDatePicker) { + init((JXDatePicker) o); + continue; + } + + if (o instanceof TimeEditor) { + init((TimeEditor) o); + continue; + } + + if (o instanceof DateTimeEditor) { + init((DateTimeEditor) o); + continue; + } + + if (o instanceof CoordinatesEditor) { + init((CoordinatesEditor) o); + continue; + } + + if (o instanceof BooleanEditor) { + init((BooleanEditor) o); + continue; + } + + if (o instanceof EnumEditor) { + init((EnumEditor) o); + continue; + } + + if (o instanceof ObserveSwingValidator<?>) { + init(ui, (ObserveSwingValidator<?>) o); + continue; + } + + if (o instanceof JTextField) { + init((JTextField) o); + continue; + } + + if (o instanceof JTextArea) { + init((JTextArea) o); + } + + } + + if (!doNotBlockComponentIds.isEmpty()) { + + String[] acceptedComponentNames = doNotBlockComponentIds.toArray(new String[doNotBlockComponentIds.size()]); + + initBlockLayerUI(acceptedComponentNames); + + } + } + + protected void initBlockLayerUI(String... doNotBlockComponentIds) { + ui.getBlockLayerUI().setAcceptedComponentTypes(ObserveMapPane.class, JScrollBar.class); + ui.getBlockLayerUI().setAcceptedComponentNames(doNotBlockComponentIds); + + } + + protected void init(UI ui, ObserveSwingValidator<?> validator) { + SwingValidatorUtil.listenValidatorContextNameAndRefreshFields( + validator, + (JAXXValidator) ui + ); + } + + protected void init(ActionMap actionMap, AbstractButton editor) { + String actionId = (String) editor.getClientProperty(OBSERVE_ACTION); + if (actionId == null) { + // le boutton n'est pas commun + + final String propertyName = (String) editor.getClientProperty(CLIENT_PROPERTY_RESET_PROPERTY_NAME); + if (propertyName != null) { + editor.addActionListener(e -> JavaBeanObjectUtil.setProperty(getBean(), propertyName, null)); + } + + return; + } + + // on a trouve une action commune + AbstractUIAction action = (AbstractUIAction) actionMap.get(actionId); + + if (action == null) { + + // l'action n'est pas enregistrée + throw new IllegalStateException( + "action [" + actionId + "] not found for ui " + + ui.getClass().getName()); + } + + if (log.isDebugEnabled()) { + log.debug("init common action " + actionId); + } + + action.initAction(null, editor); + } + + protected void init(NumberEditor editor) { + if (log.isDebugEnabled()) { + log.debug("init number editor " + editor.getName()); + } + editor.init(); + } + + protected void init(BeanComboBox beanComboBox) { + if (log.isDebugEnabled()) { + log.debug("init combobox for " + beanComboBox.getBeanType()); + } + beanComboBox.setI18nPrefix("observe.common."); + beanComboBox.setMinimumSize(new Dimension(0, 24)); + + Class dtoClass = getDtoClass(beanComboBox); + + if (ReferentialDto.class.isAssignableFrom(dtoClass)) { + prepareReferentialBeanComboBox(dtoClass, beanComboBox); + } else { + prepareDataBeanComboBox(dtoClass, beanComboBox); + } + + } + + protected void init(BeanListHeader beanList) { + + beanList.setI18nPrefix("observe.common."); + + if (log.isInfoEnabled()) { + log.info("init list for " + beanList.getBeanType()); + } + + Class dtoClass = getDtoClass(beanList); + + if (ReferentialDto.class.isAssignableFrom(dtoClass)) { + prepareReferentialEntityList(dtoClass, beanList); + } else { + prepareDataEntityList(dtoClass, beanList); + } + + } + + protected void init(FilterableDoubleList beanList) { + + beanList.setI18nPrefix("observe.common."); + + if (log.isInfoEnabled()) { + log.info("init list for " + beanList.getBeanType()); + } + + Class dtoClass = getDtoClass(beanList); + + if (ReferentialDto.class.isAssignableFrom(dtoClass)) { + prepareReferentialFilterableDoubleList(dtoClass, beanList); + } else { + prepareDataFilterableDoubleList(dtoClass, beanList); + } + + } + + protected void init(TimeEditor editor) { + if (log.isDebugEnabled()) { + log.debug("init time editor " + editor.getName()); + } + editor.init(); + if (isAutoSelectOnFocus(editor)) { + + addAutoSelectOnFocus((JSpinner.DateEditor) editor.getHourEditor().getEditor()); + addAutoSelectOnFocus((JSpinner.DateEditor) editor.getMinuteEditor().getEditor()); + + } + } + + protected void init(DateTimeEditor editor) { + if (log.isDebugEnabled()) { + log.debug("init date time editor " + editor.getName()); + } + editor.init(); + if (isAutoSelectOnFocus(editor)) { + + addAutoSelectOnFocus((JSpinner.DateEditor) editor.getHourEditor().getEditor()); + addAutoSelectOnFocus((JSpinner.DateEditor) editor.getMinuteEditor().getEditor()); + + } + } + + private void addAutoSelectOnFocus(JSpinner.DateEditor hourEditor) { + addAutoSelectOnFocus(hourEditor.getTextField()); + } + + protected void init(CoordinatesEditor editor) { + if (log.isDebugEnabled()) { + log.debug("init coordinates editor " + editor.getName()); + } + editor.init(); + } + + protected void init(JTextField editor) { + + final String propertyName = (String) editor.getClientProperty(CLIENT_PROPERTY_PROPERTY_NAME); + if (propertyName != null) { + editor.addKeyListener(new KeyAdapter() { + + @Override + public void keyReleased(KeyEvent e) { + JTextField source = (JTextField) e.getSource(); + String text = source.getText(); + JavaBeanObjectUtil.setProperty(getBean(), propertyName, text); + } + }); + } + } + + protected void init(JTextArea editor) { + + final String propertyName = (String) editor.getClientProperty(CLIENT_PROPERTY_PROPERTY_NAME); + if (propertyName != null) { + editor.addKeyListener(new KeyAdapter() { + + @Override + public void keyReleased(KeyEvent e) { + JTextArea source = (JTextArea) e.getSource(); + String text = source.getText(); + JavaBeanObjectUtil.setProperty(getBean(), propertyName, text); + } + }); + } + } + + protected void init(BooleanEditor editor) { + if (log.isDebugEnabled()) { + log.debug("init boolean editor " + editor.getName()); + } + final String propertyName = (String) editor.getClientProperty(CLIENT_PROPERTY_PROPERTY_NAME); + if (propertyName != null) { + editor.addItemListener(event -> { + if (event.getStateChange() == ItemEvent.SELECTED) { + + Boolean newValue = ((BooleanEditor) event.getSource()).getBooleanValue(); + JavaBeanObjectUtil.setProperty(getBean(), propertyName, newValue); + } + }); + } + } + + protected void init(JComponent editor, Set<String> notBlockingComponents) { + final Boolean propertyName = (Boolean) editor.getClientProperty(CLIENT_PROPERTY_NOT_BLOCKING); + if (propertyName != null) { + + if (editor instanceof FilterableDoubleList) { + + notBlockingComponents.add("universeListPane"); + notBlockingComponents.add("selectedListPane"); + + } else { + + notBlockingComponents.add(editor.getName()); + + } + } + } + + protected void init(JCheckBox editor) { + if (log.isDebugEnabled()) { + log.debug("init simple boolean editor " + editor.getName()); + } + final String propertyName = (String) editor.getClientProperty(CLIENT_PROPERTY_PROPERTY_NAME); + if (propertyName != null) { + editor.addItemListener(event -> { + Boolean newValue = ((JCheckBox) event.getSource()).isSelected(); + JavaBeanObjectUtil.setProperty(getBean(), propertyName, newValue); + }); + } + } + + protected void init(JXDatePicker picker) { + + if (log.isDebugEnabled()) { + log.debug("disable JXDatePicker editor" + picker.getName()); + } + picker.getEditor().setEditable(false); + JXMonthView monthView = new JXMonthView(); + monthView.setLowerBound(DateUtil.createDate(1, 1, 1970)); + monthView.setTraversable(true); + monthView.setZoomable(true); + picker.setMonthView(monthView); + + final String propertyName = (String) picker.getClientProperty(CLIENT_PROPERTY_PROPERTY_NAME); + if (propertyName != null) { + picker.addActionListener(e -> { + JXDatePicker source = (JXDatePicker) e.getSource(); + Date date = source.getDate(); + JavaBeanObjectUtil.setProperty(getBean(), propertyName, date); + }); + } + + } + + protected <B extends Enum<B>> void init(EnumEditor<B> editor) { + if (log.isDebugEnabled()) { + log.debug("init enumEditor editor " + editor.getName()); + } + ImmutableMap.Builder<B, String> labelsBuilder = ImmutableMap.builder(); + for (B e : EnumSet.allOf(editor.getType())) { + String label = I18nEnumUtil.getLabel(e); + labelsBuilder.put(e, label); + } + editor.setRenderer(new EnumEditorRenderer<>(labelsBuilder.build())); + } + + protected boolean isAutoSelectOnFocus(JComponent comp) { + Boolean selectOnFocus = (Boolean) comp.getClientProperty("selectOnFocus"); + return BooleanUtils.isTrue(selectOnFocus); + } + + protected void addAutoSelectOnFocus(JTextField jTextField) { + jTextField.addFocusListener(new FocusAdapter() { + + @Override + public void focusGained(final FocusEvent e) { + SwingUtilities.invokeLater(() -> { + JTextField source = (JTextField) e.getSource(); + source.selectAll(); + }); + + } + }); + } + + /** + * Ajoute à une liste graphique donnée le comportement de + * sélection-déselection en un seul click. + * + * TODO: il faudrait que cela ne perturbe pas le comportement des raccourcis clavier. + * + * @param list la liste graphique à traiter + */ + protected void prepareToogleListSelectionModel(JList list) { + + OneClicListSelectionModel model = new OneClicListSelectionModel(list.getSelectionModel(), list.getModel()); + list.setSelectionModel(model); + + } + + /** + * Remplit le modèle d'une liste graphique avec la liste des entités d'un + * type donné sur un service de persistance donné. + * + * @param list le component graphique à initialiser + * @since 1.5 + */ + protected <D extends DataDto> void prepareDataFilterableDoubleList(Class<D> dtoClass, FilterableDoubleList<DataReference<D>> list) { + + DataReferenceDecorator<D> decorator = decoratorService.getDataReferenceDecorator(dtoClass); + if (log.isDebugEnabled()) { + log.debug("Will use decorator " + decorator); + } + + String entityLabel = t(DecoratorService.getEntityLabel(dtoClass)); + list.getPopupSortLabel().setText(t("observe.content.type.data", entityLabel)); + + list.putClientProperty("decorator", decorator); + + list.init(decorator, new ArrayList<>(), new ArrayList<>()); + + JList<AbstractReference<D>> selectedList = list.getSelectedList(); + ListCellRenderer<? super AbstractReference<D>> renderer = selectedList.getCellRenderer(); + + selectedList.setCellRenderer(new ReferentielListCellRenderer<>(renderer)); + list.getUniverseList().setCellRenderer(new ReferentielListCellRenderer<>((ListCellRenderer<? super AbstractReference<IdDto>>) renderer)); + + } + + /** + * Remplit le modèle d'une liste graphique avec la liste des entités d'un + * type donné sur un service de persistance donné. + * + * @param list le component graphique à initialiser + * @since 1.5 + */ + protected <D extends ReferentialDto> void prepareReferentialFilterableDoubleList(Class<D> dtoClass, FilterableDoubleList<ReferentialReference<D>> list) { + + ReferentialReferenceDecorator<D> decorator = decoratorService.getReferentialReferenceDecorator(dtoClass); + if (log.isDebugEnabled()) { + log.debug("Will use decorator " + decorator); + } + + String entityLabel = t(DecoratorService.getEntityLabel(dtoClass)); + list.getPopupSortLabel().setText(t("observe.content.type.referential", entityLabel)); + + list.putClientProperty("decorator", decorator); + + list.init(decorator, new ArrayList<>(), new ArrayList<>()); + + JList<AbstractReference<D>> selectedList = list.getSelectedList(); + ListCellRenderer<? super AbstractReference<D>> renderer = selectedList.getCellRenderer(); + + selectedList.setCellRenderer(new ReferentielListCellRenderer<>(renderer)); + list.getUniverseList().setCellRenderer(new ReferentielListCellRenderer<>((ListCellRenderer<? super AbstractReference<IdDto>>) renderer)); + + } + + /** + * Remplit le modèle d'une liste graphique avec la liste des entités d'un + * type donné sur un service de persistance donné. + * + * @param list le component graphique à initialiser + * @since 1.5 + */ + protected <D extends DataDto> void prepareDataEntityList(Class<D> dtoClass, BeanListHeader<DataReference<D>> list) { + + DataReferenceDecorator<D> decorator = decoratorService.getDataReferenceDecorator(dtoClass); + if (log.isDebugEnabled()) { + log.debug("Will use decorator " + decorator); + } + + String entityLabel = t(DecoratorService.getEntityLabel(dtoClass)); + list.setPopupTitleText(t("observe.content.type.data", entityLabel)); + + list.putClientProperty("decorator", decorator); + + list.init(decorator, Collections.emptyList()); + + JList<AbstractReference<D>> list1 = list.getList(); + ListCellRenderer<? super AbstractReference<D>> renderer = list1.getCellRenderer(); + list1.setCellRenderer(new ReferentielListCellRenderer<>(renderer)); + + } + + /** + * Remplit le modèle d'une liste graphique avec la liste des entités d'un + * type donné sur un service de persistance donné. + * + * @param list le component graphique à initialiser + * @since 1.5 + */ + protected <D extends ReferentialDto> void prepareReferentialEntityList(Class<D> dtoClass, BeanListHeader<ReferentialReference<D>> list) { + + ReferentialReferenceDecorator<D> decorator = decoratorService.getReferentialReferenceDecorator(dtoClass); + if (log.isDebugEnabled()) { + log.debug("Will use decorator " + decorator); + } + + String entityLabel = t(DecoratorService.getEntityLabel(dtoClass)); + list.setPopupTitleText(t("observe.content.type.referential", entityLabel)); + + list.putClientProperty("decorator", decorator); + + list.init(decorator, Collections.emptyList()); + + JList<AbstractReference<D>> list1 = list.getList(); + ListCellRenderer<? super AbstractReference<D>> renderer = list1.getCellRenderer(); + list1.setCellRenderer(new ReferentielListCellRenderer<>(renderer)); + + } + + /** + * Prépare un component de choix d'entités pour un type d'entité donné et pour un service de persistance donné. + * + * @param <D> le type de l'entité + * @param comboBox le component graphique à initialiser + */ + protected <D extends DataDto> void prepareDataBeanComboBox(Class<D> dtoClass, BeanComboBox<DataReference<D>> comboBox) { + + DataReferenceDecorator<D> decorator = decoratorService.getDataReferenceDecorator(dtoClass); + + String entityLabel = t(DecoratorService.getEntityLabel(dtoClass)); + comboBox.setPopupTitleText(t("observe.content.type.data", entityLabel)); + + comboBox.init(decorator, Collections.emptyList()); + + JComboBox<DataReference<D>> combobox = comboBox.getCombobox(); + + ListCellRenderer<DataReference<D>> toolTipRenderer = new ComboBoxListCellRenderer<>(combobox.getRenderer()); + combobox.setRenderer(toolTipRenderer); + if (log.isDebugEnabled()) { + log.debug("combo list [" + dtoClass.getName() + "] : " + comboBox.getData().size()); + } + + } + + /** + * Prépare un component de choix d'entités pour un type d'entité donné et pour un service de persistance donné. + * + * @param <D> le type de l'entité + * @param comboBox le component graphique à initialiser + */ + protected <D extends ReferentialDto> void prepareReferentialBeanComboBox(Class<D> dtoClass, BeanComboBox<ReferentialReference<D>> comboBox) { + + ReferentialReferenceDecorator<D> decorator = decoratorService.getReferentialReferenceDecorator(dtoClass); + + String entityLabel = t(DecoratorService.getEntityLabel(dtoClass)); + comboBox.setPopupTitleText(t("observe.content.type.referential", entityLabel)); + + comboBox.init(decorator, Collections.emptyList()); + + JComboBox<ReferentialReference<D>> combobox = comboBox.getCombobox(); + + ListCellRenderer<ReferentialReference<D>> toolTipRenderer = new ComboBoxListCellRenderer<>(combobox.getRenderer()); + combobox.setRenderer(toolTipRenderer); + if (log.isDebugEnabled()) { + log.debug("combo list [" + dtoClass.getName() + "] : " + comboBox.getData().size()); + } + + } + + protected <D extends IdDto> Class<D> getDtoClass(JComponent list) { + Object clientProperty = list.getClientProperty(ObserveContentUI.CLIENT_PROPERTY_ENTITY_CLASS); + return (Class<D>) clientProperty; + } + + /** + * Un renderer de liste d'entites d'un referentiel dans le quel on veut + * differencier les entites qui sont desactivees. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.2 + */ + public static class ReferentielListCellRenderer<D extends IdDto> implements ListCellRenderer<AbstractReference<D>> { + + /** la couleur normal pour les entites non desactivees */ + protected Color normalColor; + + /** la couleur a utiliser pour les entites desactivees */ + protected Color disableColor = Color.LIGHT_GRAY; + + protected ListCellRenderer<? super AbstractReference<D>> delegate; + + public ReferentielListCellRenderer(ListCellRenderer<? super AbstractReference<D>> delegate) { + this.delegate = delegate; + } + + @Override + public Component getListCellRendererComponent(JList<? extends AbstractReference<D>> list, AbstractReference<D> value, int index, boolean isSelected, boolean cellHasFocus) { + JComponent comp; + comp = (JComponent) delegate.getListCellRendererComponent( + list, + value, + index, + isSelected, + cellHasFocus); + if (normalColor == null) { + // premiere fois, on intialise la couleur dite normale + normalColor = comp.getForeground(); + } + + String tip = null; + + // par defaut, on utilise la couleur normale + Color col = normalColor; + if (value != null) { + + boolean enabled = true; + + if (value instanceof ReferentialReference<?>) { + + ReferentialReference e = (ReferentialReference) value; + enabled = e.isEnabled(); + + } + + if (!enabled) { + // l'entite est desactivee + // on la grise pour bien la differencier + col = disableColor; + tip = t("observe.common.obsolete.entity", ((JLabel) comp).getText()); + } + } + comp.setForeground(col); + comp.setToolTipText(tip); + return comp; + } + + } + + private static class ComboBoxListCellRenderer<E> implements ListCellRenderer<E> { + + private final ListCellRenderer<? super E> renderer; + + public ComboBoxListCellRenderer(ListCellRenderer<? super E> renderer) { + this.renderer = renderer; + } + + @Override + public Component getListCellRendererComponent(JList<? extends E> list, + E value, + int index, + boolean isSelected, + boolean cellHasFocus) { + Component comp = renderer.getListCellRendererComponent( + list, + value, + index, + isSelected, + cellHasFocus + ); + if (comp instanceof JLabel) { + JLabel jcomp = (JLabel) comp; + jcomp.setToolTipText(jcomp.getText()); + } + return comp; + } + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ContentUIManager.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ContentUIManager.java new file mode 100644 index 0000000..0f639f5 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ContentUIManager.java @@ -0,0 +1,447 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.constants.GearType; +import fr.ird.observe.services.dto.longline.ActivityLonglineDto; +import fr.ird.observe.services.dto.longline.ActivityLonglineEncounterDto; +import fr.ird.observe.services.dto.longline.ActivityLonglineSensorUsedDto; +import fr.ird.observe.services.dto.longline.SetLonglineCatchDto; +import fr.ird.observe.services.dto.longline.SetLonglineDto; +import fr.ird.observe.services.dto.longline.SetLonglineTdrDto; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialDtos; +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.services.dto.seine.ActivitySeineObservedSystemDto; +import fr.ird.observe.services.dto.seine.FloatingObjectDto; +import fr.ird.observe.services.dto.seine.FloatingObjectObservedSpeciesDto; +import fr.ird.observe.services.dto.seine.FloatingObjectSchoolEstimateDto; +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.services.dto.seine.SetSeineDto; +import fr.ird.observe.services.dto.seine.SetSeineNonTargetCatchDto; +import fr.ird.observe.services.dto.seine.SetSeineSchoolEstimateDto; +import fr.ird.observe.services.dto.seine.SetSeineTargetCatchDto; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.impl.longline.LonglineDetailCompositionUI; +import fr.ird.observe.application.swing.ui.content.impl.longline.LonglineGlobalCompositionUI; +import fr.ird.observe.application.swing.ui.content.impl.longline.SetLonglineUI; +import fr.ird.observe.application.swing.ui.content.impl.seine.ActivitySeineObservedSystemUI; +import fr.ird.observe.application.swing.ui.content.impl.seine.FloatingObjectTransmittingBuoyOperationUI; +import fr.ird.observe.application.swing.ui.content.impl.seine.FloatingObjectUI; +import fr.ird.observe.application.swing.ui.content.impl.seine.SetSeineUI; +import fr.ird.observe.application.swing.ui.content.list.impl.longline.ActivityLonglinesUI; +import fr.ird.observe.application.swing.ui.content.list.impl.longline.TripLonglinesUI; +import fr.ird.observe.application.swing.ui.content.list.impl.seine.ActivitySeinesUI; +import fr.ird.observe.application.swing.ui.content.list.impl.seine.RoutesUI; +import fr.ird.observe.application.swing.ui.content.list.impl.seine.TripSeinesUI; +import fr.ird.observe.application.swing.ui.content.open.impl.longline.ActivityLonglineUI; +import fr.ird.observe.application.swing.ui.content.open.impl.longline.TripLonglineUI; +import fr.ird.observe.application.swing.ui.content.open.impl.seine.ActivitySeineUI; +import fr.ird.observe.application.swing.ui.content.open.impl.seine.RouteUI; +import fr.ird.observe.application.swing.ui.content.open.impl.seine.TripSeineUI; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI; +import fr.ird.observe.application.swing.ui.content.ref.ReferenceHomeUI; +import fr.ird.observe.application.swing.ui.content.table.impl.longline.CatchLonglineUI; +import fr.ird.observe.application.swing.ui.content.table.impl.longline.EncounterUI; +import fr.ird.observe.application.swing.ui.content.table.impl.longline.GearUseFeaturesLonglineUI; +import fr.ird.observe.application.swing.ui.content.table.impl.longline.SensorUsedUI; +import fr.ird.observe.application.swing.ui.content.table.impl.longline.TdrUI; +import fr.ird.observe.application.swing.ui.content.table.impl.seine.GearUseFeaturesSeineUI; +import fr.ird.observe.application.swing.ui.content.table.impl.seine.NonTargetCatchUI; +import fr.ird.observe.application.swing.ui.content.table.impl.seine.NonTargetSampleUI; +import fr.ird.observe.application.swing.ui.content.table.impl.seine.ObjectObservedSpeciesUI; +import fr.ird.observe.application.swing.ui.content.table.impl.seine.ObjectSchoolEstimateUI; +import fr.ird.observe.application.swing.ui.content.table.impl.seine.SchoolEstimateUI; +import fr.ird.observe.application.swing.ui.content.table.impl.seine.TargetCatchUI; +import fr.ird.observe.application.swing.ui.content.table.impl.seine.TargetDiscardCatchUI; +import fr.ird.observe.application.swing.ui.content.table.impl.seine.TargetSampleCaptureUI; +import fr.ird.observe.application.swing.ui.content.table.impl.seine.TargetSampleRejeteUI; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import jaxx.runtime.JAXXContext; +import jaxx.runtime.context.JAXXInitialContext; +import jaxx.runtime.swing.CardLayout2; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JComponent; +import javax.swing.JPanel; +import java.awt.Component; +import java.lang.reflect.Constructor; +import java.util.Map; +import java.util.TreeMap; + +import static org.nuiton.i18n.I18n.n; + +/** + * Manager des ecrans d'editions + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ContentUIManager { + + public static final String REFERENCE = "reference"; + + public static final String DATA = "data"; + + /** Logger */ + static private final Log log = LogFactory.getLog(ContentUIManager.class); + +// /** L'ui qui utilise le manager */ +// protected final ObserveMainUI ui; + + protected final Map<String, Class<? extends ObserveContentUI<?>>> mapping; + + protected ObserveMainUI getMainUI() { + return ObserveSwingApplicationContext.get().getMainUI(); + } + + public ContentUIManager() { + +// this.ui = ui; + mapping = new TreeMap<>(); + + // --- Seine data --- // + addMapping(DATA, ProgramDto.class, GearType.seine.name(), TripSeinesUI.class); + + addMapping(DATA, TripSeineDto.class, TripSeineUI.class); + addMapping(DATA, TripSeineDto.class, n("observe.tree.tripSeine.unsaved"), TripSeineUI.class); + addMapping(DATA, TripSeineDto.class, "gearUseFeaturesSeine", GearUseFeaturesSeineUI.class); + addMapping(DATA, TripSeineDto.class, TripSeineDto.PROPERTY_ROUTE, RoutesUI.class); + + addMapping(DATA, RouteDto.class, RouteUI.class); + addMapping(DATA, RouteDto.class, n("observe.tree.route.unsaved"), RouteUI.class); + addMapping(DATA, RouteDto.class, RouteDto.PROPERTY_ACTIVITY_SEINE, ActivitySeinesUI.class); + + addMapping(DATA, ActivitySeineDto.class, ActivitySeineUI.class); + addMapping(DATA, ActivitySeineDto.class, n("observe.tree.activitySeine.unsaved"), ActivitySeineUI.class); + addMapping(DATA, ActivitySeineDto.class, ActivitySeineObservedSystemDto.PROPERTY_OBSERVED_SYSTEM, ActivitySeineObservedSystemUI.class); + + addMapping(DATA, SetSeineDto.class, SetSeineUI.class); + addMapping(DATA, SetSeineDto.class, n("observe.tree.setSeine.unsaved"), SetSeineUI.class); + addMapping(DATA, SetSeineDto.class, SetSeineSchoolEstimateDto.PROPERTY_SCHOOL_ESTIMATE, SchoolEstimateUI.class); + addMapping(DATA, SetSeineDto.class, SetSeineTargetCatchDto.PROPERTY_TARGET_CATCH, TargetCatchUI.class); + addMapping(DATA, SetSeineDto.class, SetSeineDto.PROPERTY_TARGET_DISCARDED, TargetDiscardCatchUI.class); + addMapping(DATA, SetSeineDto.class, SetSeineDto.PROPERTY_TARGET_SAMPLE_CAPTURE, TargetSampleCaptureUI.class); + addMapping(DATA, SetSeineDto.class, SetSeineNonTargetCatchDto.PROPERTY_NON_TARGET_CATCH, NonTargetCatchUI.class); + + addMapping(DATA, SetSeineDto.class, "targetSample", TargetSampleRejeteUI.class); + addMapping(DATA, SetSeineDto.class, "nonTargetSample", NonTargetSampleUI.class); + + addMapping(DATA, FloatingObjectDto.class, FloatingObjectUI.class); + addMapping(DATA, FloatingObjectDto.class, n("observe.tree.floatingObject.unsaved"), FloatingObjectUI.class); + addMapping(DATA, FloatingObjectDto.class, FloatingObjectDto.PROPERTY_OBJECT_OPERATION, FloatingObjectTransmittingBuoyOperationUI.class); + addMapping(DATA, FloatingObjectDto.class, FloatingObjectObservedSpeciesDto.PROPERTY_OBJECT_OBSERVED_SPECIES, ObjectObservedSpeciesUI.class); + addMapping(DATA, FloatingObjectDto.class, FloatingObjectSchoolEstimateDto.PROPERTY_OBJECT_SCHOOL_ESTIMATE, ObjectSchoolEstimateUI.class); + + // --- Longline data --- // + + addMapping(DATA, ProgramDto.class, GearType.longline.name(), TripLonglinesUI.class); + + addMapping(DATA, TripLonglineDto.class, TripLonglineUI.class); + addMapping(DATA, TripLonglineDto.class, n("observe.tree.tripLongline.unsaved"), TripLonglineUI.class); + addMapping(DATA, TripLonglineDto.class, "gearUseFeaturesLongline", GearUseFeaturesLonglineUI.class); + addMapping(DATA, TripLonglineDto.class, TripLonglineDto.PROPERTY_ACTIVITY_LONGLINE, ActivityLonglinesUI.class); + + addMapping(DATA, ActivityLonglineDto.class, ActivityLonglineUI.class); + addMapping(DATA, ActivityLonglineDto.class, n("observe.tree.activityLongline.unsaved"), ActivityLonglineUI.class); + addMapping(DATA, ActivityLonglineDto.class, ActivityLonglineEncounterDto.PROPERTY_ENCOUNTER, EncounterUI.class); + addMapping(DATA, ActivityLonglineDto.class, ActivityLonglineSensorUsedDto.PROPERTY_SENSOR_USED, SensorUsedUI.class); + + addMapping(DATA, SetLonglineDto.class, SetLonglineUI.class); + addMapping(DATA, SetLonglineDto.class, n("observe.tree.setLongline.unsaved"), SetLonglineUI.class); + addMapping(DATA, SetLonglineDto.class, "longlineGlobalComposition", LonglineGlobalCompositionUI.class); + addMapping(DATA, SetLonglineDto.class, "longlineDetailComposition", LonglineDetailCompositionUI.class); + + addMapping(DATA, SetLonglineDto.class, SetLonglineCatchDto.PROPERTY_CATCH_LONGLINE, CatchLonglineUI.class); + addMapping(DATA, SetLonglineDto.class, SetLonglineTdrDto.PROPERTY_TDR, TdrUI.class); + + // --- Referential --- // + + for (Class<? extends ReferentialDto> editType : ReferentialDtos.REFERENCE_COMMON_DTOS) { + String simpleName = StringUtils.removeEnd(editType.getSimpleName(), "Dto"); + String fqn = ContentReferenceUI.class.getPackage().getName() + ".impl." + simpleName + "UI"; + Class<?> result; + try { + result = Class.forName(fqn); + addMapping(REFERENCE, editType, null, result); + } catch (ClassNotFoundException e) { + throw new IllegalStateException("Could not find " + fqn); + } + } + + for (Class<? extends ReferentialDto> editType : ReferentialDtos.REFERENCE_SEINE_DTOS) { + String simpleName = StringUtils.removeEnd(editType.getSimpleName(), "Dto"); + String fqn = ContentReferenceUI.class.getPackage().getName() + ".impl.seine." + simpleName + "UI"; + Class<?> result; + try { + result = Class.forName(fqn); + addMapping(REFERENCE, editType, null, result); + } catch (ClassNotFoundException e) { + throw new IllegalStateException("Could not find " + fqn); + } + } + + for (Class<? extends ReferentialDto> editType : ReferentialDtos.REFERENCE_LONGLINE_DTOS) { + String simpleName = StringUtils.removeEnd(editType.getSimpleName(), "Dto"); + String fqn = ContentReferenceUI.class.getPackage().getName() + ".impl.longline." + simpleName + "UI"; + Class<?> result; + try { + result = Class.forName(fqn); + addMapping(REFERENCE, editType, null, result); + } catch (ClassNotFoundException e) { + throw new IllegalStateException("Could not find " + fqn); + } + } + + addMapping(REFERENCE, null, ReferenceHomeUI.class); + + } + + public Class<? extends ObserveContentUI<?>> convertNodeToContentUI(ObserveNode node) { + if (log.isDebugEnabled()) { + log.debug("Entrer for node = " + node); + } + if (node.isRoot()) { + return null; + } + + Class<?> editType = node.getInternalClass(); + String prefix = node.isReferentielNode() ? REFERENCE : DATA; + String context = node.getContext(); + + String mappingKey; + + if (node.isReferentielNode()) { + + if (String.class.equals(editType)) { + editType = null; + } + + } else { + + // noeud de donnee + if (String.class.equals(editType)) { + editType = node.getContainerNode().getInternalClass(); + } + } + + mappingKey = getMappingKey(prefix, editType, context); + if (mappingKey == null) { + throw new NullPointerException("Could not find mappingKey for node " + node); + } + if (log.isDebugEnabled()) { + log.debug("mappingKey = [" + mappingKey + "] for node " + node); + } + Class<? extends ObserveContentUI<?>> result = mapping.get(mappingKey); + + return result; + } + + @SuppressWarnings({"unchecked"}) + public <U extends ObserveContentUI<?>> U getContent(Class<U> uiClass) { + + CardLayout2 layout = getLayout(); + JPanel layoutContent = getLayoutContent(); + String constraints = uiClass.getName(); + + if (!layout.contains(constraints)) { + + // pas trouvé + return null; + } + + U content = (U) layout.getComponent(layoutContent, constraints); + + if (log.isDebugEnabled()) { + log.debug("Will use existing content [" + constraints + "] : " + content.getClass().getName()); + } + return content; + } + + public <U extends ObserveContentUI<?>> U createContent(Class<U> uiClass) { + + String constraints = uiClass.getName(); + + if (getLayout().contains(constraints)) { + throw new IllegalStateException("Already existing constrainst [" + constraints + "]"); + } + U result; + try { + Constructor<U> constructor = uiClass.getConstructor(JAXXContext.class); + if (log.isDebugEnabled()) { + log.debug("create new content : " + uiClass); + } + result = constructor.newInstance(new JAXXInitialContext().add(getMainUI())); + } catch (Exception e) { + throw new IllegalStateException("Could not create content ui " + uiClass, e); + } + + try { + + // ajout du content dans son parent + getLayoutContent().add((JComponent) result, constraints); + + if (log.isDebugEnabled()) { + log.debug("Add new content [" + constraints + "] : " + result.getClass().getName()); + } + + // initialisation du content + result.init(); + + return result; + } catch (Exception e) { + throw new IllegalStateException("Could not init content ui " + uiClass, e); + } + } + + public ObserveContentUI<?> getCurrentContent() { + ObserveContentUI<?> component = (ObserveContentUI<?>) + getLayout().getVisibleComponent(getLayoutContent()); + return component; + } + + public void openContent(ObserveContentUI<?> content) { + + String constraints = content.getClass().getName(); + + if (log.isDebugEnabled()) { + log.debug("Will open ui [" + constraints + "] : " + content.getClass()); + } + + // on ouvre l'ui + try { + content.open(); + + } catch (Exception e) { + UIHelper.handlingError(e); + } finally { + + // on affiche l'ui quoi qu'il arrive ? + getLayout().show(getLayoutContent(), constraints); + } + } + + public void close() { + getLayout().reset(getLayoutContent()); + } + + public ContentUI<?> getSelectedContentUI() { + + ObserveMainUI ui = getMainUI(); + return getSelectedContentUI(ui); + } + + public boolean closeSelectedContentUI() { + ObserveMainUI ui = getMainUI(); + return closeSelectedContentUI(ui); + } + + public ContentUI<?> getSelectedContentUI(ObserveMainUI ui) { + + ContentUI<?> result = null; + + if (ui == null) { + // no ui, so no modification + return result; + } + + CardLayout2 layout = ui.getContentLayout(); + JPanel container = ui.getContent(); + Component currentContent = layout.getVisibleComponent(container); + if (currentContent != null && + currentContent instanceof ContentUI<?>) { + + result = (ContentUI<?>) currentContent; + } + return result; + } + + /** + * Essaye de fermer l'écran d'édition s'il existe. + * + * @param mainUI l'ui principale + * @return {@code true} si le contenu a bien été fermé, {@code false} si on + * ne peut pas fermer l'écran + * @since 1.5 + */ + public boolean closeSelectedContentUI(ObserveMainUI mainUI) { + ContentUI<?> ui = getSelectedContentUI(mainUI); + if (ui == null) { + // no content ui + return true; + } + boolean closed = false; + try { + closed = ui.close(); + } catch (Exception e) { + UIHelper.handlingError(e); + } + return closed; + } + + protected JPanel getLayoutContent() { + JPanel content = getMainUI().getContent(); + return content; + } + + protected CardLayout2 getLayout() { + CardLayout2 layout = getMainUI().getContentLayout(); + return layout; + } + + @Override + protected void finalize() throws Throwable { + super.finalize(); + close(); + } + + protected void addMapping(String prefix, Class<?> klass, Class<? extends ObserveContentUI<?>> contentClass) { + addMapping(prefix, klass, null, contentClass); + } + + @SuppressWarnings({"unchecked"}) + protected void addMapping(String prefix, Class<?> klass, String context, Class<?> contentClass) { + String key = getMappingKey(prefix, klass, context); + mapping.put(key, (Class<? extends ContentUI<?>>) contentClass); + } + + protected String getMappingKey(String prefix, Class<?> klass, String context) { + String key = prefix + "."; + if (klass != null) { + key += klass.getName(); + } + if (context != null) { + if (klass != null) { + key += "#"; + } + key += context; + } + return key; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ContentUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ContentUIModel.java new file mode 100644 index 0000000..b4154e2 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ContentUIModel.java @@ -0,0 +1,335 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content; + +import com.google.common.collect.ImmutableMap; +import fr.ird.observe.application.swing.ObserveSwingTechnicalException; +import fr.ird.observe.services.dto.DataDto; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.DataReferenceSet; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.ReferentialReferenceSet; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.jdesktop.beans.AbstractSerializableBean; + +import java.util.Objects; +import java.util.Optional; +import java.util.Set; + +/** + * Le modèle d'un écran d'édition + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public abstract class ContentUIModel<E extends IdDto> extends AbstractSerializableBean { + + public static final String PROPERTY_EDIT_BEAN = "editBean"; + + public static final String PROPERTY_MODE = "mode"; + + public static final String PROPERTY_READING_MODE = "readingMode"; + + public static final String PROPERTY_CREATING_MODE = "creatingMode"; + + public static final String PROPERTY_UPDATING_MODE = "updatingMode"; + + public static final String PROPERTY_ENABLED = "enabled"; + + public static final String PROPERTY_MODIFIED = "modified"; + + public static final String PROPERTY_EDITING = "editing"; + + public static final String PROPERTY_EDITABLE = "editable"; + + public static final String PROPERTY_VALID = "valid"; + + public static final String PROPERTY_CAN_WRITE = "canWrite"; + + public static final String PROPERTY_FORM = "form"; + + /** Logger */ + static private final Log log = LogFactory.getLog(ContentUIModel.class); + + private static final long serialVersionUID = 1L; + + protected final Class<E> beanType; + + protected Form<E> form; + + protected E bean; + + protected ContentMode mode = ContentMode.READ; + + protected boolean enabled; + + protected boolean editing; + + protected boolean valid; + + protected boolean modified; + + protected boolean editable; + + protected boolean canWrite; + + /** + * Les référentiels qu'on peut utiliser, ils sont chargés depuis le cache des référentiels et peuvent être filtrés. + */ + protected ImmutableMap<String, ReferentialReferenceSet<?>> referentialReferenceSetsByPropertyName = ImmutableMap.of(); + + /** + * Les données métier qu'on peut utiliser. + */ + protected ImmutableMap<String, DataReferenceSet<?>> dataReferenceSetsByPropertyName = ImmutableMap.of(); + + public static <E extends IdDto> ContentUIModel<E> newModel(ObserveContentUI<E> ui) { + + String uiName = ui.getClass().getName(); + String modelName = uiName + "Model"; + + try { + + Class<ContentUIModel<E>> modelClass = (Class<ContentUIModel<E>>) Class.forName(modelName); + ContentUIModel<E> model = modelClass.newInstance(); + return model; + + } catch (Exception e) { + throw new ObserveSwingTechnicalException("Could not create model for ui: " + ui, e); + } + + } + + public ContentUIModel(Class<E> beanType) { + this.beanType = beanType; + try { + setBean(beanType.newInstance()); + + } catch (Exception e) { + // ne devrait jamain arrive + if (log.isErrorEnabled()) { + log.error(e); + } + } + + } + + public E getBean() { + return bean; + } + + public void setBean(E bean) { + Object oldValue = this.bean; + this.bean = bean; + firePropertyChange(PROPERTY_EDIT_BEAN, oldValue, bean); + } + + public Form<E> getForm() { + return form; + } + + public void setForm(Form<E> form) { + Object oldValue = getForm(); + this.form = form; + firePropertyChange(PROPERTY_FORM, oldValue, form); + } + + public ContentMode getMode() { + return mode; + } + + public void setMode(ContentMode mode) { + ContentMode oldValue = this.mode; + this.mode = mode; + firePropertyChange(PROPERTY_MODE, oldValue, mode); + firePropertyChange(PROPERTY_READING_MODE, ContentMode.READ.equals(oldValue), isReadingMode()); + firePropertyChange(PROPERTY_CREATING_MODE, ContentMode.CREATE.equals(oldValue), isCreatingMode()); + firePropertyChange(PROPERTY_UPDATING_MODE, ContentMode.UPDATE.equals(oldValue), isUpdatingMode()); + } + + /** + * @return {@code true} si l'écran est en mode creation + * @see ContentMode#CREATE + */ + public boolean isCreatingMode() { + return ContentMode.CREATE.equals(getMode()); + } + + /** + * @return {@code true} si l'écran est en mode mise a jour + * @see ContentMode#UPDATE + */ + public boolean isUpdatingMode() { + return ContentMode.UPDATE.equals(getMode()); + } + + /** + * @return {@code true} si l'écran est en mode lecture + * @see ContentMode#READ + */ + public boolean isReadingMode() { + return ContentMode.READ.equals(getMode()); + } + + public Class<E> getBeanType() { + return beanType; + } + + public boolean isEnabled() { + return enabled; + } + + public void setEnabled(boolean enabled) { + Object oldValue = this.enabled; + this.enabled = enabled; + firePropertyChange(PROPERTY_ENABLED, oldValue, enabled); + } + + public boolean isEditable() { + return editable; + } + + public void setEditable(boolean editable) { + Object oldValue = this.editable; + this.editable = editable; + firePropertyChange(PROPERTY_EDITABLE, oldValue, editable); + } + + public boolean isEditing() { + return editing; + } + + public void setEditing(boolean editing) { + Object oldValue = this.editing; + this.editing = editing; + firePropertyChange(PROPERTY_EDITING, oldValue, editing); + } + + public boolean isValid() { + return valid; + } + + public void setValid(boolean valid) { + Object oldValue = this.valid; + this.valid = valid; + firePropertyChange(PROPERTY_VALID, oldValue, valid); + } + + public boolean isModified() { + return modified; + } + + public void setModified(boolean modified) { + Object oldValue = this.modified; + this.modified = modified; + firePropertyChange(PROPERTY_MODIFIED, oldValue, modified); + } + + public boolean isCanWrite() { + return canWrite; + } + + public void setCanWrite(boolean canWrite) { + boolean oldValue = isCanWrite(); + this.canWrite = canWrite; + firePropertyChange(PROPERTY_CAN_WRITE, oldValue, canWrite); + } + + public <D extends ReferentialDto> Set<ReferentialReference<D>> getReferentialReferences(String name) { + + ReferentialReferenceSet<D> referentialReferenceSet = getReferentialReferenceSet(name); + Set<ReferentialReference<D>> references = referentialReferenceSet.getReferences(); + return references; + + } + + public <D extends DataDto> Set<DataReference<D>> getDataReferences(String name) { + + DataReferenceSet<D> referentialReferenceSet = getDataReferenceSet(name); + Set<DataReference<D>> references = referentialReferenceSet.getReferences(); + return references; + + } + + public <D extends ReferentialDto> Optional<ReferentialReference<D>> tryGetReferentialReferenceById(String name, String id) { + + ReferentialReferenceSet<D> referenceSet = getReferentialReferenceSet(name); + Optional<ReferentialReference<D>> optionalReference = referenceSet.tryGetReferenceById(id); + return optionalReference; + + } + + public void setReferentialReferenceSets(ImmutableMap<String, ReferentialReferenceSet<?>> referentialReferenceSetsByPropertyName) { + this.referentialReferenceSetsByPropertyName = referentialReferenceSetsByPropertyName; + } + + public void setDataReferenceSetsByPropertyName(ImmutableMap<String, DataReferenceSet<?>> dataReferenceSetsByPropertyName) { + this.dataReferenceSetsByPropertyName = dataReferenceSetsByPropertyName; + } + + public ImmutableMap<String, ReferentialReferenceSet<?>> getReferentialReferenceSets() { + return referentialReferenceSetsByPropertyName; + } + + public ImmutableMap<String, DataReferenceSet<?>> getDataReferenceSets() { + return dataReferenceSetsByPropertyName; + } + + protected <R extends DataDto> Optional<Set<DataReference<R>>> tryToGetDataReferenceSet(String propertyName) { + DataReferenceSet<R> referenceSet = getDataReferenceSet(propertyName); + Set<DataReference<R>> references = null; + if (referenceSet != null) { + references = referenceSet.getReferences(); + } + return Optional.ofNullable(references); + } + + protected <R extends ReferentialDto> Optional<Set<ReferentialReference<R>>> tryToGetReferentialReferenceSet(String propertyName) { + ReferentialReferenceSet<R> referenceSet = getReferentialReferenceSet(propertyName); + Set<ReferentialReference<R>> references = null; + if (referenceSet != null) { + references = referenceSet.getReferences(); + } + return Optional.ofNullable(references); + } + + protected void firePropertyChange(String propertyName, Object newValue) { + firePropertyChange(propertyName, null, newValue); + } + + private <R extends ReferentialDto> ReferentialReferenceSet<R> getReferentialReferenceSet(String propertyName) { + ImmutableMap<String, ReferentialReferenceSet<?>> referenceSet = this.referentialReferenceSetsByPropertyName; + Objects.requireNonNull(referenceSet, "Could not find referantialRefenceSet named " + propertyName); + return (ReferentialReferenceSet<R>) referenceSet.get(propertyName); + } + + public <R extends DataDto> DataReferenceSet<R> getDataReferenceSet(String propertyName) { + DataReferenceSet<?> referenceSet = dataReferenceSetsByPropertyName.get(propertyName); + Objects.requireNonNull(referenceSet, "Could not find dataReferenceSet named " + propertyName); + return (DataReferenceSet<R>) referenceSet; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ObserveContentUI.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ObserveContentUI.java new file mode 100644 index 0000000..5aebffe --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ObserveContentUI.java @@ -0,0 +1,81 @@ +package fr.ird.observe.application.swing.ui.content; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.IdDto; +import jaxx.runtime.JAXXObject; +import jaxx.runtime.swing.BlockingLayerUI; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; + +import javax.swing.Icon; +import javax.swing.JToolBar; + +/** + * Created on 10/5/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public interface ObserveContentUI<E extends IdDto> extends JAXXObject { + + String CLIENT_PROPERTY_FORCE_LOAD = "forceLoad"; + + String CLIENT_PROPERTY_LIST_NO_LOAD = "listNoLoad"; + + String CLIENT_PROPERTY_ENTITY_CLASS = "entityClass"; + + ContentUIModel<E> getModel(); + + DataContext getDataContext(); + + ObserveSwingDataSource getDataSource(); + + SwingValidatorMessageTableModel getErrorTableModel(); + + void setContentIcon(Icon icon); + + void init(); + + void open(); + + boolean close(); + + void stopEdit(); + + void startEdit(E bean); + + void restartEdit(); + + void resetEdit(); + + void save(boolean refresh); + + void delete(); + + JToolBar getTitleRightToolBar(); + + BlockingLayerUI getBlockLayerUI(); + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/BasketsTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/BasketsTableModel.java new file mode 100644 index 0000000..3c0a3c3 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/BasketsTableModel.java @@ -0,0 +1,168 @@ +package fr.ird.observe.application.swing.ui.content.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.longline.SectionTemplate; +import fr.ird.observe.services.dto.longline.BasketDto; + +/** + * Created on 12/11/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.10 + */ +public class BasketsTableModel extends LonglineCompositionTableModelSupport<BasketDto> { + + private static final long serialVersionUID = 1L; + + public BasketsTableModel(LonglineDetailCompositionUIModel model) { + super(model); + } + + @Override + protected BasketDto createNewRow() { + return new BasketDto(); + } + + @Override + public int getColumnCount() { + return 4; + } + + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + + boolean result; + + switch (columnIndex) { + + case 0: + + // can never edit setting id + result = false; + break; + + case 1: + + // can edit hauling id if and only if set has hauling breaks + result = !isGenerateHaulingIds(); + break; + + case 2: + + // can always change length ? + result = true; + break; + + case 3: + + // can always change length ? + result = true; + break; + + default: + throw new IllegalStateException("Can't come here"); + + } + + return result; + + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + + BasketDto row = data.get(rowIndex); + Object result; + + switch (columnIndex) { + case 0: + + result = row.getSettingIdentifier(); + break; + + case 1: + + result = row.getHaulingIdentifier(); + break; + + case 2: + + result = row.getFloatline1Length(); + break; + + case 3: + + result = row.getFloatline2Length(); + break; + + default: + throw new IllegalStateException("Can't come here"); + } + + return result; + + } + + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + + BasketDto row = data.get(rowIndex); + + switch (columnIndex) { + case 0: + + row.setSettingIdentifier((Integer) aValue); + break; + + case 1: + + row.setHaulingIdentifier((Integer) aValue); + break; + + case 2: + + row.setFloatline1Length((Float) aValue); + break; + + case 3: + + row.setFloatline2Length((Float) aValue); + break; + + default: + throw new IllegalStateException("Can't come here"); + } + + setModified(true); + + } + + public void applySectionTemplate(SectionTemplate newTemplate) { + + newTemplate.applyToBaskets(data); + fireTableRowsUpdated(0, getRowCount() - 1); + setModified(true); + + } +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/BranchlineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/BranchlineUI.jaxx new file mode 100644 index 0000000..e332224 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/BranchlineUI.jaxx @@ -0,0 +1,254 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ContentUI superGenericType='BranchlineDto' contentTitle='{n("observe.content.branchline.title")}'> + + <import> + fr.ird.observe.services.dto.CommentableDto + fr.ird.observe.services.dto.longline.BranchlineDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.longline.LineTypeDto + fr.ird.observe.services.dto.referential.longline.BaitTypeDto + fr.ird.observe.services.dto.referential.longline.BaitHaulingStatusDto + fr.ird.observe.services.dto.referential.longline.BaitSettingStatusDto + fr.ird.observe.services.dto.referential.longline.HookSizeDto + fr.ird.observe.services.dto.referential.longline.HookTypeDto + + fr.ird.observe.application.swing.ui.actions.shared.ResetEditUIAction + fr.ird.observe.application.swing.ui.actions.shared.SaveEditUIAction + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + org.nuiton.jaxx.widgets.datetime.DateTimeEditor + + org.apache.commons.lang3.BooleanUtils + + java.awt.Dimension + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <style source="../../Common.jcss"/> + + <!-- handler --> + <BranchlineUIHandler id='handler'/> + + <!-- model --> + <BranchlineUIModel id='model'/> + + <!-- edit bean --> + <BranchlineDto id='bean'/> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' context='ui-update' + beanClass='fr.ird.observe.services.dto.longline.BranchlineDto' + errorTableModel='{getErrorTableModel()}'> + </BeanValidator> + + + <script><![CDATA[ +public void edit(BranchlineDto branchline) { getHandler().edit(branchline); } + +]]> + </script> + + <!-- formulaire --> + <JPanel id="body" layout='{new BorderLayout()}'> + + <Table insets="0" fill="both" constraints='BorderLayout.CENTER'> + <row> + <cell anchor="north" weightx="1"> + <JTabbedPane id='fishingOperationTabPane'> + + <tab id='generalTab'> + <JPanel layout='{new BorderLayout()}'> + <Table fill="both" constraints='BorderLayout.CENTER'> + + <!-- topType --> + <row> + <cell anchor='west'> + <JLabel id='topTypeLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <BeanComboBox id='topType' constructorParams='this' genericType='ReferentialReference<LineTypeDto>' _entityClass='LineTypeDto.class'/> + </cell> + </row> + + <!-- tracelineType --> + <row> + <cell anchor='west'> + <JLabel id='tracelineTypeLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <BeanComboBox id='tracelineType' constructorParams='this' genericType='ReferentialReference<LineTypeDto>' _entityClass='LineTypeDto.class'/> + </cell> + </row> + + <!-- depthRecorder --> + <!-- hookLost --> + <!-- traceCutOff --> + <row> + <cell columns="3"> + <JPanel layout="{new GridLayout()}"> + <JCheckBox id='depthRecorder'/> + <JCheckBox id='hookLost'/> + <JCheckBox id='traceCutOff'/> + </JPanel> + </cell> + </row> + + <!-- timer --> + <!-- timeSinceContact --> + <row> + <cell anchor='east'> + <JCheckBox id='timer'/> + </cell> + <cell> + <JLabel id='timeSinceContactLabel'/> + </cell> + <cell> + <NumberEditor id='timeSinceContact' constructorParams='this'/> + </cell> + </row> + + <!-- timerTimeOnBoard --> + <row> + <cell columns="3"> + <DateTimeEditor id='timerTimeOnBoard' constructorParams='this'/> + </cell> + </row> + + <!-- weighted snaps --> + <!-- snap weights --> + <row> + <cell anchor='east'> + <JCheckBox id='weightedSnap'/> + </cell> + <cell> + <JLabel id='snapWeightLabel'/> + </cell> + <cell> + <NumberEditor id='snapWeight' constructorParams='this'/> + </cell> + </row> + + <!-- weighted swivels --> + <!-- swivels weights --> + <row> + <cell anchor="east"> + <JCheckBox id='weightedSwivel'/> + </cell> + <cell anchor="west"> + <JLabel id='swivelWeightLabel'/> + </cell> + <cell> + <NumberEditor id='swivelWeight' constructorParams='this'/> + </cell> + </row> + + </Table> + </JPanel> + </tab> + + <tab id='hookAndBaitTab'> + <JPanel layout='{new BorderLayout()}'> + <Table fill="both" constraints='BorderLayout.CENTER'> + + <!-- HookType --> + <row> + <cell anchor='west'> + <JLabel id='hookTypeLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <BeanComboBox id='hookType' constructorParams='this' genericType='ReferentialReference<HookTypeDto>' _entityClass='HookTypeDto.class'/> + </cell> + </row> + + <!-- HookSize --> + <row> + <cell anchor='west'> + <JLabel id='hookSizeLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <BeanComboBox id='hookSize' constructorParams='this' genericType='ReferentialReference<HookSizeDto>' _entityClass='HookSizeDto.class'/> + </cell> + </row> + + <!-- hookOffset --> + <row> + <cell anchor='west'> + <JLabel id='hookOffsetLabel'/> + </cell> + <cell columns="2" weightx="1" fill="both"> + <NumberEditor id='hookOffset' constructorParams='this'/> + </cell> + </row> + + <!-- baitType --> + <row> + <cell anchor='west'> + <JLabel id='baitTypeLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <BeanComboBox id='baitType' constructorParams='this' genericType='ReferentialReference<BaitTypeDto>' _entityClass='BaitTypeDto.class'/> + </cell> + </row> + + <!-- baitSettingStatus --> + <row> + <cell anchor='west'> + <JLabel id='baitSettingStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <BeanComboBox id='baitSettingStatus' constructorParams='this' genericType='ReferentialReference<BaitSettingStatusDto>' _entityClass='BaitSettingStatusDto.class'/> + </cell> + </row> + + <!-- baitHaulingStatus --> + <row> + <cell anchor='west'> + <JLabel id='baitHaulingStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <BeanComboBox id='baitHaulingStatus' constructorParams='this' genericType='ReferentialReference<BaitHaulingStatusDto>' _entityClass='BaitHaulingStatusDto.class'/> + </cell> + </row> + + </Table> + </JPanel> + </tab> + </JTabbedPane> + </cell> + </row> + <row> + <cell weighty="1"> + <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2'/> + </JScrollPane> + </cell> + </row> + </Table> + + </JPanel> + +</fr.ird.observe.application.swing.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/BranchlineUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/BranchlineUI.jcss new file mode 100644 index 0000000..e3bf267 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/BranchlineUI.jcss @@ -0,0 +1,245 @@ + /* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#model { + editable:true; + modified:{validator.isChanged()}; + valid:{validator.isValid()}; + enabled:{!model.isReadingMode()}; +} + + +#comment { + columnHeaderView:{new JLabel(t("observe.content.branchline.comment"))}; +} + +#comment2 { + _tablePropertyName: {BranchlineDto.PROPERTY_COMMENT}; + text:{getStringValue(bean.getComment())}; +} + +/* ***************************************************************************** */ +/* GENERAL TAB **************************************************************** */ +/* ***************************************************************************** */ + +#generalTab { + title:{t("observe.content.branchline.tab.general")}; + icon:{getHandler().getErrorIconIfFalse(model.isGeneralTabValid())}; +} + +#depthRecorder { + horizontalTextPosition:{JCheckBox.LEFT}; + text:"observe.content.branchline.depthRecorder"; + _propertyName:{BranchlineDto.PROPERTY_DEPTH_RECORDER}; + selected:{BooleanUtils.isTrue(bean.getDepthRecorder())}; + _validatorLabel:{t("observe.content.branchline.depthRecorder")}; +} + +#hookLost { + horizontalTextPosition:{JCheckBox.LEFT}; + text:"observe.content.branchline.hookLost"; + _propertyName:{BranchlineDto.PROPERTY_HOOK_LOST}; + selected:{BooleanUtils.isTrue(bean.getHookLost())}; + _validatorLabel:{t("observe.content.branchline.hookLost")}; +} + +#traceCutOff { + horizontalTextPosition:{JCheckBox.LEFT}; + text:"observe.content.branchline.traceCutOff"; + _propertyName:{BranchlineDto.PROPERTY_TRACE_CUT_OFF}; + selected:{BooleanUtils.isTrue(bean.getTraceCutOff())}; + _validatorLabel:{t("observe.content.branchline.traceCutOff")}; +} + +#timer { + text:"observe.content.branchline.timer"; + horizontalTextPosition:{JCheckBox.LEFT}; + _propertyName:{BranchlineDto.PROPERTY_TIMER}; + selected:{BooleanUtils.isTrue(bean.getTimer())}; + _validatorLabel:{t("observe.content.branchline.timer")}; +} + +#timeSinceContactLabel { + text:"observe.content.branchline.timeSinceContact"; + labelFor:{timeSinceContact}; +} + +#timeSinceContact { + enabled:{BooleanUtils.isTrue(bean.getTimer())}; + property:{BranchlineDto.PROPERTY_TIME_SINCE_CONTACT}; + model:{bean.getTimeSinceContact()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.LONG_10_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.branchline.timeSinceContact")}; +} + +#timerTimeOnBoardLabel { + text:"observe.content.branchline.timerTimeOnBoard"; + labelFor:{timerTimeOnBoard}; +} + +#timerTimeOnBoard { + enabled:{BooleanUtils.isTrue(bean.getTimer())}; + label:{t("observe.content.branchline.timerTimeOnBoard")}; + date:{bean.getTimerTimeOnBoard()}; + propertyDate: {BranchlineDto.PROPERTY_TIMER_TIME_ON_BOARD}; + _validatorLabel:{t("observe.content.branchline.timerTimeOnBoard")}; +} + +#topTypeLabel { + text:"observe.content.branchline.topType"; + labelFor:{topType}; +} + +#topType { + property:{BranchlineDto.PROPERTY_TOP_TYPE}; + selectedItem:{bean.getTopType()}; + _validatorLabel:{t("observe.content.branchline.topType")}; +} + +#tracelineTypeLabel { + text:"observe.content.branchline.tracelineType"; + labelFor:{tracelineType}; +} + +#tracelineType { + property:{BranchlineDto.PROPERTY_TRACELINE_TYPE}; + selectedItem:{bean.getTracelineType()}; + _validatorLabel:{t("observe.content.branchline.tracelineType")}; +} + +#weightedSwivel { + horizontalTextPosition:{JCheckBox.LEFT}; + text:"observe.content.branchline.weightedSwivel"; + _propertyName:{BranchlineDto.PROPERTY_WEIGHTED_SWIVEL}; + selected:{BooleanUtils.isTrue(bean.getWeightedSwivel())}; + _validatorLabel:{t("observe.content.branchline.weightedSwivel")}; +} + +#swivelWeightLabel { + text:"observe.content.branchline.swivelWeight"; + labelFor:{swivelWeight}; +} + +#swivelWeight { + enabled:{BooleanUtils.isTrue(bean.getWeightedSwivel())}; + property:{BranchlineDto.PROPERTY_SWIVEL_WEIGHT}; + model:{bean.getSwivelWeight()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL3_PATTERN}; + _validatorLabel:{t("observe.content.branchline.swivelWeight")}; +} + +#weightedSnap { + horizontalTextPosition:{JCheckBox.LEFT}; + text:"observe.content.branchline.weightedSnap"; + _propertyName:{BranchlineDto.PROPERTY_WEIGHTED_SNAP}; + selected:{BooleanUtils.isTrue(bean.getWeightedSnap())}; + _validatorLabel:{t("observe.content.branchline.weightedSnap")}; +} + +#snapWeightLabel { + text:"observe.content.branchline.snapWeight"; + labelFor:{snapWeight}; +} + +#snapWeight { + enabled:{BooleanUtils.isTrue(bean.getWeightedSnap())}; + property:{BranchlineDto.PROPERTY_SNAP_WEIGHT}; + model:{bean.getSnapWeight()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL3_PATTERN}; + _validatorLabel:{t("observe.content.branchline.snapWeight")}; +} + +/* ***************************************************************************** */ +/* HOOK AND BAIT TAB ********************************************************** */ +/* ***************************************************************************** */ + +#hookAndBaitTab { + title:{t("observe.content.branchline.tab.hookAndBait")}; + icon:{getHandler().getErrorIconIfFalse(model.isHookAndBaitTabValid())}; +} + +#hookTypeLabel { + text:"observe.content.branchline.hookType"; + labelFor:{hookType}; +} + +#hookType { + property:{BranchlineDto.PROPERTY_HOOK_TYPE}; + selectedItem:{bean.getHookType()}; + _validatorLabel:{t("observe.content.branchline.hookType")}; +} + +#hookSizeLabel { + text:"observe.content.branchline.hookSize"; + labelFor:{hookSize}; +} + +#hookSize { + property:{BranchlineDto.PROPERTY_HOOK_SIZE}; + selectedItem:{bean.getHookSize()}; + _validatorLabel:{t("observe.content.branchline.hookSize")}; +} + +#hookOffsetLabel { + text:"observe.content.branchline.hookOffset"; + labelFor:{hookOffset}; +} + +#hookOffset { + property:{BranchlineDto.PROPERTY_HOOK_OFFSET}; + model:{bean.getHookOffset()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.branchline.hookOffset")}; +} + +#baitSettingStatusLabel { + text:"observe.content.branchline.baitSettingStatus"; + labelFor:{baitSettingStatus}; +} + +#baitSettingStatus { + property:{BranchlineDto.PROPERTY_BAIT_SETTING_STATUS}; + selectedItem:{bean.getBaitSettingStatus()}; + _validatorLabel:{t("observe.content.branchline.baitSettingStatus")}; +} + +#baitHaulingStatusLabel { + text:"observe.content.branchline.baitHaulingStatus"; + labelFor:{baitHaulingStatus}; +} + +#baitHaulingStatus { + property:{BranchlineDto.PROPERTY_BAIT_HAULING_STATUS}; + selectedItem:{bean.getBaitHaulingStatus()}; + _validatorLabel:{t("observe.content.branchline.baitHaulingStatus")}; +} + +#baitTypeLabel { + text:"observe.content.branchline.baitType"; + labelFor:{baitType}; +} + +#baitType { + property:{BranchlineDto.PROPERTY_BAIT_TYPE}; + selectedItem:{bean.getBaitType()}; + _validatorLabel:{t("observe.content.branchline.baitType")}; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/BranchlineUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/BranchlineUIHandler.java new file mode 100644 index 0000000..22de4ca --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/BranchlineUIHandler.java @@ -0,0 +1,354 @@ +package fr.ird.observe.application.swing.ui.content.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.longline.BranchlineDto; +import fr.ird.observe.services.dto.longline.BranchlineDtos; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.ContentUIHandler; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; +import jaxx.runtime.validator.swing.SwingValidatorMessage; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.decorator.Decorator; +import org.nuiton.i18n.I18n; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.JOptionPane; +import javax.swing.event.TableModelListener; +import java.util.HashSet; +import java.util.Set; + +/** + * Created on 12/22/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.10 + */ +public class BranchlineUIHandler extends ContentUIHandler<BranchlineDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(BranchlineUIHandler.class); + + // Compute valid state of tab from the error table + protected final TableModelListener computeTabValidStateListener; + + private Decorator<BranchlineDto> branchlineDecorator; + + public BranchlineUIHandler(BranchlineUI ui) { + super(ui, DataContextType.SetLongline, null); + computeTabValidStateListener = e -> { + + SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); + computeTabValidState(source); + + }; + } + + public void edit(BranchlineDto branchline) { + + if (log.isInfoEnabled()) { + log.info("Will edit branchline: " + branchlineDecorator.toString(branchline)); + } + + getModel().setBranchline(branchline); + BranchlineDtos.copyBranchlineDto(branchline, getBean()); + + if (branchline == null) { + + // stop edit + stopEditUI(); + + } else { + + if (getModel().isEnabled() && !getModel().isEditing()) { + + startEditUI(); + + } + } + + // To be sure always remove listener (could prevent some leaks) + getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); + // listen messages to see if required to add + getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); + + SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); + computeTabValidState(errorTableModel); + + getModel().setModified(false); + + } + + @Override + public BranchlineUIModel getModel() { + return (BranchlineUIModel) super.getModel(); + } + + @Override + public BranchlineUI getUi() { + return (BranchlineUI) super.getUi(); + } + + @Override + protected boolean computeCanWrite(ObserveSwingDataSource source) { + return source.canWriteData(); + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + ContentMode contentMode; + + if (getOpenDataManager().isOpenActivityLongline(dataContext.getSelectedActivityLonglineId())) { + + // l'activité est ouverte, mode édition + contentMode = ContentMode.UPDATE; + + } else { + + contentMode = ContentMode.READ; + + } + + return contentMode; + + } + + @Override + public void initUI() { + + branchlineDecorator = getDecoratorService().getDecoratorByType(BranchlineDto.class); + super.initUI(); + + } + + @Override + public void openUI() { + + if (log.isInfoEnabled()) { + log.info("OpenUI: " + getModel()); + } + + boolean canWrite = computeCanWrite(getDataSource()); + + getModel().setCanWrite(canWrite); + + updateActions(); + + ContentMode mode = computeContentMode(); + + // utilisation du mode requis + setContentMode(mode); + + // when opening screen do not edit incoming bean + edit(null); + + if (mode != ContentMode.READ) { + ui.startEdit(null); + } + + } + + @Override + public void startEditUI(String... binding) { + + ContentUIModel<BranchlineDto> model = getModel(); + + super.startEditUI(BranchlineUI.BINDING_COMMENT2_TEXT, + + BranchlineUI.BINDING_TOP_TYPE_SELECTED_ITEM, + BranchlineUI.BINDING_TRACELINE_TYPE_SELECTED_ITEM, + + BranchlineUI.BINDING_DEPTH_RECORDER_SELECTED, + BranchlineUI.BINDING_HOOK_LOST_SELECTED, + BranchlineUI.BINDING_TRACE_CUT_OFF_SELECTED, + + BranchlineUI.BINDING_WEIGHTED_SWIVEL_SELECTED, + BranchlineUI.BINDING_SWIVEL_WEIGHT_MODEL, + BranchlineUI.BINDING_WEIGHTED_SNAP_SELECTED, + BranchlineUI.BINDING_SNAP_WEIGHT_MODEL, + + BranchlineUI.BINDING_BAIT_TYPE_SELECTED_ITEM, + BranchlineUI.BINDING_BAIT_SETTING_STATUS_SELECTED_ITEM, + BranchlineUI.BINDING_BAIT_HAULING_STATUS_SELECTED_ITEM, + + BranchlineUI.BINDING_HOOK_TYPE_SELECTED_ITEM, + BranchlineUI.BINDING_HOOK_SIZE_SELECTED_ITEM, + BranchlineUI.BINDING_HOOK_OFFSET_MODEL, + + BranchlineUI.BINDING_TIMER_SELECTED, + BranchlineUI.BINDING_TIME_SINCE_CONTACT_MODEL, + BranchlineUI.BINDING_TIMER_TIME_ON_BOARD_DATE + ); + + model.setModified(false); + + } + + @Override + protected boolean doSave(BranchlineDto bean) throws Exception { + + // bind back to model branchline + BranchlineDto beanToSave = getModel().getBranchline(); + BranchlineDtos.copyBranchlineDto(bean, beanToSave); + + // for external models + getModel().fireSaved(); + + return true; + + } + + @Override + public void resetEditUI() { + + BranchlineDto branchline = getModel().getBranchline(); + + // on arrete l'edition + stopEditUI(); + + // on re-ouvre l'écran d'édition + try { + openUI(); + } catch (Exception ex) { + UIHelper.handlingError(ex); + stopEditUI(); + } + + edit(branchline); + + } + + public boolean tryToQuit() { + + boolean canContinue; + + if (getModel().isEditing() && getModel().isModified()) { + + canContinue = false; + + if (getModel().isValid()) { + + // le formulaire est valide, on demande a l'utilisateur s'il + // veut la sauvegarder + + int reponse = UIHelper.askUser( + I18n.t("observe.title.need.confirm"), + I18n.t("observe.content.branchline.message.modified"), + JOptionPane.WARNING_MESSAGE, + new Object[]{ + I18n.t("observe.choice.save"), + I18n.t("observe.choice.doNotSave"), + I18n.t("observe.choice.cancel")}, + 0); + if (log.isDebugEnabled()) { + log.debug("response : " + reponse); + } + + switch (reponse) { + case JOptionPane.CLOSED_OPTION: + case 2: + + break; + case 0: + // will save ui + // sauvegarde des modifications + saveUI(false); + canContinue = true; + break; + case 1: + + // reset edit + resetEditUI(); + canContinue = true; + + break; + } + + } else { + + // le formulaire n'est pas valide, on ne peut que proposer la perte + // des donnees car elles sont ne pas enregistrables + + int reponse = UIHelper.askUser( + I18n.t("observe.title.need.confirm"), + I18n.t("observe.content.branchline.message.modified.but.invalid"), + JOptionPane.ERROR_MESSAGE, + new Object[]{ + I18n.t("observe.choice.continue"), + I18n.t("observe.choice.cancel")}, + 0); + if (log.isDebugEnabled()) { + log.debug("response : " + reponse); + } + switch (reponse) { + case 0: + + // reset edit + resetEditUI(); + canContinue = true; + + break; + } + + } + + } else { + + // pas en mode edition ou formulaire non modifié + // on peut toujours quitter + canContinue = true; + + } + + return canContinue; + + } + + protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { + + Set<String> errorProperties = new HashSet<>(); + int rowCount = errorTableModel.getRowCount(); + for (int i = 0; i < rowCount; i++) { + + SwingValidatorMessage row = errorTableModel.getRow(i); + if (NuitonValidatorScope.ERROR.equals(row.getScope())) { + errorProperties.add(row.getField()); + } + } + + boolean generalTabValid = !errorProperties.removeAll(BranchlineUIModel.GENERAL_TAB_PROPERTIES); + boolean hookAndBaitTabValid = !errorProperties.removeAll(BranchlineUIModel.HOOK_AND_BAIT_TAB_PROPERTIES); + + BranchlineUIModel model = getModel(); + model.setGeneralTabValid(generalTabValid); + model.setHookAndBaitTabValid(hookAndBaitTabValid); + + } +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/BranchlineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/BranchlineUIModel.java new file mode 100644 index 0000000..be455a2 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/BranchlineUIModel.java @@ -0,0 +1,110 @@ +package fr.ird.observe.application.swing.ui.content.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.ImmutableSet; +import fr.ird.observe.services.dto.longline.BranchlineDto; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; + +import java.util.Set; + +/** + * Created on 12/22/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.10 + */ +public class BranchlineUIModel extends ContentUIModel<BranchlineDto> { + + public static final String PROPERTY_SAVED = "saved"; + + private static final long serialVersionUID = 1L; + + public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; + + public static final String PROPERTY_HOOK_AND_BAIT_TAB_VALID = "hookAndBaitTabValid"; + + public static final Set<String> GENERAL_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(BranchlineDto.PROPERTY_TOP_TYPE, + BranchlineDto.PROPERTY_TRACELINE_TYPE, + BranchlineDto.PROPERTY_DEPTH_RECORDER, + BranchlineDto.PROPERTY_HOOK_LOST, + BranchlineDto.PROPERTY_TRACE_CUT_OFF, + BranchlineDto.PROPERTY_TIMER, + BranchlineDto.PROPERTY_TIME_SINCE_CONTACT, + BranchlineDto.PROPERTY_TIMER_TIME_ON_BOARD, + BranchlineDto.PROPERTY_WEIGHTED_SNAP, + BranchlineDto.PROPERTY_SNAP_WEIGHT, + BranchlineDto.PROPERTY_WEIGHTED_SWIVEL, + BranchlineDto.PROPERTY_SWIVEL_WEIGHT).build(); + + public static final Set<String> HOOK_AND_BAIT_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(BranchlineDto.PROPERTY_HOOK_TYPE, + BranchlineDto.PROPERTY_HOOK_SIZE, + BranchlineDto.PROPERTY_HOOK_OFFSET, + BranchlineDto.PROPERTY_BAIT_TYPE, + BranchlineDto.PROPERTY_BAIT_SETTING_STATUS, + BranchlineDto.PROPERTY_BAIT_HAULING_STATUS).build(); + + private BranchlineDto branchlineDto; + + private boolean generalTabValid; + + private boolean hookAndBaitTabValid; + + public BranchlineUIModel() { + super(BranchlineDto.class); + } + + public BranchlineDto getBranchline() { + return branchlineDto; + } + + public void setBranchline(BranchlineDto branchlineDto) { + this.branchlineDto = branchlineDto; + } + + public boolean isGeneralTabValid() { + return generalTabValid; + } + + public void setGeneralTabValid(boolean generalTabValid) { + this.generalTabValid = generalTabValid; + firePropertyChange(PROPERTY_GENERAL_TAB_VALID, null, generalTabValid); + } + + public boolean isHookAndBaitTabValid() { + return hookAndBaitTabValid; + } + + public void setHookAndBaitTabValid(boolean hookAndBaitTabValid) { + this.hookAndBaitTabValid = hookAndBaitTabValid; + firePropertyChange(PROPERTY_HOOK_AND_BAIT_TAB_VALID, null, hookAndBaitTabValid); + } + + // For external model known when a saved action was done + public void fireSaved() { + firePropertyChange(PROPERTY_SAVED, null, true); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/BranchlinesTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/BranchlinesTableModel.java new file mode 100644 index 0000000..812d31e --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/BranchlinesTableModel.java @@ -0,0 +1,180 @@ +package fr.ird.observe.application.swing.ui.content.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.longline.BranchlineDto; + +import java.util.Date; + +/** + * Created on 12/11/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.10 + */ +public class BranchlinesTableModel extends LonglineCompositionTableModelSupport<BranchlineDto> { + + private static final long serialVersionUID = 1L; + + protected Date defaultDate; + + private boolean useTimer; + + public BranchlinesTableModel(LonglineDetailCompositionUIModel model) { + super(model); + } + + public void setDefaultDate(Date defaultDate) { + this.defaultDate = defaultDate; + } + + @Override + protected BranchlineDto createNewRow() { + + BranchlineDto branchline = new BranchlineDto(); + branchline.setTimerTimeOnBoard(defaultDate); + branchline.setTimer(useTimer); + return branchline; + + } + + @Override + public int getColumnCount() { + return 4; + } + + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + + boolean result; + + switch (columnIndex) { + + case 0: + + // can never edit setting id + result = false; + break; + + case 1: + + // can edit hauling id if and only if set has hauling breaks + result = !isGenerateHaulingIds(); + break; + + case 2: + + result = true; + break; + + case 3: + + result = true; + break; + + default: + throw new IllegalStateException("Can't come here"); + + } + + return result; + + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + + BranchlineDto row = data.get(rowIndex); + Object result; + + switch (columnIndex) { + case 0: + + result = row.getSettingIdentifier(); + break; + + case 1: + + result = row.getHaulingIdentifier(); + break; + + case 2: + + result = row.getBranchlineLength(); + break; + + case 3: + + result = row.getTracelineLength(); + break; + + default: + throw new IllegalStateException("Can't come here"); + } + + return result; + + } + + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + + BranchlineDto row = data.get(rowIndex); + + switch (columnIndex) { + case 0: + + row.setSettingIdentifier((Integer) aValue); + break; + + case 1: + + row.setHaulingIdentifier((Integer) aValue); + break; + + case 2: + + row.setBranchlineLength((Float) aValue); + break; + + case 3: + + row.setTracelineLength((Float) aValue); + break; + + default: + throw new IllegalStateException("Can't come here"); + } + + setModified(true); + + } + + public void setUseTimer(boolean useTimer) { + this.useTimer = useTimer; + } + + public boolean isUseTimer() { + return useTimer; + } +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineCompositionTableModelSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineCompositionTableModelSupport.java new file mode 100644 index 0000000..8c72785 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineCompositionTableModelSupport.java @@ -0,0 +1,215 @@ +package fr.ird.observe.application.swing.ui.content.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.AbstractObserveDto; +import fr.ird.observe.services.dto.longline.LonglineCompositionDto; +import fr.ird.observe.application.swing.ui.util.table.EditableTableModelSupport; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.List; + +/** + * Created on 12/13/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.10 + */ +public abstract class LonglineCompositionTableModelSupport<E extends AbstractObserveDto & LonglineCompositionDto> extends EditableTableModelSupport<E> { + + /** Logger. */ + private static final Log log = LogFactory.getLog(LonglineCompositionTableModelSupport.class); + + private static final long serialVersionUID = 1L; + + private final LonglineDetailCompositionUIModel model; + + public LonglineCompositionTableModelSupport(LonglineDetailCompositionUIModel model) { + super(false); + this.model = model; + } + + @Override + protected final boolean isRowValid(E valid) { + // Not used here + return true; + } + + @Override + public final boolean isRowNotEmpty(E valid) { + // Not used here + return true; + } + + public void rearrangeIds(boolean fire) { + + rearrangeIds(data); + + if (fire && !isEmpty()) { + + fireTableRowsUpdated(0, getRowCount() - 1); + + } + + } + + public void rearrangeIds(List<E> data) { + + boolean generateHaulingIds = isGenerateHaulingIds(); + boolean haulingdirectionSameAsSettings = model.isHaulingdirectionSameAsSettings(); + + int dataSize = data.size(); + + if (log.isInfoEnabled()) { + log.info("Will rearrange ids for " + dataSize + " data on " + this); + log.info("generateHaulingIds ? " + generateHaulingIds); + log.info("haulingdirectionSameAsSettings ? " + haulingdirectionSameAsSettings); + } + + int index = 1; + + for (E e : data) { + + if (log.isInfoEnabled()) { + log.info("SettingIdentifier : " + index); + } + e.setSettingIdentifier(index); + + if (generateHaulingIds) { + + int haulingId; + + if (haulingdirectionSameAsSettings) { + haulingId = index; + } else { + haulingId = dataSize - index + 1; + } + + if (log.isInfoEnabled()) { + log.info("HaulingIdentifier : " + haulingId); + } + e.setHaulingIdentifier(haulingId); + + } + + index++; + + } + + } + + @Override + public void addNewRow() { + + super.addNewRow(); + + validate(); + setModified(true); + + } + + @Override + public void insertAfterSelectedRow() { + + super.insertAfterSelectedRow(); + + validate(); + setModified(true); + + } + + @Override + public void insertBeforeSelectedRow() { + + super.insertBeforeSelectedRow(); + + validate(); + setModified(true); + + } + + @Override + public void removeData(int selectedRow) { + + super.removeData(selectedRow); + + validate(); + setModified(true); + + } + + protected boolean isGenerateHaulingIds() { + return model.isGenerateHaulingIds(); + } + + protected boolean isCanGenerate() { + return model.isCanGenerate(); + } + + @Override + public void fireTableDataChanged() { + + // rearrange ids when data has changed + rearrangeIds(false); + + super.fireTableDataChanged(); + + } + + @Override + public void fireTableRowsDeleted(int firstRow, int lastRow) { + super.fireTableRowsDeleted(firstRow, lastRow); + + // must rearrange ids + rearrangeIds(true); + + } + + @Override + public void fireTableRowsInserted(int firstRow, int lastRow) { + super.fireTableRowsInserted(firstRow, lastRow); + + // must rearrange ids + rearrangeIds(true); + + } + + @Override + public void removeSelectedRow() { + + super.removeSelectedRow(); + validate(); + setModified(true); + + } + + + @Override + public void setData(List<E> data) { + + super.setData(data); + validate(); + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionUI.jaxx new file mode 100644 index 0000000..c3fbe7b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionUI.jaxx @@ -0,0 +1,205 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ContentUI superGenericType='SetLonglineDetailCompositionDto' + contentTitle='{n("observe.content.longlineDetailComposition.title")}'> + + <import> + fr.ird.observe.application.swing.ObserveSwingApplicationContext + fr.ird.observe.services.dto.longline.SetLonglineDetailCompositionDto + fr.ird.observe.application.swing.ui.actions.shared.ResetEditUIAction + fr.ird.observe.application.swing.ui.actions.shared.SaveEditUIAction + + fr.ird.observe.application.swing.ui.util.JVetoableTabbedPane + + org.jdesktop.swingx.JXTable + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <style source="../../Common.jcss"/> + + <!-- handler --> + <LonglineDetailCompositionUIHandler id='handler'/> + + <!-- model --> + <LonglineDetailCompositionUIModel id='model'/> + + <!-- section templates table model --> + <SectionTemplatesTableModel id='sectionTemplatesTableModel' initializer="getModel().getSectionTemplatesTableModel()"/> + + <!-- sections table model --> + <SectionsTableModel id='sectionsTableModel' initializer="getModel().getSectionsTableModel()"/> + + <!-- baskets table model --> + <BasketsTableModel id='basketsTableModel' initializer="getModel().getBasketsTableModel()"/> + + <!-- branchlines table model --> + <BranchlinesTableModel id='branchlinesTableModel' initializer="getModel().getBranchlinesTableModel()"/> + + <!-- edit bean --> + <SetLonglineDetailCompositionDto id='bean'/> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' beanClass='fr.ird.observe.services.dto.longline.SetLonglineDetailCompositionDto' + errorTableModel='{getErrorTableModel()}' context='ui-update-longlineDetailComposition'> + </BeanValidator> + + <BeanValidator id='sectionValidator' beanClass='fr.ird.observe.services.dto.longline.SectionDto' + errorTableModel='{getErrorTableModel()}' context='ui-update-table'> + <field name='basket' component='sectionsPane'/> + </BeanValidator> + + <BeanValidator id='basketValidator' beanClass='fr.ird.observe.services.dto.longline.BasketDto' + errorTableModel='{getErrorTableModel()}' context='ui-update-table'> + <field name='branchline' component='basketsPane'/> + <field name='floatline1Length' component='basketsPane'/> + <field name='floatline2Length' component='basketsPane'/> + </BeanValidator> + + <BeanValidator id='branchlineValidator' beanClass='fr.ird.observe.services.dto.longline.BranchlineDto' + errorTableModel='{getErrorTableModel()}' context='ui-update-table'> + <field name='settingIdentifier' component='branchlinesPane'/> + <field name='tracelineLength' component='branchlinesPane'/> + <field name='branchlineLength' component='branchlinesPane'/> + </BeanValidator> + + <JPopupMenu id='sectionTemplatesPopup'> + <JMenuItem id='deleteSelectedSectionTemplate' onActionPerformed='getHandler().deleteSelectedSectionTemplate()'/> + </JPopupMenu> + + <JPopupMenu id='sectionsPopup'> + <JMenuItem id='deleteSelectedSection' onActionPerformed='getHandler().deleteSelectedSection()'/> + <JMenuItem id='insertBeforeSelectedSection' onActionPerformed='getHandler().insertBeforeSelectedSection()'/> + <JMenuItem id='insertAfterSelectedSection' onActionPerformed='getHandler().insertAfterSelectedSection()'/> + </JPopupMenu> + + <JPopupMenu id='basketsPopup'> + <JMenuItem id='deleteSelectedBasket' onActionPerformed='getHandler().deleteSelectedBasket()'/> + <JMenuItem id='insertBeforeSelectedBasket' onActionPerformed='getHandler().insertBeforeSelectedBasket()'/> + <JMenuItem id='insertAfterSelectedBasket' onActionPerformed='getHandler().insertAfterSelectedBasket()'/> + </JPopupMenu> + + <JPopupMenu id='branchlinesPopup'> + <JMenuItem id='deleteSelectedBranchline' onActionPerformed='getHandler().deleteSelectedBranchline()'/> + <JMenuItem id='insertBeforeSelectedBranchline' onActionPerformed='getHandler().insertBeforeSelectedBranchline()'/> + <JMenuItem id='insertAfterSelectedBranchline' onActionPerformed='getHandler().insertAfterSelectedBranchline()'/> + </JPopupMenu> + + <!-- formulaire --> + <JPanel id="body" layout='{new BorderLayout()}'> + + <JVetoableTabbedPane id='fishingOperationTabPane' constraints='BorderLayout.CENTER'> + + <!-- generation tab --> + <tab id='generateTab'> + + <Table id='generateTabForm' fill='both' insets='1'> + + <!-- canGenerate --> + <row> + <cell anchor='west' fill="both"> + <JCheckBox id='canGenerate' + onItemStateChanged="getModel().setCanGenerate(((JCheckBox) event.getSource()).isSelected())"/> + </cell> + </row> + + <!-- sectionTemplates --> + <row> + <cell columns="2" fill="both" weightx="1" weighty="1"> + <JScrollPane id='sectionTemplatesPane'> + <JXTable id='sectionTemplatesTable'/> + </JScrollPane> + </cell> + </row> + + </Table> + + </tab> + + <!-- composition tab --> + <tab id='compositionTab'> + + <JPanel layout='{new BorderLayout()}'> + + <JPanel id="compositionActionPanel" constraints='BorderLayout.NORTH' layout='{new GridLayout()}'> + <JButton id='generateAll' onActionPerformed='getHandler().generateAllSections()'/> + <JButton id='deleteAll' onActionPerformed='getHandler().deleteAllSections()'/> + </JPanel> + + <JPanel id="compositionTablesPanel" constraints='BorderLayout.CENTER' layout='{new GridLayout(0,1)}'> + + <JScrollPane id='sectionsPane'> + <JXTable id='sectionsTable'/> + </JScrollPane> + + <JScrollPane id='basketsPane'> + <JXTable id='basketsTable'/> + </JScrollPane> + + <JScrollPane id='branchlinesPane'> + <JXTable id='branchlinesTable'/> + </JScrollPane> + + </JPanel> + + </JPanel> + + </tab> + + <!-- branchlineDetail tab --> + <tab id='branchlineDetailTab'> + + <JPanel id="branchlineDetailPanel" layout='{new BorderLayout()}'> + <Table fill="both" constraints='BorderLayout.NORTH'> + <row> + <cell weightx="1" fill="both" weighty="1"> + <BranchlineUI id="branchlineDetailUI" constructorParams="ObserveSwingApplicationContext.get().getMainUI()"/> + </cell> + </row> + </Table> + + </JPanel> + + </tab> + + </JVetoableTabbedPane> + + </JPanel> + + <!-- actions --> + <Table id="actions" fill='both' weightx='1' insets='0'> + <row> + <cell weightx="0.5"> + <JButton id='reset'/> + </cell> + <cell weightx="0.5"> + <JButton id='save'/> + </cell> + </row> + </Table> + + <!-- branchline detail model --> + <BranchlineUIModel id="branchlineDetailUIModel" initializer="branchlineDetailUI.getModel()"/> + +</fr.ird.observe.application.swing.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionUIHandler.java new file mode 100644 index 0000000..78589b7 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionUIHandler.java @@ -0,0 +1,1369 @@ +package fr.ird.observe.application.swing.ui.content.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.longline.ActivityLonglineDto; +import fr.ird.observe.services.dto.longline.BasketDto; +import fr.ird.observe.services.dto.longline.BranchlineDto; +import fr.ird.observe.services.dto.longline.SectionDto; +import fr.ird.observe.services.dto.longline.SectionTemplate; +import fr.ird.observe.services.dto.longline.SectionWithTemplate; +import fr.ird.observe.services.dto.longline.SectionWithTemplates; +import fr.ird.observe.services.dto.longline.SetLonglineDetailCompositionDto; +import fr.ird.observe.services.dto.longline.SetLonglineDetailCompositionDtos; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.service.longline.SetLonglineDetailCompositionService; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.ContentUIHandler; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; +import fr.ird.observe.application.swing.ui.util.JVetoableTabbedPane; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.decorator.Decorator; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.JComboBox; +import javax.swing.JOptionPane; +import javax.swing.event.ChangeListener; +import javax.swing.event.TableModelListener; +import java.beans.PropertyChangeListener; +import java.util.ArrayList; +import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.stream.Collectors; + +import static com.google.common.collect.Lists.newArrayList; +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 12/5/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.8 + */ +public class LonglineDetailCompositionUIHandler extends ContentUIHandler<SetLonglineDetailCompositionDto> { + + static final String SECTION_TEMPLATES_EDITOR = "sectionTemplatesEditor"; + + /** Logger */ + private static final Log log = LogFactory.getLog(LonglineDetailCompositionUIHandler.class); + + private final PropertyChangeListener sectionTemplatesTableModelModified; + + private final PropertyChangeListener sectionsTableModelModified; + + private final TableModelListener sectionsTableModelChanged; + + private final PropertyChangeListener branchlineDetailChanged; + + private final PropertyChangeListener selectedSectionTemplateChanged; + + private final PropertyChangeListener basketsTableModelModified; + + private final TableModelListener basketsTableModelChanged; + + private final PropertyChangeListener branchinesTableModelModified; + + private final TableModelListener branchinesTableModelChanged; + + private final PropertyChangeListener selectedBranchlineChanged; + + private final ChangeListener tabbedPaneChanged; + + private Decorator<SectionDto> sectionDecorator; + + private Decorator<BasketDto> basketDecorator; + + private Decorator<BranchlineDto> branchlineDecorator; + + /** + * To avoid section flush when selected section changes (used when deleting a section). + */ + private boolean skipSavePreviousSelectedSection; + + /** + * To avoid basket flush when selection basket changes (used when deleting a bakset). + */ + private boolean skipSavePreviousSelectedBasket; + + /** + * To avoid branchline flush when selection branchline changes (used when deleting a branchline). + */ + private boolean skipSavePreviousSelectedBranchline; + + /** + * To avoid basket flush when section is adjusting (used when changing selected section). + */ + private boolean sectionAdjusting; + + private final PropertyChangeListener modelCanGenerateChanged; + + private final PropertyChangeListener selectedSectionChanged; + + /** + * To avoid branchline flush when basket is adjusting (used when changing selected basket). + */ + private boolean basketAdjusting; + + private final PropertyChangeListener selectedBasketChanged; + + private LonglineDetailCompositionUIValidationHelper validationHelper; + + /** + * To avoid some checks while opening ui. + */ + private boolean onOpen; + + private final JVetoableTabbedPane.ChangeSelectedIndex tabbedPaneWillChanged; + + public LonglineDetailCompositionUIHandler(LonglineDetailCompositionUI ui) { + super(ui, DataContextType.ActivityLongline, DataContextType.SetLongline); + sectionTemplatesTableModelModified = evt -> { + Boolean newValue = (Boolean) evt.getNewValue(); + onSectionTemplatesTableModelModified(newValue); + }; + sectionsTableModelModified = evt -> { + Boolean newValue = (Boolean) evt.getNewValue(); + onSectionsTableModelModified(newValue); + }; + sectionsTableModelChanged = e -> { + SectionsTableModel source = (SectionsTableModel) e.getSource(); + onSectionsTableModelChanged(source.getData()); + }; + branchlineDetailChanged = evt -> getUi().getValidator().setChanged(true); + selectedSectionTemplateChanged = evt -> { + SectionTemplate newValue = (SectionTemplate) evt.getNewValue(); + onSelectedSectionTemplateChanged(newValue); + }; + basketsTableModelModified = evt -> { + Boolean newValue = (Boolean) evt.getNewValue(); + onBasketsTableModelModified(newValue); + }; + basketsTableModelChanged = e -> { + BasketsTableModel source = (BasketsTableModel) e.getSource(); + onBasketsTableModelChanged(source.getData()); + }; + branchinesTableModelModified = evt -> onBranchlinesTableModelModified((Boolean) evt.getNewValue()); + branchinesTableModelChanged = e -> { + BranchlinesTableModel source = (BranchlinesTableModel) e.getSource(); + onBranchlinesTableModelChanged(source.getData()); + }; + selectedBranchlineChanged = evt -> { + BranchlineDto previousValue = (BranchlineDto) evt.getOldValue(); + BranchlineDto newValue = (BranchlineDto) evt.getNewValue(); + onSelectedBranchlineChanged(previousValue, newValue); + }; + tabbedPaneChanged = e -> { + JVetoableTabbedPane source = (JVetoableTabbedPane) e.getSource(); + int previousIndex = source.getPreviousIndex(); + int selectedIndex = source.getSelectedIndex(); + onTabChanged(previousIndex, selectedIndex); + }; + modelCanGenerateChanged = evt -> { + + sectionAdjusting = true; + + try { + Boolean newValue = (Boolean) evt.getNewValue(); + onModelCanGenerateChanged(newValue); + } finally { + + sectionAdjusting = false; + } + }; + selectedSectionChanged = evt -> { + + sectionAdjusting = true; + + try { + SectionDto previousValue = (SectionDto) evt.getOldValue(); + SectionDto newValue = (SectionDto) evt.getNewValue(); + onSelectedSectionChanged(previousValue, newValue); + } finally { + + sectionAdjusting = false; + } + }; + selectedBasketChanged = evt -> { + + basketAdjusting = true; + + try { + BasketDto previousValue = (BasketDto) evt.getOldValue(); + BasketDto newValue = (BasketDto) evt.getNewValue(); + onSelectedBasketChanged(previousValue, newValue); + } finally { + + basketAdjusting = false; + } + }; + tabbedPaneWillChanged = this::onTabWillChanged; + } + + @Override + public LonglineDetailCompositionUI getUi() { + return (LonglineDetailCompositionUI) super.getUi(); + } + + @Override + public LonglineDetailCompositionUIModel getModel() { + return (LonglineDetailCompositionUIModel) super.getModel(); + } + + @Override + protected boolean computeCanWrite(ObserveSwingDataSource source) { + return source.canWriteData(); + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + ContentMode contentMode; + + if (getOpenDataManager().isOpenActivityLongline(dataContext.getSelectedActivityLonglineId())) { + + // l'activité est ouverte, mode édition + contentMode = ContentMode.UPDATE; + } else { + + // l'activité n'est pas ouverte, mode lecture + addMessage(getUi(), + NuitonValidatorScope.INFO, + getEntityLabel(ActivityLonglineDto.class), + t("observe.storage.activityLongline.message.not.open")); + + contentMode = ContentMode.READ; + } + + return contentMode; + + } + + @Override + public void initUI() { + + this.sectionDecorator = getDecoratorService().getDecoratorByType(SectionDto.class); + this.basketDecorator = getDecoratorService().getDecoratorByType(BasketDto.class); + this.branchlineDecorator = getDecoratorService().getDecoratorByType(BranchlineDto.class); + + LonglineDetailCompositionUIInitializer uiInitializer = new LonglineDetailCompositionUIInitializer(getUi()); + uiInitializer.initUI(); + + LonglineDetailCompositionUI ui1 = getUi(); + + this.validationHelper = new LonglineDetailCompositionUIValidationHelper(ui1, getDecoratorService()); + + getBranchlineDetailUIModel().addPropertyChangeListener(BranchlineUIModel.PROPERTY_SAVED, branchlineDetailChanged); + + { + // init section templates table + + SectionTemplatesTableModel tableModel = getSectionTemplatesTableModel(); + tableModel.addPropertyChangeListener(SectionTemplatesTableModel.MODIFIED_PROPERTY, sectionTemplatesTableModelModified); + + getModel().addPropertyChangeListener(LonglineDetailCompositionUIModel.PROPERTY_CAN_GENERATE, modelCanGenerateChanged); + } + + { + // init sections table + + SectionsTableModel tableModel = getSectionsTableModel(); + tableModel.addPropertyChangeListener(SectionsTableModel.MODIFIED_PROPERTY, sectionsTableModelModified); + tableModel.addPropertyChangeListener(SectionsTableModel.SELECTED_ROW_PROPERTY, selectedSectionChanged); + tableModel.addPropertyChangeListener(SectionsTableModel.TEMPLATE_PROPERTY, selectedSectionTemplateChanged); + tableModel.addTableModelListener(sectionsTableModelChanged); + + } + { + // init baskets table + + BasketsTableModel tableModel = getBasketsTableModel(); + tableModel.addPropertyChangeListener(BasketsTableModel.MODIFIED_PROPERTY, basketsTableModelModified); + tableModel.addPropertyChangeListener(BasketsTableModel.SELECTED_ROW_PROPERTY, selectedBasketChanged); + tableModel.addTableModelListener(basketsTableModelChanged); + + } + + { + // init branchlines table + + BranchlinesTableModel tableModel = getBranchlinesTableModel(); + tableModel.addPropertyChangeListener(BranchlinesTableModel.MODIFIED_PROPERTY, branchinesTableModelModified); + tableModel.addPropertyChangeListener(BranchlinesTableModel.SELECTED_ROW_PROPERTY, selectedBranchlineChanged); + tableModel.addTableModelListener(branchinesTableModelChanged); + + } + + JVetoableTabbedPane tabPane = ui1.getFishingOperationTabPane(); + + tabPane.setChangeSelectedIndex(tabbedPaneWillChanged); + tabPane.addChangeListener(tabbedPaneChanged); + + } + + @Override + public void openUI() { + + UIHelper.stopEditing(getUi().getSectionTemplatesTable()); + UIHelper.stopEditing(getUi().getSectionsTable()); + + super.openUI(); + + { + // open brancheline detail + BranchlineUI branchlineDetailUI = getUi().getBranchlineDetailUI(); + branchlineDetailUI.open(); + } + + String setId = getSelectedId(); + + if (log.isInfoEnabled()) { + log.info("setId = " + setId); + } + ContentMode mode = computeContentMode(); + // utilisation du mode requis + setContentMode(mode); + + SetLonglineDetailCompositionService setLonglineService = getSetLonglineDetailCompositionService(); + + Form<SetLonglineDetailCompositionDto> setLonglineDtoForm = setLonglineService.loadForm(setId); + + loadReferentialReferenceSetsInModel(setLonglineDtoForm); + + getModel().setForm(setLonglineDtoForm); + + SetLonglineDetailCompositionDto bean = getBean(); + SetLonglineDetailCompositionDtos.copySetLonglineDetailCompositionDto(setLonglineDtoForm.getObject(), bean); + + //FIXME Voir comment gérer ça + Form<BranchlineDto> branchlineDtoForm = Form.newFormDto(BranchlineDto.class, null, null, null); + + BranchlineUIModel branchlineUIModel = getUi().getBranchlineDetailUI().getModel(); + branchlineUIModel.setReferentialReferenceSets(getModel().getReferentialReferenceSets()); + branchlineUIModel.setForm(branchlineDtoForm); + + //FIXME Validate this default date + if (log.isInfoEnabled()) { + log.info("Use as default branchline timer date: " + bean.getSettingStartTimeStamp()); + } + getBranchlinesTableModel().setDefaultDate(bean.getSettingStartTimeStamp()); + getBranchlinesTableModel().setUseTimer(BooleanUtils.isTrue(bean.getMonitored())); + + // by default, can generate if there is no section in database + getModel().setCanGenerate(bean.isSectionEmpty()); + + // TODO Use a cache of templates on setLongline (session scope) + getSectionTemplatesTableModel().setData(new ArrayList<>()); + + BranchlineUI branchlineDetailUI = getUi().getBranchlineDetailUI(); + branchlineDetailUI.edit(null); + + onOpen = true; + + try { + + List<SectionWithTemplate> section = SectionWithTemplates.getSectionTemplates(bean.getSection()); + getSectionsTableModel().setData(section); + + validationHelper.setObjectValueAdjusting(true); + + try { + + onSectionTemplatesTableModelModified(false); + onSectionsTableModelModified(false); + onBasketsTableModelModified(false); + onBranchlinesTableModelModified(false); + + } finally { + + validationHelper.setObjectValueAdjusting(false); + validationHelper.whenSectionChanged(); + + } + + // Always go back to first tab + getUi().getFishingOperationTabPane().setSelectedIndex(0); + + } finally { + + onOpen = false; + + } + + if (mode != ContentMode.READ) { + getUi().startEdit(null); + } + + } + + @Override + public void startEditUI(String... binding) { + + ContentUIModel<SetLonglineDetailCompositionDto> model = getModel(); + addInfoMessage(t("observe.content.longlineDetailComposition.message.updating")); + + super.startEditUI(LonglineDetailCompositionUI.BINDING_GENERATE_ALL_ENABLED, + LonglineDetailCompositionUI.BINDING_DELETE_ALL_ENABLED); + + model.setModified(false); + + } + + @Override + protected boolean doSave(SetLonglineDetailCompositionDto bean) throws Exception { + + BranchlineUI branchlineDetailUI = getUi().getBranchlineDetailUI(); + + boolean continueSave = true; + + if (getUi().getFishingOperationTabPane().getSelectedIndex() == 2) { + + BranchlineUIHandler branchlineUIHandler = branchlineDetailUI.getHandler(); + + continueSave = branchlineUIHandler.tryToQuit(); + + } + + if (continueSave) { + + SectionsTableModel sectionsTableModel = getSectionsTableModel(); + SectionWithTemplate selectedSection = sectionsTableModel.getSelectedRow(); + if (selectedSection != null) { + + // flush selected section before save + flushSection(selectedSection); + + } + + SaveResultDto saveResult = getSetLonglineDetailCompositionService().save(bean); + saveResult.toDto(bean); + + } + + return continueSave; + } + + public void generateAllSections() { + + if (log.isInfoEnabled()) { + log.info("Generate all sections."); + } + + SetLonglineDetailCompositionDto bean = getBean(); + Integer nbSections = bean.getTotalSectionsCount(); + Integer basketsCount = bean.getBasketsPerSectionCount(); + Integer nbBranchlines = bean.getBranchlinesPerBasketCount(); + + SectionTemplate template = null; + + SectionTemplatesTableModel sectionTemplatesTableModel = getSectionTemplatesTableModel(); + List<SectionTemplate> sectionTemplates = sectionTemplatesTableModel.getNotEmptyData(); + if (sectionTemplates.size() == 1) { + + template = sectionTemplates.get(0); + + boolean compiliantWithBasketCount = template.isCompiliantWithBasketCount(basketsCount); + if (!compiliantWithBasketCount) { + + if (log.isWarnEnabled()) { + log.warn("sectionTemplate " + template + " is not compliant with basketCount: " + basketsCount); + } + + UIHelper.displayWarning(t("observe.content.longlineDetailComposition.title.section.cant.use.firstTemplate"), t("observe.content.longlineDetailComposition.firstTemplate.template.notCompilant.basketCount", template.getFloatlineLengths(), basketsCount)); + + template = null; + + } + + } + + boolean usingTemplate = template != null; + + if (usingTemplate) { + + if (log.isInfoEnabled()) { + log.info("Will use sectionTemplate: " + template); + } + } + + validationHelper.setObjectValueAdjusting(true); + + try { + + SectionsTableModel sectionsTableModel = getSectionsTableModel(); + BasketsTableModel basketsTableModel = getBasketsTableModel(); + BranchlinesTableModel branchlinesTableModel = getBranchlinesTableModel(); + + List<SectionWithTemplate> sections = new ArrayList<>(nbSections); + + for (int sectionNumber = 0; sectionNumber < nbSections; sectionNumber++) { + + SectionWithTemplate section = sectionsTableModel.createNewRow(); + sections.add(section); + + for (int basketNumber = 0; basketNumber < basketsCount; basketNumber++) { + + BasketDto basket = basketsTableModel.createNewRow(); + section.addBasket(basket); + + for (int branchlineNumber = 0; branchlineNumber < nbBranchlines; branchlineNumber++) { + + BranchlineDto branchline = branchlinesTableModel.createNewRow(); + basket.addBranchline(branchline); + + } + + LinkedList<BranchlineDto> branchlines = Lists.newLinkedList(basket.getBranchline()); + branchlinesTableModel.rearrangeIds(branchlines); + + } + + List<BasketDto> baskets = Lists.newLinkedList(section.getBasket()); + basketsTableModel.rearrangeIds(baskets); + + if (usingTemplate) { + + section.setSectionTemplate(template); + template.applyToBaskets(baskets); + + } + + } + + sectionsTableModel.rearrangeIds(sections); + sectionsTableModel.setData(sections); + + List<SectionDto> sectionDtos = sections.stream() + .map(SectionWithTemplate::getDelegate) + .collect(Collectors.toList()); + + getBean().addAllSection(sectionDtos); + + getModel().setModified(true); + + } finally { + + validationHelper.setObjectValueAdjusting(false); + validationHelper.whenSectionChanged(); + + } + + } + + public void deleteAllSections() { + + if (getSectionsTableModel().isEmpty()) { + + // no section + return; + } + + boolean canDelete = true; + for (SectionWithTemplate sectionWithTemplate : getSectionsTableModel().getNotEmptyData()) { + + if (!canDeleteSection(sectionWithTemplate.getDelegate())) { + canDelete = false; + break; + } + } + + if (!canDelete) { + + // there is some references, can't delete + UIHelper.displayWarning(t("observe.content.section.cant.delete.title"), t("observe.content.section.cant.delete.message")); + return; + + } + + ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); + int response = UIHelper.askUser(mainUI, + t("observe.title.delete"), + t("observe.content.sections.delete.message"), + JOptionPane.WARNING_MESSAGE, + new Object[]{t("observe.choice.confirm.delete"), + t("observe.choice.cancel")}, + 1); + + if (response != 0) { + + // user cancel + return; + } + + if (log.isInfoEnabled()) { + log.info("Remove all sections."); + } + + validationHelper.setObjectValueAdjusting(true); + + try { + + getSectionsTableModel().setData(new ArrayList<>()); + getBean().getSection().clear(); + getModel().setModified(true); + + } finally { + + validationHelper.setObjectValueAdjusting(false); + validationHelper.whenSectionChanged(); + + } + + } + + public void deleteSelectedSectionTemplate() { + + SectionTemplatesTableModel tableModel = getSectionTemplatesTableModel(); + boolean selectionEmpty = tableModel.isSelectionEmpty(); + + if (!selectionEmpty) { + + SectionTemplate data = getSectionTemplatesTableModel().getSelectedRow(); + + if (log.isInfoEnabled()) { + log.info("Delete: " + data); + } + + ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); + int response = UIHelper.askUser(mainUI, + t("observe.title.delete"), + t("observe.content.sectionTemplate.delete.message"), + JOptionPane.WARNING_MESSAGE, + new Object[]{t("observe.choice.confirm.delete"), + t("observe.choice.cancel")}, + 1); + + if (response != 0) { + + // user cancel + return; + } + + getSectionTemplatesTableModel().removeSelectedRow(); + + } + + } + + public void deleteSelectedSection() { + + SectionsTableModel tableModel = getSectionsTableModel(); + + boolean selectionEmpty = tableModel.isSelectionEmpty(); + + if (!selectionEmpty) { + + SectionWithTemplate selectedSection = tableModel.getSelectedRow(); + + boolean canDelete = canDeleteSection(selectedSection.getDelegate()); + + if (!canDelete) { + // there is some references, can't delete + UIHelper.displayWarning(t("observe.content.section.cant.delete.title"), t("observe.content.section.cant.delete.message")); + return; + } + + boolean accept = UIHelper.confirmForEntityDelete(ui, SectionDto.class, selectedSection); + + ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); + mainUI.setBusy(false); + + if (!accept) { + return; + } + + if (log.isInfoEnabled()) { + log.info("Delete section: " + sectionDecorator.toString(selectedSection)); + } + + validationHelper.setObjectValueAdjusting(true); + skipSavePreviousSelectedSection = true; + + try { + + getBean().removeSection(tableModel.getSelectedRow().getDelegate()); + tableModel.removeSelectedRow(); + + } finally { + + skipSavePreviousSelectedSection = false; + validationHelper.setObjectValueAdjusting(false); + validationHelper.whenSectionChanged(); + + } + + } + + } + + public void insertBeforeSelectedSection() { + + validationHelper.setObjectValueAdjusting(true); + + try { + + SectionsTableModel tableModel = getSectionsTableModel(); + tableModel.insertBeforeSelectedRow(); + + SectionWithTemplate newSectionWithTemplate = tableModel.getSelectedRow(); + int selectedRowIndex = tableModel.getSelectedRowIndex(); + List<SectionDto> sections = newArrayList(getBean().getSection()); + sections.add(selectedRowIndex, newSectionWithTemplate.getDelegate()); + getBean().getSection().clear(); + getBean().addAllSection(sections); + + } finally { + + validationHelper.setObjectValueAdjusting(false); + validationHelper.whenSectionChanged(); + + } + + } + + public void insertAfterSelectedSection() { + + validationHelper.setObjectValueAdjusting(true); + + try { + + SectionsTableModel tableModel = getSectionsTableModel(); + tableModel.insertAfterSelectedRow(); + + SectionWithTemplate newSectionWithTemplate = tableModel.getSelectedRow(); + int selectedRowIndex = tableModel.getSelectedRowIndex(); + List<SectionDto> sections = newArrayList(getBean().getSection()); + sections.add(selectedRowIndex, newSectionWithTemplate.getDelegate()); + getBean().getSection().clear(); + getBean().addAllSection(sections); + + } finally { + + validationHelper.setObjectValueAdjusting(false); + validationHelper.whenSectionChanged(); + + } + + } + + public void deleteSelectedBasket() { + + BasketsTableModel tableModel = getBasketsTableModel(); + + boolean selectionNotEmpty = !tableModel.isSelectionEmpty(); + + if (selectionNotEmpty) { + + BasketDto selectedBasket = tableModel.getSelectedRow(); + + boolean canDelete = canDeleteBasket(selectedBasket); + + if (!canDelete) { + + // there is some references, can't delete + UIHelper.displayWarning(t("observe.content.basket.cant.delete.title"), t("observe.content.basket.cant.delete.message")); + return; + + } + + boolean accept = UIHelper.confirmForEntityDelete(ui, BasketDto.class, selectedBasket); + ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); + mainUI.setBusy(false); + + if (!accept) { + return; + } + + if (log.isInfoEnabled()) { + log.info("Delete basket: " + basketDecorator.toString(selectedBasket)); + } + + validationHelper.setObjectValueAdjusting(true); + skipSavePreviousSelectedBasket = true; + + try { + + getSectionsTableModel().getSelectedRow().removeBasket(selectedBasket); + tableModel.removeSelectedRow(); + + } finally { + + skipSavePreviousSelectedBasket = false; + + validationHelper.setObjectValueAdjusting(false); + validationHelper.whenBasketChanged(); + + } + + } + + } + + public void insertBeforeSelectedBasket() { + + validationHelper.setObjectValueAdjusting(true); + + try { + + BasketsTableModel tableModel = getBasketsTableModel(); + tableModel.insertBeforeSelectedRow(); + + BasketDto newBasket = tableModel.getSelectedRow(); + int selectedRowIndex = tableModel.getSelectedRowIndex(); + SectionWithTemplate selectedSection = getSectionsTableModel().getSelectedRow(); + if (selectedSection.isBasketEmpty()) { + selectedSection.setBasket(new LinkedHashSet<>()); + } + List<BasketDto> baskets = newArrayList(selectedSection.getBasket()); + baskets.add(selectedRowIndex, newBasket); + selectedSection.getBasket().clear(); + selectedSection.addAllBasket(baskets); + + } finally { + + validationHelper.setObjectValueAdjusting(false); + validationHelper.whenBasketChanged(); + + } + + } + + public void insertAfterSelectedBasket() { + + validationHelper.setObjectValueAdjusting(true); + + try { + + BasketsTableModel tableModel = getBasketsTableModel(); + tableModel.insertAfterSelectedRow(); + + BasketDto newBasket = tableModel.getSelectedRow(); + int selectedRowIndex = tableModel.getSelectedRowIndex(); + SectionWithTemplate selectedSection = getSectionsTableModel().getSelectedRow(); + if (selectedSection.isBasketEmpty()) { + selectedSection.setBasket(new LinkedHashSet<>()); + } + List<BasketDto> baskets = newArrayList(selectedSection.getBasket()); + baskets.add(selectedRowIndex, newBasket); + selectedSection.getBasket().clear(); + selectedSection.addAllBasket(baskets); + + } finally { + + validationHelper.setObjectValueAdjusting(false); + validationHelper.whenBasketChanged(); + + } + + } + + public void deleteSelectedBranchline() { + + BranchlinesTableModel tableModel = getBranchlinesTableModel(); + + boolean selectionNotEmpty = !tableModel.isSelectionEmpty(); + + if (selectionNotEmpty) { + + BranchlineDto selectedBranchline = tableModel.getSelectedRow(); + + boolean canDelete = canDeleteBranchline(selectedBranchline); + + if (!canDelete) { + + // there is some references, can't delete + UIHelper.displayWarning(t("observe.content.branchLine.cant.delete.title"), t("observe.content.branchLine.cant.delete.message")); + return; + + } + + boolean accept = UIHelper.confirmForEntityDelete(ui, BranchlineDto.class, selectedBranchline); + ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); + mainUI.setBusy(false); + if (!accept) { + return; + } + + if (log.isInfoEnabled()) { + log.info("Delete branchline: " + branchlineDecorator.toString(selectedBranchline)); + } + + validationHelper.setObjectValueAdjusting(true); + skipSavePreviousSelectedBranchline = true; + + try { + + getBasketsTableModel().getSelectedRow().removeBranchline(selectedBranchline); + tableModel.removeSelectedRow(); + + } finally { + + skipSavePreviousSelectedBranchline = false; + validationHelper.setObjectValueAdjusting(false); + validationHelper.whenBranchlineChanged(); + + } + + } + + } + + public void insertBeforeSelectedBranchline() { + + validationHelper.setObjectValueAdjusting(true); + + try { + + BranchlinesTableModel tableModel = getBranchlinesTableModel(); + tableModel.insertBeforeSelectedRow(); + + BranchlineDto newBranchline = tableModel.getSelectedRow(); + int selectedRowIndex = tableModel.getSelectedRowIndex(); + BasketDto selectedBasket = getBasketsTableModel().getSelectedRow(); + if (selectedBasket.isBranchlineEmpty()) { + selectedBasket.setBranchline(new LinkedHashSet<>()); + } + + List<BranchlineDto> branchlines = newArrayList(selectedBasket.getBranchline()); + branchlines.add(selectedRowIndex, newBranchline); + selectedBasket.getBranchline().clear(); + selectedBasket.addAllBranchline(branchlines); + + } finally { + + validationHelper.setObjectValueAdjusting(false); + validationHelper.whenBasketChanged(); + + } + + } + + public void insertAfterSelectedBranchline() { + + validationHelper.setObjectValueAdjusting(true); + + try { + + BranchlinesTableModel tableModel = getBranchlinesTableModel(); + tableModel.insertAfterSelectedRow(); + + BranchlineDto newBranchline = tableModel.getSelectedRow(); + int selectedRowIndex = tableModel.getSelectedRowIndex(); + BasketDto selectedBasket = getBasketsTableModel().getSelectedRow(); + if (selectedBasket.isBranchlineEmpty()) { + selectedBasket.setBranchline(new LinkedHashSet<>()); + } + List<BranchlineDto> branchlines = newArrayList(selectedBasket.getBranchline()); + branchlines.add(selectedRowIndex, newBranchline); + selectedBasket.getBranchline().clear(); + selectedBasket.addAllBranchline(branchlines); + + + } finally { + + validationHelper.setObjectValueAdjusting(false); + validationHelper.whenBasketChanged(); + + } + + } + + protected void onSectionTemplatesTableModelModified(Boolean newValue) { + + // recompute table model valid state + getSectionTemplatesTableModel().validate(); + + } + + protected void onSectionsTableModelModified(Boolean newValue) { + + if (newValue) { + + getModel().setModified(true); + + } + + validationHelper.whenSectionChanged(); + + } + + protected void onSectionsTableModelChanged(List<SectionWithTemplate> data) { + + if (log.isInfoEnabled()) { + log.info("Sections was changed, new size: " + data.size()); + } + + validationHelper.whenSectionChanged(); + + } + + protected void onModelCanGenerateChanged(Boolean canGenerate) { + + if (canGenerate) { + + if (getSectionTemplatesTableModel().isEmpty()) { + + // add an empty row + getSectionTemplatesTableModel().addNewRow(); + + } + + } + + } + + protected void onSelectedSectionChanged(SectionDto previousSection, SectionDto newSection) { + + if (log.isInfoEnabled()) { + log.info("New selected section: " + sectionDecorator.toString(newSection)); + } + + validationHelper.setObjectValueAdjusting(true); + + try { + + if (previousSection != null && !onOpen && !skipSavePreviousSelectedSection) { + + // must flush back baksets to the previous section + flushSection(previousSection); + + } + + List<BasketDto> baskets = newSection == null ? new ArrayList<>() : newArrayList(newSection.getBasket()); + getBasketsTableModel().setData(baskets); + + } finally { + + validationHelper.setObjectValueAdjusting(false); + + } + + } + + protected void onSelectedSectionTemplateChanged(SectionTemplate newTemplate) { + + if (newTemplate != null) { + + SectionWithTemplate selectedSection = getSectionsTableModel().getSelectedRow(); + if (log.isInfoEnabled()) { + log.info("Will apply template: " + newTemplate + " to section: " + sectionDecorator.toString(selectedSection)); + } + + validationHelper.setObjectValueAdjusting(true); + + try { + + getBasketsTableModel().applySectionTemplate(newTemplate); + + } finally { + + validationHelper.setObjectValueAdjusting(false); + validationHelper.whenSectionChanged(); + + } + + } + + } + + protected void onBasketsTableModelModified(Boolean newValue) { + + if (newValue) { + + getModel().setModified(true); + + } + + validationHelper.whenBasketChanged(); + + } + + protected void onBasketsTableModelChanged(List<BasketDto> data) { + + if (log.isInfoEnabled()) { + log.info("Baskets was changed, new size: " + data.size()); + } + + } + + protected void onSelectedBasketChanged(BasketDto previousBasket, BasketDto newBasket) { + + if (log.isInfoEnabled()) { + log.info("New selected basket: " + basketDecorator.toString(newBasket)); + } + + if (previousBasket != null && !sectionAdjusting && !skipSavePreviousSelectedBasket) { + + flushBasket(previousBasket); + + } + + List<BranchlineDto> branchlines = new ArrayList<>(); + if (newBasket != null && newBasket.getBranchline() != null) { + branchlines.addAll(newBasket.getBranchline()); + } + getBranchlinesTableModel().setData(branchlines); + + } + + protected void onBranchlinesTableModelModified(Boolean newValue) { + + if (newValue) { + + getModel().setModified(true); + + } + + validationHelper.whenBranchlineChanged(); + + } + + protected void onBranchlinesTableModelChanged(List<BranchlineDto> data) { + + if (log.isInfoEnabled()) { + log.info("Branchlines was changed, new size: " + data.size()); + } + + } + + protected void onSelectedBranchlineChanged(BranchlineDto previousBranchline, BranchlineDto newBranchline) { + + if (log.isInfoEnabled()) { + log.info("New selected branchline: " + branchlineDecorator.toString(newBranchline)); + } + + if (previousBranchline != null && !basketAdjusting && !skipSavePreviousSelectedBranchline) { + + // must flush back branchline detail to his row + flushBranchline(previousBranchline); + + } + + } + + protected boolean onTabWillChanged(int selectedIndex, int index) { + + boolean result = true; + + if (!onOpen && index > -1) { + + switch (selectedIndex) { + + case 0: + + boolean generateTabValid = getModel().isGenerateTabValid(); + result = generateTabValid; + + break; + + case 1: + + boolean compositionTabValid = getModel().isCompositionTabValid(); + result = compositionTabValid; + + break; + + case 2: + + boolean branchlineDetailTabValid = getUi().getBranchlineDetailUI().getHandler().tryToQuit(); + result = branchlineDetailTabValid; + + break; + } + + } + + return result; + } + + protected void onTabChanged(int previousIndex, int selectedIndex) { + + switch (previousIndex) { + case 0: + + // abort editing table + UIHelper.stopEditing(getUi().getSectionTemplatesTable()); + + break; + case 1: + + // abort editing tables + UIHelper.stopEditing(getUi().getSectionsTable()); + + break; + case 2: + + BranchlineUI branchlineDetailUI = getUi().getBranchlineDetailUI(); + branchlineDetailUI.getModel().removePropertyChangeListener(BranchlineUIModel.PROPERTY_MODIFIED, branchlineDetailChanged); + branchlineDetailUI.edit(null); + + break; + } + + switch (selectedIndex) { + case 0: + + break; + case 1: + + if (previousIndex == 0) { + + if (getModel().isCanGenerate()) { + + // update section templates list + List<SectionTemplate> sectionTemplates = getSectionTemplatesTableModel().getNotEmptyData(); + JComboBox comboBox = (JComboBox) getUi().getSectionsTable().getClientProperty(SECTION_TEMPLATES_EDITOR); + LonglineDetailCompositionUIInitializer.prepareComboBoxData(comboBox, sectionTemplates); + + //FIXME See why templates are not well reselect in cell editor + //FIXME See cell editor does not loose focus and empty selection when losing focus + + } + } + + break; + case 2: + + BranchlineDto branchline = getBranchlinesTableModel().getSelectedRow(); + + if (branchline != null) { + + // update branchline detail + BranchlineUI branchlineDetailUI = getUi().getBranchlineDetailUI(); + branchlineDetailUI.edit(branchline); + branchlineDetailUI.getModel().addPropertyChangeListener(BranchlineUIModel.PROPERTY_MODIFIED, branchlineDetailChanged); + + } + + break; + + } + + } + + protected void flushSection(SectionDto section) { + + BasketsTableModel basketsTableModel = getBasketsTableModel(); + + if (!basketsTableModel.isSelectionEmpty()) { + + // must flush back branchlines to selected basket + BasketDto selectedBasket = basketsTableModel.getSelectedRow(); + flushBasket(selectedBasket); + + } + + // flush bask baskets to the given section + + List<BasketDto> baskets = basketsTableModel.getNotEmptyData(); + section.setBasket(new LinkedHashSet<>(baskets)); + + if (log.isInfoEnabled()) { + log.info("Flush baskets (" + baskets.size() + ") to his section: " + sectionDecorator.toString(section)); + } + + } + + protected void flushBasket(BasketDto basket) { + + BranchlinesTableModel branchlinesTableModel = getBranchlinesTableModel(); + + if (!branchlinesTableModel.isSelectionEmpty()) { + + // must flush back details to selected branchline + flushBranchline(branchlinesTableModel.getSelectedRow()); + + } + + // flush bask branchlines to the given basket + + List<BranchlineDto> branchlines = branchlinesTableModel.getNotEmptyData(); + basket.setBranchline(new LinkedHashSet<>(branchlines)); + + if (log.isInfoEnabled()) { + log.info("Flush branchlines (" + branchlines.size() + ") to his basket: " + basketDecorator.toString(basket)); + } + + } + + protected void flushBranchline(BranchlineDto branchline) { + + if (log.isInfoEnabled()) { + log.info("Flush branchline details: " + branchlineDecorator.toString(branchline)); + } + + } + + protected SectionTemplatesTableModel getSectionTemplatesTableModel() { + return getModel().getSectionTemplatesTableModel(); + } + + protected SectionsTableModel getSectionsTableModel() { + return getModel().getSectionsTableModel(); + } + + protected BasketsTableModel getBasketsTableModel() { + return getModel().getBasketsTableModel(); + } + + protected BranchlinesTableModel getBranchlinesTableModel() { + return getModel().getBranchlinesTableModel(); + } + + public BranchlineUIModel getBranchlineDetailUIModel() { + return getUi().getBranchlineDetailUIModel(); + } + + protected boolean canDeleteSection(SectionDto section) { + + return section.isNotPersisted() || getSetLonglineDetailCompositionService().canDeleteSection(section.getId()); + + } + + protected boolean canDeleteBasket(BasketDto basket) { + + return basket.isNotPersisted() || getSetLonglineDetailCompositionService().canDeleteBasket(basket.getId()); + + } + + protected boolean canDeleteBranchline(BranchlineDto branchline) { + + return branchline.isNotPersisted() || getSetLonglineDetailCompositionService().canDeleteBranchline(branchline.getId()); + + } + + protected SetLonglineDetailCompositionService getSetLonglineDetailCompositionService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newSetLonglineDetailCompositionService(); + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionUIInitializer.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionUIInitializer.java new file mode 100644 index 0000000..1f3f049 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionUIInitializer.java @@ -0,0 +1,398 @@ +package fr.ird.observe.application.swing.ui.content.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.longline.SectionTemplate; +import fr.ird.observe.services.dto.longline.SetLonglineDetailCompositionDto; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.ContentUIInitializer; +import fr.ird.observe.application.swing.ui.util.table.AutotSelectRowAndShowPopupActionSupport; +import fr.ird.observe.application.swing.ui.util.table.EditableTableModelSupport; +import org.jdesktop.swingx.autocomplete.ComboBoxCellEditor; +import org.nuiton.decorator.Decorator; + +import javax.swing.JComboBox; +import javax.swing.JPopupMenu; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.ListSelectionModel; +import javax.swing.table.TableCellRenderer; +import java.awt.Container; +import java.io.Serializable; +import java.util.Collections; + +import static org.nuiton.i18n.I18n.n; + +/** + * Created on 12/13/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.10 + */ +public class LonglineDetailCompositionUIInitializer extends ContentUIInitializer<SetLonglineDetailCompositionDto, LonglineDetailCompositionUI> { + + public LonglineDetailCompositionUIInitializer(LonglineDetailCompositionUI ui) { + super(ui); + } + + @Override + public void initUI() { + super.initUI(); + + LonglineDetailCompositionUIModel model = ui.getModel(); + + { + // init section templates table + JTable table = ui.getSectionTemplatesTable(); + + UIHelper.setI18nTableHeaderRenderer(table, + n("observe.content.longlineDetailComposition.sectionTemplatesTable.identifier"), + n("observe.content.longlineDetailComposition.sectionTemplatesTable.identifier.tip"), + n("observe.content.longlineDetailComposition.sectionTemplatesTable.value"), + n("observe.content.longlineDetailComposition.sectionTemplatesTable.value.tip")); + + SectionTemplatesTableModel tableModel = model.getSectionTemplatesTableModel(); + tableModel.installTableKeyListener(table); + tableModel.installTableFocusListener(table); + + ListSelectionModel selectionModel = table.getSelectionModel(); + selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + tableModel.installSelectionListener(table); + + new SectionTemplatesAutotSelectRowAndShowPopupAction(ui, ui.getSectionTemplatesPane(), table, ui.getSectionTemplatesPopup()); + + } + + { + // init sections table + JTable table = ui.getSectionsTable(); + + UIHelper.setI18nTableHeaderRenderer(table, + n("observe.content.longlineDetailComposition.sectionsTable.settingIdentifier"), + n("observe.content.longlineDetailComposition.sectionsTable.settingIdentifier.tip"), + n("observe.content.longlineDetailComposition.sectionsTable.haulingIdentifier"), + n("observe.content.longlineDetailComposition.sectionsTable.haulingIdentifier.tip"), + n("observe.content.longlineDetailComposition.sectionsTable.template"), + n("observe.content.longlineDetailComposition.sectionsTable.template.tip")); + + TableCellRenderer renderer = table.getDefaultRenderer(Object.class); + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 2, UIHelper.newDecorateTableCellRenderer(renderer, SectionTemplate.class)); + + UIHelper.setTableColumnEditor(table, 1, newIntegerColumnEditor(table)); + + DecoratorService decoratorService = ui.getHandler().getDecoratorService(); + Decorator<SectionTemplate> sectionTemplateDecorator = decoratorService.getDecoratorByType(SectionTemplate.class); + JComboBox comboBox = new JComboBox(); + table.putClientProperty(LonglineDetailCompositionUIHandler.SECTION_TEMPLATES_EDITOR, comboBox); + ComboBoxCellEditor editor = newDataColumnEditor(comboBox, Collections.emptyList(), sectionTemplateDecorator); + UIHelper.setTableColumnEditor(table, 2, editor); + + SectionsTableModel tableModel = model.getSectionsTableModel(); + tableModel.installTableKeyListener(table); + tableModel.installTableFocusListener(table); + + ListSelectionModel selectionModel = table.getSelectionModel(); + selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + tableModel.installSelectionListener(table); + + new SectionsAutotSelectRowAndShowPopupAction(ui, ui.getSectionsPane(), table, ui.getSectionsPopup()); + + } + { + // init baskets table + JTable table = ui.getBasketsTable(); + + UIHelper.setI18nTableHeaderRenderer(table, + n("observe.content.longlineDetailComposition.basketsTable.settingIdentifier"), + n("observe.content.longlineDetailComposition.basketsTable.settingIdentifier.tip"), + n("observe.content.longlineDetailComposition.basketsTable.haulingIdentifier"), + n("observe.content.longlineDetailComposition.basketsTable.haulingIdentifier.tip"), + n("observe.content.longlineDetailComposition.basketsTable.floatline1Length"), + n("observe.content.longlineDetailComposition.basketsTable.floatline1Length.tip"), + n("observe.content.longlineDetailComposition.basketsTable.floatline2Length"), + n("observe.content.longlineDetailComposition.basketsTable.floatline2Length.tip")); + + TableCellRenderer renderer = table.getDefaultRenderer(Object.class); + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + + UIHelper.setTableColumnEditor(table, 1, newIntegerColumnEditor(table)); + UIHelper.setTableColumnEditor(table, 2, newFloatColumnEditor(table)); + UIHelper.setTableColumnEditor(table, 3, newFloatColumnEditor(table)); + + BasketsTableModel tableModel = model.getBasketsTableModel(); + tableModel.installTableKeyListener(table); + tableModel.installTableFocusListener(table); + + ListSelectionModel selectionModel = table.getSelectionModel(); + selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + tableModel.installSelectionListener(table); + + new BasketsAutotSelectRowAndShowPopupAction(ui, ui.getBasketsPane(), table, ui.getBasketsPopup()); + + } + + { + // init branchlines table + JTable table = ui.getBranchlinesTable(); + + UIHelper.setI18nTableHeaderRenderer(table, + n("observe.content.longlineDetailComposition.branchlinesTable.settingIdentifier"), + n("observe.content.longlineDetailComposition.branchlinesTable.settingIdentifier.tip"), + n("observe.content.longlineDetailComposition.branchlinesTable.haulingIdentifier"), + n("observe.content.longlineDetailComposition.branchlinesTable.haulingIdentifier.tip"), + n("observe.content.longlineDetailComposition.branchlinesTable.branchlineLength"), + n("observe.content.longlineDetailComposition.branchlinesTable.branchlineLength.tip"), + n("observe.content.longlineDetailComposition.branchlinesTable.tracelineLength"), + n("observe.content.longlineDetailComposition.branchlinesTable.tracelineLength.tip")); + + TableCellRenderer renderer = table.getDefaultRenderer(Object.class); + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + + UIHelper.setTableColumnEditor(table, 1, newIntegerColumnEditor(table)); + UIHelper.setTableColumnEditor(table, 2, newFloatColumnEditor(table)); + UIHelper.setTableColumnEditor(table, 3, newFloatColumnEditor(table)); + + BranchlinesTableModel tableModel = model.getBranchlinesTableModel(); + tableModel.installTableKeyListener(table); + tableModel.installTableFocusListener(table); + + ListSelectionModel selectionModel = table.getSelectionModel(); + selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + tableModel.installSelectionListener(table); + + new BranchlinesAutotSelectRowAndShowPopupAction(ui, ui.getBranchlinesPane(), table, ui.getBranchlinesPopup()); + + } + + { + + // init branchlineDetail tab + BranchlineUI compositionUI = ui.getBranchlineDetailUI(); + compositionUI.init(); + Container parent = ui.getBranchlineDetailPanel(); + parent .removeAll(); + parent.add(compositionUI.getBody()); + + } + + } + + + static class SectionTemplatesAutotSelectRowAndShowPopupAction extends AutotSelectRowAndShowPopupActionSupport { + + private final LonglineDetailCompositionUI ui; + + public SectionTemplatesAutotSelectRowAndShowPopupAction(LonglineDetailCompositionUI ui, + JScrollPane pane, + JTable table, + JPopupMenu popup) { + super(pane, table, popup); + this.ui = ui; + } + + @Override + protected void beforeOpenPopup(int modelRowIndex, int modelColumnIndex) { + + EditableTableModelSupport model = (EditableTableModelSupport) getTable().getModel(); + + boolean canDelete = !model.isSelectionEmpty(); + + if (canDelete) { + + // check also that the row is not empty + Serializable selectedData = model.getSelectedRow(); + canDelete = model.isRowNotEmpty(selectedData); + + } + + ui.getDeleteSelectedSectionTemplate().setEnabled(canDelete); + + } + + } + + static class SectionsAutotSelectRowAndShowPopupAction extends AutotSelectRowAndShowPopupActionSupport { + + private final LonglineDetailCompositionUI ui; + + public SectionsAutotSelectRowAndShowPopupAction(LonglineDetailCompositionUI ui, + JScrollPane pane, + JTable table, + JPopupMenu popup) { + super(pane, table, popup); + this.ui = ui; + } + + @Override + protected void beforeOpenPopup(int modelRowIndex, int modelColumnIndex) { + + EditableTableModelSupport model = (EditableTableModelSupport) getTable().getModel(); + + boolean selectionNotEmpty = !model.isSelectionEmpty(); + boolean selectedRowIsNotEmpty = false; + + if (selectionNotEmpty) { + + Serializable selectedData = model.getSelectedRow(); + selectedRowIsNotEmpty = model.isRowNotEmpty(selectedData); + + } + + boolean canDelete = false; + boolean canInsertBefore = true; + boolean canInsertAfter = true; + + if (selectionNotEmpty) { + + // can delete only a non empty selected row + canDelete = selectedRowIsNotEmpty; + + // won't add before an empty row + canInsertBefore = selectedRowIsNotEmpty; + + // won't after before an empty row + canInsertAfter = selectedRowIsNotEmpty; + + } + + ui.getDeleteSelectedSection().setEnabled(canDelete); + ui.getInsertBeforeSelectedSection().setEnabled(canInsertBefore); + ui.getInsertAfterSelectedSection().setEnabled(canInsertAfter); + + } + + } + + static class BasketsAutotSelectRowAndShowPopupAction extends AutotSelectRowAndShowPopupActionSupport { + + private final LonglineDetailCompositionUI ui; + + public BasketsAutotSelectRowAndShowPopupAction(LonglineDetailCompositionUI ui, + JScrollPane pane, + JTable table, + JPopupMenu popup) { + super(pane, table, popup); + this.ui = ui; + } + + @Override + protected void beforeOpenPopup(int modelRowIndex, int modelColumnIndex) { + + EditableTableModelSupport model = (EditableTableModelSupport) getTable().getModel(); + + boolean selectionNotEmpty = !model.isSelectionEmpty(); + boolean selectedRowIsNotEmpty = false; + + if (selectionNotEmpty) { + + Serializable selectedData = model.getSelectedRow(); + selectedRowIsNotEmpty = model.isRowNotEmpty(selectedData); + + } + + boolean canDelete = false; + boolean canInsertBefore = true; + boolean canInsertAfter = true; + + if (selectionNotEmpty) { + + // can delete only a non empty selected row + canDelete = selectedRowIsNotEmpty; + + // won't add before an empty row + canInsertBefore = selectedRowIsNotEmpty; + + // won't after before an empty row + canInsertAfter = selectedRowIsNotEmpty; + + } + + ui.getDeleteSelectedBasket().setEnabled(canDelete); + ui.getInsertBeforeSelectedBasket().setEnabled(canInsertBefore); + ui.getInsertAfterSelectedBasket().setEnabled(canInsertAfter); + + } + + } + + static class BranchlinesAutotSelectRowAndShowPopupAction extends AutotSelectRowAndShowPopupActionSupport { + + private final LonglineDetailCompositionUI ui; + + public BranchlinesAutotSelectRowAndShowPopupAction(LonglineDetailCompositionUI ui, + JScrollPane pane, + JTable table, + JPopupMenu popup) { + super(pane, table, popup); + this.ui = ui; + } + + @Override + protected void beforeOpenPopup(int modelRowIndex, int modelColumnIndex) { + + EditableTableModelSupport model = (EditableTableModelSupport) getTable().getModel(); + + boolean selectionNotEmpty = !model.isSelectionEmpty(); + boolean selectedRowIsNotEmpty = false; + + if (selectionNotEmpty) { + + Serializable selectedData = model.getSelectedRow(); + selectedRowIsNotEmpty = model.isRowNotEmpty(selectedData); + + } + + boolean canDelete = false; + boolean canInsertBefore = true; + boolean canInsertAfter = true; + + if (selectionNotEmpty) { + + // can delete only a non empty selected row + canDelete = selectedRowIsNotEmpty; + + // won't add before an empty row + canInsertBefore = selectedRowIsNotEmpty; + + // won't after before an empty row + canInsertAfter = selectedRowIsNotEmpty; + + } + + ui.getDeleteSelectedBranchline().setEnabled(canDelete); + ui.getInsertBeforeSelectedBranchline().setEnabled(canInsertBefore); + ui.getInsertAfterSelectedBranchline().setEnabled(canInsertAfter); + + } + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionUIModel.java new file mode 100644 index 0000000..79cbeaa --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionUIModel.java @@ -0,0 +1,132 @@ +package fr.ird.observe.application.swing.ui.content.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.longline.SetLonglineDetailCompositionDto; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; + +/** + * Created on 12/5/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.8 + */ +public class LonglineDetailCompositionUIModel extends ContentUIModel<SetLonglineDetailCompositionDto> { + + public static final String PROPERTY_CAN_GENERATE = "canGenerate"; + + public static final String PROPERTY_GENERATE_TAB_VALID = "generateTabValid"; + + public static final String PROPERTY_COMPOSITION_TAB_VALID = "compositionTabValid"; + + public static final String PROPERTY_BRANCHLINE_DETAIL_TAB_VALID = "branchlineDetailTabValid"; + + private static final long serialVersionUID = 1L; + + protected final SectionTemplatesTableModel sectionTemplatesTableModel; + + protected final SectionsTableModel sectionsTableModel; + + protected final BasketsTableModel basketsTableModel; + + protected final BranchlinesTableModel branchlinesTableModel; + + protected boolean canGenerate; + + protected boolean generateTabValid; + + protected boolean compositionTabValid; + + protected boolean branchlineDetailTabValid; + + public LonglineDetailCompositionUIModel() { + + super(SetLonglineDetailCompositionDto.class); + this.sectionTemplatesTableModel = new SectionTemplatesTableModel(); + this.sectionsTableModel = new SectionsTableModel(this); + this.basketsTableModel = new BasketsTableModel(this); + this.branchlinesTableModel = new BranchlinesTableModel(this); + } + + public SectionTemplatesTableModel getSectionTemplatesTableModel() { + return sectionTemplatesTableModel; + } + + public BasketsTableModel getBasketsTableModel() { + return basketsTableModel; + } + + public SectionsTableModel getSectionsTableModel() { + return sectionsTableModel; + } + + public BranchlinesTableModel getBranchlinesTableModel() { + return branchlinesTableModel; + } + + public boolean isHaulingdirectionSameAsSettings() { + Boolean haulingDirectionSameAsSetting = getBean().getHaulingDirectionSameAsSetting(); + return haulingDirectionSameAsSetting != null && haulingDirectionSameAsSetting; + } + + public boolean isGenerateHaulingIds() { + return getBean().getHaulingBreaks() == 0; + } + + public boolean isCanGenerate() { + return canGenerate; + } + + public void setCanGenerate(boolean canGenerate) { + this.canGenerate = canGenerate; + firePropertyChange(PROPERTY_CAN_GENERATE, null, canGenerate); + } + + public boolean isBranchlineDetailTabValid() { + return branchlineDetailTabValid; + } + + public void setBranchlineDetailTabValid(boolean branchlineDetailTabValid) { + this.branchlineDetailTabValid = branchlineDetailTabValid; + firePropertyChange(PROPERTY_BRANCHLINE_DETAIL_TAB_VALID, null, branchlineDetailTabValid); + } + + public boolean isCompositionTabValid() { + return compositionTabValid; + } + + public void setCompositionTabValid(boolean compositionTabValid) { + this.compositionTabValid = compositionTabValid; + firePropertyChange(PROPERTY_COMPOSITION_TAB_VALID, null, compositionTabValid); + } + + public boolean isGenerateTabValid() { + return generateTabValid; + } + + public void setGenerateTabValid(boolean generateTabValid) { + this.generateTabValid = generateTabValid; + firePropertyChange(PROPERTY_GENERATE_TAB_VALID, null, generateTabValid); + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionUIValidationHelper.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionUIValidationHelper.java new file mode 100644 index 0000000..bffc230 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionUIValidationHelper.java @@ -0,0 +1,165 @@ +package fr.ird.observe.application.swing.ui.content.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.ImmutableMap; +import com.google.common.collect.ImmutableSet; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.services.dto.longline.BasketDto; +import fr.ird.observe.services.dto.longline.BranchlineDto; +import fr.ird.observe.services.dto.longline.SectionDto; +import fr.ird.observe.services.dto.longline.SectionWithTemplate; +import fr.ird.observe.application.swing.ui.util.ObserveSwingValidatorMessageTableModel; +import jaxx.runtime.validator.swing.SwingValidator; +import jaxx.runtime.validator.swing.SwingValidatorMessage; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.validator.bean.simple.SimpleBeanValidator; + +import javax.swing.JComponent; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Created on 3/18/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.15 + */ +public class LonglineDetailCompositionUIValidationHelper { + + /** Logger. */ + private static final Log log = LogFactory.getLog(LonglineDetailCompositionUIValidationHelper.class); + + private final LonglineDetailCompositionUIModel model; + + private final ObserveSwingValidatorMessageTableModel errorTableModel; + + private boolean objectValueAdjusting; + + private final LonglineDetailCompositionValidatorService validatorService; + + private final Set<SwingValidator> validators; + + public LonglineDetailCompositionUIValidationHelper(LonglineDetailCompositionUI ui, DecoratorService decoratorService) { + this.model = ui.getModel(); + this.errorTableModel = (ObserveSwingValidatorMessageTableModel) ui.getErrorTableModel(); + SwingValidator<SectionDto> sectionValidator = ui.getSectionValidator(); + SwingValidator<BasketDto> basketValidator = ui.getBasketValidator(); + SwingValidator<BranchlineDto> branchlineValidator = ui.getBranchlineValidator(); + + this.validators = ImmutableSet.<SwingValidator>builder().add( + sectionValidator, + basketValidator, + branchlineValidator + ).build(); + Map<SwingValidator, JComponent> validatorEditor = ImmutableMap.<SwingValidator, JComponent>builder() + .put(sectionValidator, ui.getSectionsPane()) + .put(basketValidator, ui.getBasketsPane()) + .put(branchlineValidator, ui.getBranchlinesPane()) + .build(); + + this.validatorService = new LonglineDetailCompositionValidatorService( + sectionValidator, + basketValidator, + branchlineValidator, + validatorEditor, + decoratorService + ); + } + + public void whenSectionChanged() { + + if (!objectValueAdjusting) { + + if (log.isInfoEnabled()) { + log.info("Rebuild messages, section model changes."); + } + + List<SectionWithTemplate> notEmptyData = model.getSectionsTableModel().getNotEmptyData(); + List<SwingValidatorMessage> messages = validatorService.validateSections(notEmptyData); + + removeOldMessages(); + + errorTableModel.addMessages(messages); + + model.setCompositionTabValid(messages.isEmpty()); + + } + } + + public void whenBasketChanged() { + + if (!objectValueAdjusting) { + + if (log.isInfoEnabled()) { + log.info("Rebuild messages, basket model changes."); + } + List<SectionWithTemplate> notEmptyData = model.getSectionsTableModel().getNotEmptyData(); + List<SwingValidatorMessage> messages = validatorService.validateSections(notEmptyData); + + removeOldMessages(); + + errorTableModel.addMessages(messages); + + model.setCompositionTabValid(messages.isEmpty()); + + } + + } + + public void whenBranchlineChanged() { + + if (!objectValueAdjusting) { + + if (log.isInfoEnabled()) { + log.info("Rebuild messages, branchline model changes."); + } + + List<SectionWithTemplate> notEmptyData = model.getSectionsTableModel().getNotEmptyData(); + List<SwingValidatorMessage> messages = validatorService.validateSections(notEmptyData); + + removeOldMessages(); + + errorTableModel.addMessages(messages); + + model.setCompositionTabValid(messages.isEmpty()); + + } + + } + + public void removeOldMessages() { + errorTableModel.removeMessages(input -> { + SimpleBeanValidator<?> validator = input.getValidator(); + boolean remove = validators.contains(validator); + return remove; + }); + } + + public void setObjectValueAdjusting(boolean objectValueAdjusting) { + this.objectValueAdjusting = objectValueAdjusting; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionValidationContext.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionValidationContext.java new file mode 100644 index 0000000..aec867a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionValidationContext.java @@ -0,0 +1,116 @@ +package fr.ird.observe.application.swing.ui.content.impl.longline; + +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.services.dto.longline.BasketDto; +import fr.ird.observe.services.dto.longline.BranchlineDto; +import fr.ird.observe.services.dto.longline.SectionDto; +import jaxx.runtime.validator.swing.SwingValidator; +import jaxx.runtime.validator.swing.SwingValidatorMessage; +import org.nuiton.validator.NuitonValidatorScope; +import org.nuiton.validator.bean.simple.SimpleBeanValidatorEvent; +import org.nuiton.validator.bean.simple.SimpleBeanValidatorListener; + +import javax.swing.JComponent; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 09/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + */ +public class LonglineDetailCompositionValidationContext implements SimpleBeanValidatorListener { + + SectionDto section; + + BasketDto basket; + + BranchlineDto branchline; + + String contextLabel; + + final List<SwingValidatorMessage> messages; + + final DecoratorService decoratorService; + + private final Map<SwingValidator, JComponent> validatorEditors; + + LonglineDetailCompositionValidationContext(DecoratorService decoratorService, Map<SwingValidator, JComponent> validatorEditors) { + this.decoratorService = decoratorService; + this.validatorEditors = validatorEditors; + this.messages = new ArrayList<>(); + } + + public List<SwingValidatorMessage> getMessages() { + return messages; + } + + public void setSection(SectionDto section) { + this.section = section; + this.basket = null; + this.branchline = null; + updateContextLabel(); + } + + public void setBasket(BasketDto basket) { + this.basket = basket; + this.branchline = null; + updateContextLabel(); + } + + public void setBranchline(BranchlineDto branchline) { + this.branchline = branchline; + updateContextLabel(); + } + + protected void updateContextLabel() { + + contextLabel = ""; + if (section != null) { + contextLabel += "S " + section.getSettingIdentifier(); + if (basket != null) { + contextLabel += " Ba " + basket.getSettingIdentifier(); + if (branchline != null) { + contextLabel += " Br " + branchline.getSettingIdentifier(); + } + } + } + + } + + @Override + public void onFieldChanged(SimpleBeanValidatorEvent event) { + + String[] messagesToAdd = event.getMessagesToAdd(); + if (messagesToAdd != null) { + + String field = event.getField(); + NuitonValidatorScope scope = event.getScope(); + SwingValidator<?> validator = (SwingValidator<?>) event.getSource(); + + for (String messageToAdd : messagesToAdd) { + addMessage(validator, scope, field, messageToAdd); + } + + } + + } + + public void addMessage(SwingValidator validator, NuitonValidatorScope scope, String field, String messageToAdd) { + + String propertyLabel = DecoratorService.getPropertyLabel(field); + SwingValidatorMessage message = new SwingValidatorMessage( + validator, + contextLabel + " - " + t(propertyLabel), + messageToAdd, + scope, + validatorEditors.get(validator) + ); + messages.add(message); + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionValidatorService.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionValidatorService.java new file mode 100644 index 0000000..ba95dd1 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionValidatorService.java @@ -0,0 +1,155 @@ +package fr.ird.observe.application.swing.ui.content.impl.longline; + +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.services.dto.longline.BasketDto; +import fr.ird.observe.services.dto.longline.BranchlineDto; +import fr.ird.observe.services.dto.longline.SectionDto; +import jaxx.runtime.validator.swing.SwingValidator; +import jaxx.runtime.validator.swing.SwingValidatorMessage; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.JComponent; +import java.util.List; +import java.util.Map; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 09/08/16. + * + * @author Tony Chemit - chemit@codelutin.com + */ +public class LonglineDetailCompositionValidatorService { + + private final SwingValidator<SectionDto> sectionValidator; + + private final SwingValidator<BasketDto> basketValidator; + + private final SwingValidator<BranchlineDto> branchlineValidator; + + private final DecoratorService decoratorService; + + private final Map<SwingValidator, JComponent> validatorEditors; + + public LonglineDetailCompositionValidatorService(SwingValidator<SectionDto> sectionValidator, + SwingValidator<BasketDto> basketValidator, + SwingValidator<BranchlineDto> branchlineValidator, + Map<SwingValidator, JComponent> validatorEditors, + DecoratorService decoratorService) { + this.sectionValidator = sectionValidator; + this.basketValidator = basketValidator; + this.branchlineValidator = branchlineValidator; + this.validatorEditors = validatorEditors; + this.decoratorService = decoratorService; + + } + + public List<SwingValidatorMessage> validateSections(List<? extends SectionDto> sections) { + + LonglineDetailCompositionValidationContext validationContext = new LonglineDetailCompositionValidationContext(decoratorService, validatorEditors); + + addListener(validationContext); + + try { + + for (SectionDto section : sections) { + + validateSection(validationContext, section); + + } + + } finally { + + removeListener(validationContext); + + } + + return validationContext.getMessages(); + + } + + protected void validateSection(LonglineDetailCompositionValidationContext validationContext, SectionDto section) { + + validationContext.setSection(section); + validationContext.setBasket(null); + validationContext.setBranchline(null); + + sectionValidator.setBean(null); + sectionValidator.setBean(section); + + if (!section.isBasketEmpty()) { + + BasketDto previousBasket = null; + + for (BasketDto basket : section.getBasket()) { + + if (previousBasket != null) { + + // validate previousBasket.floatline2Length = basket.floatline1Length + Float previousBasketFloatline2Length = previousBasket.getFloatline2Length(); + Float basketFloatline1Length = basket.getFloatline1Length(); + if (previousBasketFloatline2Length != null + && basketFloatline1Length != null + && Math.abs(previousBasketFloatline2Length - basketFloatline1Length) > 0.001f) { + + validationContext.addMessage(basketValidator, NuitonValidatorScope.ERROR, "floatline2Length", t("observe.content.basket.invalid.nextFloatline1Length", previousBasketFloatline2Length, basketFloatline1Length)); + + } + } + + validateBasket(validationContext, basket); + + previousBasket = basket; + + } + } + + } + + protected void validateBasket(LonglineDetailCompositionValidationContext validationContext, BasketDto basket) { + + validationContext.setBranchline(null); + validationContext.setBasket(basket); + + basketValidator.setBean(null); + basketValidator.setBean(basket); + + if (!basket.isBranchlineEmpty()) { + + for (BranchlineDto branchline : basket.getBranchline()) { + + validateBranchline(validationContext, branchline); + + } + } + + validationContext.setBranchline(null); + + } + + protected void validateBranchline(LonglineDetailCompositionValidationContext validationContext, BranchlineDto branchline) { + + validationContext.setBranchline(branchline); + branchlineValidator.setBean(null); + branchlineValidator.setBean(branchline); + + + } + + protected void addListener(LonglineDetailCompositionValidationContext validationContext) { + + sectionValidator.addSimpleBeanValidatorListener(validationContext); + basketValidator.addSimpleBeanValidatorListener(validationContext); + branchlineValidator.addSimpleBeanValidatorListener(validationContext); + + } + + protected void removeListener(LonglineDetailCompositionValidationContext validationContext) { + + sectionValidator.removeSimpleBeanValidatorListener(validationContext); + basketValidator.removeSimpleBeanValidatorListener(validationContext); + branchlineValidator.removeSimpleBeanValidatorListener(validationContext); + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineGlobalCompositionUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineGlobalCompositionUI.jaxx new file mode 100644 index 0000000..f5b137f --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineGlobalCompositionUI.jaxx @@ -0,0 +1,157 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ContentUI superGenericType='SetLonglineGlobalCompositionDto' + contentTitle='{n("observe.content.longlineGlobalComposition.title")}'> + + <import> + fr.ird.observe.application.swing.ObserveSwingApplicationContext + fr.ird.observe.services.dto.CommentableDto + fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.longline.MitigationTypeDto + fr.ird.observe.application.swing.ui.actions.shared.ResetEditUIAction + fr.ird.observe.application.swing.ui.actions.shared.SaveEditUIAction + fr.ird.observe.application.swing.ui.content.table.impl.longline.BaitsCompositionUI + fr.ird.observe.application.swing.ui.content.table.impl.longline.BaitsCompositionUIModel + fr.ird.observe.application.swing.ui.content.table.impl.longline.BranchlinesCompositionUI + fr.ird.observe.application.swing.ui.content.table.impl.longline.BranchlinesCompositionUIModel + fr.ird.observe.application.swing.ui.content.table.impl.longline.FloatlinesCompositionUI + fr.ird.observe.application.swing.ui.content.table.impl.longline.FloatlinesCompositionUIModel + fr.ird.observe.application.swing.ui.content.table.impl.longline.HooksCompositionUI + fr.ird.observe.application.swing.ui.content.table.impl.longline.HooksCompositionUIModel + + org.nuiton.jaxx.widgets.select.FilterableDoubleList + + java.awt.Dimension + javax.swing.JLabel + java.util.Collection + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + static org.nuiton.i18n.I18n.t + </import> + + <style source="../../Common.jcss"/> + + <!-- handler --> + <LonglineGlobalCompositionUIHandler id='handler'/> + + <!-- model --> + <LonglineGlobalCompositionUIModel id='model'/> + + <!-- edit bean --> + <SetLonglineGlobalCompositionDto id='bean'/> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' beanClass='fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto' + errorTableModel='{getErrorTableModel()}' context='ui-update-globalComposition'> + </BeanValidator> + + <!-- formulaire --> + <JPanel id="body" layout='{new BorderLayout()}'> + + <Table insets="0" fill="both" constraints='BorderLayout.CENTER'> + <row> + <cell anchor="north"> + <JTabbedPane id='fishingOperationTabPane'> + + <!-- floatlinesComposition --> + <tab id='floatlinesCompositionTab'> + <JPanel id="floatlinesCompositionPanel" layout='{new BorderLayout()}'> + <FloatlinesCompositionUI id="floatlinesCompositionUI" + constructorParams="ObserveSwingApplicationContext.get().getMainUI()"/> + </JPanel> + </tab> + + <!-- branchlinesComposition --> + <tab id='branchlinesCompositionTab'> + <JPanel id="branchlinesCompositionPanel" layout='{new BorderLayout()}'> + <BranchlinesCompositionUI id="branchlinesCompositionUI" + constructorParams="ObserveSwingApplicationContext.get().getMainUI()"/> + </JPanel> + </tab> + + <!-- hooksComposition --> + <tab id='hooksCompositionTab'> + <JPanel id="hooksCompositionPanel" layout='{new BorderLayout()}'> + <HooksCompositionUI id="hooksCompositionUI" + constructorParams="ObserveSwingApplicationContext.get().getMainUI()"/> + </JPanel> + </tab> + + <!-- baitsComposition --> + <tab id='baitsCompositionTab'> + <JPanel id="baitsCompositionPanel" layout='{new BorderLayout()}'> + <BaitsCompositionUI id="baitsCompositionUI" + constructorParams="ObserveSwingApplicationContext.get().getMainUI()"/> + </JPanel> + </tab> + + <tab id='mitigationTypeTab'> + + <!-- mitigationType --> + <JPanel layout='{new BorderLayout()}'> + <Table fill='both' constraints='BorderLayout.NORTH'> + <row> + <cell weighty="1" weightx="1"> + <FilterableDoubleList id='mitigationType' genericType='ReferentialReference<MitigationTypeDto>' _entityClass='MitigationTypeDto.class'/> + </cell> + </row> + </Table> + </JPanel> + + </tab> + + </JTabbedPane> + </cell> + </row> + + <row> + <cell fill="both" weighty="1" weightx="1"> + <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2'/> + </JScrollPane> + </cell> + </row> + + </Table> + </JPanel> + + <!-- actions --> + <Table id="actions" fill='both' weightx='1' insets='0'> + <row> + <cell weightx="0.5"> + <JButton id='reset'/> + </cell> + <cell weightx="0.5"> + <JButton id='save'/> + </cell> + </row> + </Table> + + <FloatlinesCompositionUIModel id="floatlinesCompositionModel" initializer="floatlinesCompositionUI.getModel()"/> + <BranchlinesCompositionUIModel id="branchlinesCompositionModel" initializer="branchlinesCompositionUI.getModel()"/> + <HooksCompositionUIModel id="hooksCompositionModel" initializer="hooksCompositionUI.getModel()"/> + <BaitsCompositionUIModel id="baitsCompositionModel" initializer="baitsCompositionUI.getModel()"/> + +</fr.ird.observe.application.swing.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineGlobalCompositionUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineGlobalCompositionUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineGlobalCompositionUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineGlobalCompositionUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineGlobalCompositionUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineGlobalCompositionUIHandler.java new file mode 100644 index 0000000..a96cf99 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineGlobalCompositionUIHandler.java @@ -0,0 +1,248 @@ +package fr.ird.observe.application.swing.ui.content.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.longline.ActivityLonglineDto; +import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto; +import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDtos; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.service.longline.SetLonglineGlobalCompositionService; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.ContentUIHandler; +import fr.ird.observe.application.swing.ui.content.table.impl.longline.BaitsCompositionUI; +import fr.ird.observe.application.swing.ui.content.table.impl.longline.BaitsCompositionUIModel; +import fr.ird.observe.application.swing.ui.content.table.impl.longline.BranchlinesCompositionUI; +import fr.ird.observe.application.swing.ui.content.table.impl.longline.BranchlinesCompositionUIModel; +import fr.ird.observe.application.swing.ui.content.table.impl.longline.FloatlinesCompositionUI; +import fr.ird.observe.application.swing.ui.content.table.impl.longline.FloatlinesCompositionUIModel; +import fr.ird.observe.application.swing.ui.content.table.impl.longline.HooksCompositionUI; +import fr.ird.observe.application.swing.ui.content.table.impl.longline.HooksCompositionUIModel; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.validator.NuitonValidatorScope; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 12/5/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.8 + */ +public class LonglineGlobalCompositionUIHandler extends ContentUIHandler<SetLonglineGlobalCompositionDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(LonglineGlobalCompositionUIHandler.class); + + public LonglineGlobalCompositionUIHandler(LonglineGlobalCompositionUI ui) { + super(ui, DataContextType.ActivityLongline, DataContextType.SetLongline); + } + + @Override + public LonglineGlobalCompositionUI getUi() { + return (LonglineGlobalCompositionUI) super.getUi(); + } + + @Override + protected boolean computeCanWrite(ObserveSwingDataSource source) { + return source.canWriteData(); + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + String activityId = dataContext.getSelectedActivityLonglineId(); + + if (getOpenDataManager().isOpenActivityLongline(activityId)) { + + // l'activité est ouverte, mode édition + return ContentMode.UPDATE; + } + + // l'activité n'est pas ouverte, mode lecture + addMessage(getUi(), + NuitonValidatorScope.INFO, + getEntityLabel(ActivityLonglineDto.class), + t("observe.storage.activityLongline.message.not.open")); + return ContentMode.READ; + } + + @Override + public void initUI() { + super.initUI(); + { + // init floatlinesComposition tab + FloatlinesCompositionUI compositionUI = getUi().getFloatlinesCompositionUI(); + compositionUI.init(); + getUi().getFloatlinesCompositionPanel().remove(compositionUI); + getUi().getFloatlinesCompositionPanel().add(compositionUI.getBody()); + } + + { + // init branchlinesComposition tab + BranchlinesCompositionUI compositionUI = getUi().getBranchlinesCompositionUI(); + compositionUI.init(); + getUi().getBranchlinesCompositionPanel().remove(compositionUI); + getUi().getBranchlinesCompositionPanel().add(compositionUI.getBody()); + } + + { + // init hooksComposition tab + HooksCompositionUI compositionUI = getUi().getHooksCompositionUI(); + compositionUI.init(); + getUi().getHooksCompositionPanel().remove(compositionUI); + getUi().getHooksCompositionPanel().add(compositionUI.getBody()); + } + + { + // init baitsComposition tab + BaitsCompositionUI compositionUI = getUi().getBaitsCompositionUI(); + compositionUI.init(); + getUi().getBaitsCompositionPanel().remove(compositionUI); + getUi().getBaitsCompositionPanel().add(compositionUI.getBody()); + } + + } + + @Override + public void openUI() { + super.openUI(); + + String activityId = getSelectedParentId(); + String setId = getSelectedId(); + + if (log.isInfoEnabled()) { + log.info("activityId = " + activityId); + log.info("setId = " + setId); + } + ContentMode mode = computeContentMode(); + + // update mode + Form<SetLonglineGlobalCompositionDto> form = getSetLonglineGlobalCompositionService().loadForm(setId); + + loadReferentialReferenceSetsInModel(form); + + getModel().setForm(form); + SetLonglineGlobalCompositionDtos.copySetLonglineGlobalCompositionDto(form.getObject(), getBean()); + + // utilisation du mode requis + setContentMode(mode); + + if (mode != ContentMode.READ) { + getUi().startEdit(null); + } + + { + // open floatlinesComposition tab + FloatlinesCompositionUIModel floatlinesCompositionModel = getUi().getFloatlinesCompositionModel(); + floatlinesCompositionModel.setReferentialReferenceSets(getModel().getReferentialReferenceSets()); + floatlinesCompositionModel.setForm(form); + SetLonglineGlobalCompositionDtos.copySetLonglineGlobalCompositionDto(form.getObject(), floatlinesCompositionModel.getBean()); + + FloatlinesCompositionUI compositionUI = getUi().getFloatlinesCompositionUI(); + compositionUI.open(); + + } + + { + // open branchlinesComposition tab + BranchlinesCompositionUIModel branchlinesCompositionModel = getUi().getBranchlinesCompositionModel(); + branchlinesCompositionModel.setReferentialReferenceSets(getModel().getReferentialReferenceSets()); + branchlinesCompositionModel.setForm(form); + SetLonglineGlobalCompositionDtos.copySetLonglineGlobalCompositionDto(form.getObject(), branchlinesCompositionModel.getBean()); + + BranchlinesCompositionUI compositionUI = getUi().getBranchlinesCompositionUI(); + compositionUI.open(); + + } + + { + // open hooksComposition tab + HooksCompositionUIModel hooksCompositionModel = getUi().getHooksCompositionModel(); + hooksCompositionModel.setReferentialReferenceSets(getModel().getReferentialReferenceSets()); + hooksCompositionModel.setForm(form); + SetLonglineGlobalCompositionDtos.copySetLonglineGlobalCompositionDto(form.getObject(), hooksCompositionModel.getBean()); + + HooksCompositionUI compositionUI = getUi().getHooksCompositionUI(); + compositionUI.open(); + + } + + { + // open baitsComposition tab + BaitsCompositionUIModel baitsCompositionModel = getUi().getBaitsCompositionModel(); + baitsCompositionModel.setReferentialReferenceSets(getModel().getReferentialReferenceSets()); + baitsCompositionModel.setForm(form); + SetLonglineGlobalCompositionDtos.copySetLonglineGlobalCompositionDto(form.getObject(), baitsCompositionModel.getBean()); + + BaitsCompositionUI compositionUI = getUi().getBaitsCompositionUI(); + compositionUI.open(); + + } + + } + + @Override + public void startEditUI(String... binding) { + LonglineGlobalCompositionUIModel model = (LonglineGlobalCompositionUIModel) getModel(); + addInfoMessage(t("observe.content.longlineGlobalComposition.message.updating")); + + super.startEditUI(LonglineGlobalCompositionUI.BINDING_COMMENT2_TEXT); + model.setModified(false); + } + + @Override + protected boolean doSave(SetLonglineGlobalCompositionDto bean) throws Exception { + + bean.setFloatlinesComposition(getUi().getFloatlinesCompositionModel().getBean().getFloatlinesComposition()); + bean.setBranchlinesComposition(getUi().getBranchlinesCompositionModel().getBean().getBranchlinesComposition()); + bean.setHooksComposition(getUi().getHooksCompositionModel().getBean().getHooksComposition()); + bean.setBaitsComposition(getUi().getBaitsCompositionModel().getBean().getBaitsComposition()); + + SaveResultDto saveResult = getSetLonglineGlobalCompositionService().save(bean); + saveResult.toDto(bean); + + return true; + } + + @Override + protected void afterSave(boolean refresh) { + super.afterSave(refresh); + + getUi().getFloatlinesCompositionUI().getHandler().afterSave(refresh); + getUi().getBranchlinesCompositionUI().getHandler().afterSave(refresh); + getUi().getHooksCompositionUI().getHandler().afterSave(refresh); + getUi().getBaitsCompositionUI().getHandler().afterSave(refresh); + } + + protected SetLonglineGlobalCompositionService getSetLonglineGlobalCompositionService() { + + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newSetLonglineGlobalCompositionService(); + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineGlobalCompositionUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineGlobalCompositionUIModel.java new file mode 100644 index 0000000..88b7350 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineGlobalCompositionUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; + +/** + * Created on 12/5/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.8 + */ +public class LonglineGlobalCompositionUIModel extends ContentUIModel<SetLonglineGlobalCompositionDto> { + + private static final long serialVersionUID = 1L; + + public LonglineGlobalCompositionUIModel() { + super(SetLonglineGlobalCompositionDto.class); + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/SectionTemplatesTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/SectionTemplatesTableModel.java new file mode 100644 index 0000000..b346181 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/SectionTemplatesTableModel.java @@ -0,0 +1,158 @@ +package fr.ird.observe.application.swing.ui.content.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.longline.SectionTemplate; +import fr.ird.observe.application.swing.ui.util.table.EditableTableModelSupport; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.HashSet; +import java.util.Set; + +/** + * Created on 12/11/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.10 + */ +public class SectionTemplatesTableModel extends EditableTableModelSupport<SectionTemplate> { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(SectionTemplatesTableModel.class); + + public SectionTemplatesTableModel() { + super(true); + } + + @Override + public boolean isRowNotEmpty(SectionTemplate row) { + return !(StringUtils.isBlank(row.getId()) && StringUtils.isBlank(row.getFloatlineLengths())); + } + + @Override + public boolean isRowValid(SectionTemplate row) { + return StringUtils.isNotBlank(row.getId()) && + StringUtils.isNotBlank(row.getFloatlineLengths()) && + row.isFloatlineLengthsValid(); + } + + @Override + protected SectionTemplate createNewRow() { + return new SectionTemplate(); + } + + @Override + public int getColumnCount() { + return 2; + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + SectionTemplate measure = data.get(rowIndex); + Object result; + + switch (columnIndex) { + case 0: + + result = measure.getId(); + break; + + case 1: + + result = measure.getFloatlineLengths(); + break; + + default: + throw new IllegalStateException("Can't come here"); + } + + return result; + } + + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + SectionTemplate measure = data.get(rowIndex); + + switch (columnIndex) { + case 0: + + measure.setId((String) aValue); + break; + + case 1: + + measure.setFloatlineLengths((String) aValue); + break; + + default: + throw new IllegalStateException("Can't come here"); + } + + setModified(true); + + } + + @Override + protected boolean computeValidState() { + + boolean newValidState = super.computeValidState(); + if (newValidState) { + + // check that we are using unique ids + Set<String> ids = new HashSet<>(); + for (SectionTemplate sectionTemplate : data) { + + boolean add = ids.add(sectionTemplate.getId()); + if (!add) { + + if (log.isWarnEnabled()) { + log.warn("Template identifiants (" + sectionTemplate.getId() + ") are not unique."); + } + newValidState = false; + break; + } + + } + + } + return newValidState; + + } + + @Override + protected boolean isCanCreateNewRow(int rowIndex) { + + boolean canCreateNewRow = super.isCanCreateNewRow(rowIndex); + if (canCreateNewRow) { + + // add a new row if and only if all rows are valid + canCreateNewRow = computeValidState(); + } + return canCreateNewRow; + + } +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/SectionsTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/SectionsTableModel.java new file mode 100644 index 0000000..6d38221 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/SectionsTableModel.java @@ -0,0 +1,180 @@ +package fr.ird.observe.application.swing.ui.content.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.longline.SectionTemplate; +import fr.ird.observe.services.dto.longline.SectionWithTemplate; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Created on 12/11/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.10 + */ +public class SectionsTableModel extends LonglineCompositionTableModelSupport<SectionWithTemplate> { + + public static final String TEMPLATE_PROPERTY = "template"; + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(SectionsTableModel.class); + + public SectionsTableModel(LonglineDetailCompositionUIModel model) { + super(model); + } + + @Override + protected SectionWithTemplate createNewRow() { + return new SectionWithTemplate(); + } + + @Override + public int getColumnCount() { + return 3; + } + + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + + boolean result; + + switch (columnIndex) { + + case 0: + + // can never edit setting id + result = false; + break; + + case 1: + + // can edit hauling id if and only if set has hauling breaks + result = !isGenerateHaulingIds(); + break; + + case 2: + + // can change template if in generate mode + result = isCanGenerate(); + break; + + default: + throw new IllegalStateException("Can't come here"); + + } + + return result; + + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + SectionWithTemplate row = data.get(rowIndex); + Object result; + + switch (columnIndex) { + case 0: + + result = row.getSettingIdentifier(); + break; + + case 1: + + result = row.getHaulingIdentifier(); + break; + + case 2: + + result = row.getSectionTemplate(); + break; + + default: + throw new IllegalStateException("Can't come here"); + } + + return result; + } + + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + SectionWithTemplate row = data.get(rowIndex); + + switch (columnIndex) { + case 0: + + row.setSettingIdentifier((Integer) aValue); + setModified(true); + break; + + case 1: + + row.setHaulingIdentifier((Integer) aValue); + setModified(true); + break; + + case 2: + + SectionTemplate sectionTemplate = (SectionTemplate) aValue; + + boolean changeTemplate = true; + + if (sectionTemplate != null) { + + // check if can use this template + int basketsCount = row.sizeBasket(); + boolean compiliantWithBasketCount = sectionTemplate.isCompiliantWithBasketCount(basketsCount); + + if (!compiliantWithBasketCount) { + + // We can't use this value + if (log.isWarnEnabled()) { + log.warn("sectionTemplate " + sectionTemplate + " is not compliant with basketCount: " + basketsCount); + } + //TODO Send user a message + + changeTemplate = false; + + } + + } + + if (changeTemplate) { + + SectionTemplate previousSectionTemplate = row.getSectionTemplate(); + row.setSectionTemplate(sectionTemplate); + firePropertyChange(TEMPLATE_PROPERTY, previousSectionTemplate, sectionTemplate); + + } + + break; + + default: + throw new IllegalStateException("Can't come here"); + } + + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/SetLonglineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/SetLonglineUI.jaxx new file mode 100644 index 0000000..62fc42c --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/SetLonglineUI.jaxx @@ -0,0 +1,428 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ContentUI superGenericType='SetLonglineDto' contentTitle='{n("observe.content.setLongline.title")}'> + + <import> + fr.ird.observe.services.dto.CommentableDto + fr.ird.observe.services.dto.longline.SetLonglineDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.longline.SettingShapeDto + fr.ird.observe.services.dto.referential.longline.LineTypeDto + fr.ird.observe.services.dto.referential.longline.LightsticksTypeDto + fr.ird.observe.services.dto.referential.longline.LightsticksColorDto + + fr.ird.observe.application.swing.ui.actions.shared.CancelCreateUIAction + fr.ird.observe.application.swing.ui.actions.shared.DeleteDataUIAction + fr.ird.observe.application.swing.ui.actions.shared.ResetEditUIAction + fr.ird.observe.application.swing.ui.actions.shared.SaveEditUIAction + fr.ird.observe.application.swing.ui.content.ContentUIModel + fr.ird.observe.application.swing.ui.util.BooleanEditor + + jaxx.runtime.swing.editor.NumberEditor + org.nuiton.jaxx.widgets.datetime.TimeEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + org.nuiton.jaxx.widgets.gis.absolute.CoordinatesEditor + org.nuiton.jaxx.widgets.datetime.DateTimeEditor + + org.jdesktop.swingx.JXDatePicker + + org.apache.commons.lang3.BooleanUtils + + java.awt.Dimension + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <style source="../../Common.jcss"/> + + <!-- handler --> + <SetLonglineUIHandler id='handler'/> + + <!-- model --> + <SetLonglineUIModel id='model'/> + + <!-- edit bean --> + <SetLonglineDto id='bean'/> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' context='ui-update' + beanClass='fr.ird.observe.services.dto.longline.SetLonglineDto' + errorTableModel='{getErrorTableModel()}'> + + <field name='settingStartLongitude' component='settingStartCoordinates'/> + <field name='settingStartLatitude' component='settingStartCoordinates'/> + + <field name='settingEndLongitude' component='settingEndCoordinates'/> + <field name='settingEndLatitude' component='settingEndCoordinates'/> + + <field name='haulingStartLongitude' component='haulingStartCoordinates'/> + <field name='haulingStartLatitude' component='haulingStartCoordinates'/> + + <field name='haulingEndLongitude' component='haulingEndCoordinates'/> + <field name='haulingEndLatitude' component='haulingEndCoordinates'/> + + </BeanValidator> + + <!-- formulaire --> + <JPanel id="body" layout='{new BorderLayout()}'> + + <Table insets="0" fill="both" constraints='BorderLayout.CENTER'> + <row> + <cell anchor="north"> + <JTabbedPane id='fishingOperationTabPane'> + <tab id='settingTab'> + <JPanel layout='{new BorderLayout()}'> + <Table fill='both' constraints='BorderLayout.NORTH'> + + <!-- homeId --> + <row> + <cell anchor='west'> + <JLabel id='homeIdLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel layout='{new BorderLayout()}'> + <JToolBar id='homeIdToolbar' constraints='BorderLayout.WEST'> + <JButton id='resetHomeId' constraints='BorderLayout.WEST' styleClass='resetButton'/> + </JToolBar> + <JTextField id='homeId' constraints='BorderLayout.CENTER'/> + </JPanel> + </cell> + </row> + <!-- number --> + <row> + <cell anchor='west'> + <JLabel id='numberLabel'/> + </cell> + <cell columns="2" weightx="1" fill="both"> + <NumberEditor id='number' constructorParams='this'/> + </cell> + </row> + + <row> + <cell columns="2"> + <Table insets="0" fill='both'> + <!-- setting start timeStamp --> + <row> + <cell weightx="1"> + <DateTimeEditor id='settingStartTimeStamp' constructorParams='this'/> + </cell> + </row> + + <!-- setting start position --> + <row> + <cell anchor="east"> + <CoordinatesEditor id='settingStartCoordinates' constructorParams='this'/> + </cell> + </row> + + <!-- setting end timeStamp --> + <row> + <cell> + <DateTimeEditor id='settingEndTimeStamp' constructorParams='this'/> + </cell> + </row> + + <!-- setting end position --> + <row> + <cell anchor="east"> + <CoordinatesEditor id='settingEndCoordinates' constructorParams='this'/> + </cell> + </row> + </Table> + </cell> + </row> + + </Table> + </JPanel> + + </tab> + + <tab id='settingCaracteristicsTab'> + <Table fill='both'> + + <!-- setting shape --> + <row> + <cell anchor='west'> + <JLabel id='settingShapeLabel'/> + </cell> + <cell columns="2" fill="both"> + <BeanComboBox id='settingShape' constructorParams='this' genericType='ReferentialReference<SettingShapeDto>' _entityClass='SettingShapeDto.class'/> + </cell> + </row> + <!-- line type --> + <row> + <cell anchor='west'> + <JLabel id='lineTypeLabel'/> + </cell> + <cell columns="2"> + <BeanComboBox id='lineType' constructorParams='this' genericType='ReferentialReference<LineTypeDto>' _entityClass='LineTypeDto.class'/> + </cell> + </row> + + <!-- lightsticks type --> + <row> + <cell anchor='west'> + <JLabel id='lightsticksTypeLabel'/> + </cell> + <cell columns="2"> + <BeanComboBox id='lightsticksType' constructorParams='this' genericType='ReferentialReference<LightsticksTypeDto>' _entityClass='LightsticksTypeDto.class'/> + </cell> + </row> + + <!-- lightsticks color --> + <row> + <cell anchor='west'> + <JLabel id='lightsticksColorLabel'/> + </cell> + <cell columns="2"> + <BeanComboBox id='lightsticksColor' constructorParams='this' genericType='ReferentialReference<LightsticksColorDto>' _entityClass='LightsticksColorDto.class'/> + </cell> + </row> + + <!-- setting vessel speed --> + <row> + <cell> + <JLabel id='settingVesselSpeedLabel'/> + </cell> + <cell columns="2"> + <NumberEditor id='settingVesselSpeed' constructorParams='this'/> + </cell> + </row> + + <!-- max depth targeted (m) --> + <row> + <cell> + <JLabel id='maxDepthTargetedLabel'/> + </cell> + <cell columns="2"> + <NumberEditor id='maxDepthTargeted' constructorParams='this'/> + </cell> + </row> + + <!-- shooter used --> + <!-- shooter speed --> + <row> + <cell anchor="east"> + <JCheckBox id='shooterUsed'/> + </cell> + <cell> + <JLabel id='shooterSpeedLabel'/> + </cell> + <cell> + <NumberEditor id='shooterSpeed' constructorParams='this'/> + </cell> + </row> + + <!-- weighted swivels --> + <!-- swivels weights --> + <row> + <cell anchor="east"> + <JCheckBox id='weightedSwivel'/> + </cell> + <cell anchor="west"> + <JLabel id='swivelWeightLabel'/> + </cell> + <cell> + <NumberEditor id='swivelWeight' constructorParams='this'/> + </cell> + </row> + + <!-- weighted snaps --> + <!-- snap weights --> + <row> + <cell anchor='east'> + <JCheckBox id='weightedSnap'/> + </cell> + <cell> + <JLabel id='snapWeightLabel'/> + </cell> + <cell> + <NumberEditor id='snapWeight' constructorParams='this'/> + </cell> + </row> + + <!-- monitored --> + <!-- time between hooks --> + <row> + <cell anchor='east'> + <JCheckBox id='monitored'/> + </cell> + <cell anchor='west'> + <JLabel id='timeBetweenHooksLabel'/> + </cell> + <cell fill='both' weightx="1"> + <NumberEditor id='timeBetweenHooks' constructorParams='this'/> + </cell> + </row> + + <row> + <cell columns="3" fill="both"> + <Table insets="0"> + + <!-- basket per section count --> + <!-- total section count --> + <row> + <cell anchor='west'> + <JLabel id='basketsPerSectionCountLabel'/> + </cell> + <cell fill='both' weightx="1"> + <NumberEditor id='basketsPerSectionCount' constructorParams='this'/> + </cell> + <cell anchor='west'> + <JLabel id='totalSectionsCountLabel'/> + </cell> + <cell fill='both' weightx="1"> + <NumberEditor id='totalSectionsCount' constructorParams='this'/> + </cell> + </row> + + <!-- ligtsticks per basket count --> + <!-- total basket count --> + <row> + <cell anchor='west'> + <JLabel id='lightsticksPerBasketCountLabel'/> + </cell> + <cell fill='both' weightx="1"> + <NumberEditor id='lightsticksPerBasketCount' constructorParams='this'/> + </cell> + <cell anchor='west'> + <JLabel id='totalBasketsCountLabel'/> + </cell> + <cell fill='both' weightx="1"> + <NumberEditor id='totalBasketsCount' constructorParams='this'/> + </cell> + </row> + + <!-- branchlines per basket count --> + <!-- total hooks count --> + <row> + <cell anchor='west'> + <JLabel id='branchlinesPerBasketCountLabel'/> + </cell> + <cell fill='both' weightx="1"> + <NumberEditor id='branchlinesPerBasketCount' constructorParams='this'/> + </cell> + <cell anchor='west'> + <JLabel id='totalHooksCountLabel'/> + </cell> + <cell fill='both' weightx="1"> + <NumberEditor id='totalHooksCount' constructorParams='this'/> + </cell> + </row> + </Table> + </cell> + </row> + + </Table> + </tab> + + <tab id='haulingTab'> + + <JPanel layout='{new BorderLayout()}'> + <Table fill='both' constraints='BorderLayout.NORTH'> + + <!-- hauling same direction as setting --> + <row> + <cell> + <JLabel id='haulingDirectionSameAsSettingLabel'/> + </cell> + <cell> + <BooleanEditor id='haulingDirectionSameAsSetting'/> + </cell> + </row> + + <!-- hauling start timeStamp --> + <row> + <cell columns="2" weightx="1"> + <DateTimeEditor id='haulingStartTimeStamp' constructorParams='this'/> + </cell> + </row> + + <!-- hauling start position --> + <row> + <cell columns="2" anchor='east'> + <CoordinatesEditor id='haulingStartCoordinates' constructorParams='this'/> + </cell> + </row> + + <!-- hauling end timeStamp --> + <row> + <cell columns="2" weightx="1"> + <DateTimeEditor id='haulingEndTimeStamp' constructorParams='this'/> + </cell> + </row> + + <!-- hauling end position --> + <row> + <cell columns="2" anchor='east'> + <CoordinatesEditor id='haulingEndCoordinates' constructorParams='this'/> + </cell> + </row> + + <row> + <!-- hauling breaks --> + <cell anchor="west"> + <JLabel id='haulingBreaksLabel'/> + </cell> + <cell weightx="1" fill="both"> + <NumberEditor id='haulingBreaks' constructorParams='this'/> + </cell> + </row> + </Table> + </JPanel> + </tab> + </JTabbedPane> + </cell> + </row> + + <row> + <cell fill="both" weighty="1" weightx="1"> + <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2'/> + </JScrollPane> + </cell> + </row> + + </Table> + </JPanel> + + <!-- actions --> + <Table id="actions" fill='both' weightx='1' insets='0'> + <row> + <cell weightx="0.5" fill="both"> + <JButton id='cancel'/> + </cell> + <cell weightx="0.5"> + <JButton id='reset'/> + </cell> + <cell weightx="0.5"> + <JButton id='save'/> + </cell> + <cell weightx="0.5"> + <JButton id='delete'/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/SetLonglineUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/SetLonglineUI.jcss new file mode 100644 index 0000000..b67e2df --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/SetLonglineUI.jcss @@ -0,0 +1,398 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#model { + editable:true; + modified:{validator.isChanged()}; + valid:{validator.isValid()}; + enabled:{!model.isReadingMode()}; +} + +/* ***************************************************************************** */ +/* SETTING TAB **************************************************************** */ +/* ***************************************************************************** */ + +#settingTab { + title:{t("observe.content.setLongline.tab.setting")}; + icon:{handler.getErrorIconIfFalse(model.isSettingTabValid())}; +} + +#homeIdLabel { + text:"observe.content.setLongline.homeId"; + labelFor:{homeId}; +} + +#homeId { + text: {getStringValue(bean.getHomeId())}; + _propertyName: {SetLonglineDto.PROPERTY_HOME_ID}; + _validatorLabel:{t("observe.content.setLongline.homeId")}; +} + +#resetHomeId { + _resetPropertyName: {SetLonglineDto.PROPERTY_HOME_ID}; + toolTipText:"observe.content.setLongline.action.reset.homeId.tip"; +} + +#numberLabel { + text:"observe.content.setLongline.number"; + labelFor:{number}; +} + +#number { + property: {SetLonglineDto.PROPERTY_NUMBER}; + model:{bean.getNumber()}; + useFloat:false; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.setLongline.number")}; +} + +#settingStartTimeStamp { + label:{t("observe.content.setLongline.settingStartTimeStamp")}; + date:{bean.getSettingStartTimeStamp()}; + propertyDate: {SetLonglineDto.PROPERTY_SETTING_START_TIME_STAMP}; + _validatorLabel:{t("observe.content.setLongline.settingStartTimeStamp")}; +} + +#settingStartCoordinatesLabel { + text:"observe.content.setLongline.settingStartCoordinates"; +} + +#settingStartCoordinates { + propertyLatitude:{SetLonglineDto.PROPERTY_SETTING_START_LATITUDE}; + propertyLongitude:{SetLonglineDto.PROPERTY_SETTING_START_LONGITUDE}; + latitude:{bean.getSettingStartLatitude()}; + longitude:{bean.getSettingStartLongitude()}; + _validatorLabel:{t("observe.content.setLongline.settingStartCoordinates")}; +} + +#settingEndTimeStamp { + label:{t("observe.content.setLongline.settingEndTimeStamp")}; + date:{bean.getSettingEndTimeStamp()}; + propertyDate: {SetLonglineDto.PROPERTY_SETTING_END_TIME_STAMP}; + _validatorLabel:{t("observe.content.setLongline.settingEndTimeStamp")}; +} + +#settingEndCoordinatesLabel { + text:"observe.content.setLongline.settingEndCoordinates"; +} + +#settingEndCoordinates { + propertyLatitude:{SetLonglineDto.PROPERTY_SETTING_END_LATITUDE}; + propertyLongitude:{SetLonglineDto.PROPERTY_SETTING_END_LONGITUDE}; + latitude:{bean.getSettingEndLatitude()}; + longitude:{bean.getSettingEndLongitude()}; + _validatorLabel:{t("observe.content.setLongline.settingEndCoordinates")}; +} + +/* ***************************************************************************** */ +/* SETTING CARACTERISTICS TAB ************************************************* */ +/* ***************************************************************************** */ + +#settingCaracteristicsTab { + title:{t("observe.content.setLongline.tab.settingCaracteristics")}; + icon:{handler.getErrorIconIfFalse(model.isSettingCaracteristicsTabValid())}; +} + +#settingVesselSpeedLabel { + text:"observe.content.setLongline.settingVesselSpeed"; + labelFor:{settingVesselSpeed}; +} + +#settingVesselSpeed { + property:{SetLonglineDto.PROPERTY_SETTING_VESSEL_SPEED}; + model:{bean.getSettingVesselSpeed()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL3_PATTERN}; + _validatorLabel:{t("observe.content.setLongline.settingVesselSpeed")}; +} + +#shooterUsed { + text:"observe.content.setLongline.shooterUsed"; + horizontalTextPosition:{JCheckBox.LEFT}; + _propertyName:{SetLonglineDto.PROPERTY_SHOOTER_USED}; + selected:{BooleanUtils.isTrue(bean.getShooterUsed())}; +} + +#shooterSpeedLabel { + text:"observe.content.setLongline.shooterSpeed"; + labelFor:{shooterSpeed}; +} + +#shooterSpeed { + enabled:{BooleanUtils.isTrue(bean.getShooterUsed())}; + property:{SetLonglineDto.PROPERTY_SHOOTER_SPEED}; + model:{bean.getShooterSpeed()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL3_PATTERN}; + _validatorLabel:{t("observe.content.setLongline.shooterSpeed")}; +} + +#settingShapeLabel { + text:"observe.content.setLongline.settingShape"; + labelFor:{settingShape}; +} + +#settingShape { + property:{SetLonglineDto.PROPERTY_SETTING_SHAPE}; + selectedItem:{bean.getSettingShape()}; + _validatorLabel:{t("observe.content.setLongline.settingShape")}; +} + +#weightedSwivel { + horizontalTextPosition:{JCheckBox.LEFT}; + text:"observe.content.setLongline.weightedSwivel"; + _propertyName:{SetLonglineDto.PROPERTY_WEIGHTED_SWIVEL}; + selected:{BooleanUtils.isTrue(bean.getWeightedSwivel())}; + _validatorLabel:{t("observe.content.setLongline.weightedSwivel")}; +} + +#swivelWeightLabel { + text:"observe.content.setLongline.swivelWeight"; + labelFor:{swivelWeight}; +} + +#swivelWeight { + enabled:{BooleanUtils.isTrue(bean.getWeightedSwivel())}; + property:{SetLonglineDto.PROPERTY_SWIVEL_WEIGHT}; + model:{bean.getSwivelWeight()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL3_PATTERN}; + _validatorLabel:{t("observe.content.setLongline.swivelWeight")}; +} + +#weightedSnap { + horizontalTextPosition:{JCheckBox.LEFT}; + text:"observe.content.setLongline.weightedSnap"; + _propertyName:{SetLonglineDto.PROPERTY_WEIGHTED_SNAP}; + selected:{BooleanUtils.isTrue(bean.getWeightedSnap())}; + _validatorLabel:{t("observe.content.setLongline.weightedSnap")}; +} + +#snapWeightLabel { + text:"observe.content.setLongline.snapWeight"; + labelFor:{snapWeight}; +} + +#snapWeight { + enabled:{BooleanUtils.isTrue(bean.getWeightedSnap())}; + property:{SetLonglineDto.PROPERTY_SNAP_WEIGHT}; + model:{bean.getSnapWeight()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL3_PATTERN}; + _validatorLabel:{t("observe.content.setLongline.snapWeight")}; +} + +#lineTypeLabel { + text:"observe.content.setLongline.lineType"; + labelFor:{lineType}; +} + +#lineType { + property:{SetLonglineDto.PROPERTY_LINE_TYPE}; + selectedItem:{bean.getLineType()}; + _validatorLabel:{t("observe.content.setLongline.lineType")}; +} + +#maxDepthTargetedLabel { + text:"observe.content.setLongline.maxDepthTargeted"; + labelFor:{maxDepthTargeted}; +} + +#maxDepthTargeted { + property:{SetLonglineDto.PROPERTY_MAX_DEPTH_TARGETED}; + model:{bean.getMaxDepthTargeted()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.setLongline.maxDepthTargeted")}; +} + +#monitored { + horizontalTextPosition:{JCheckBox.LEFT}; + text:"observe.content.setLongline.monitored"; + _propertyName:{SetLonglineDto.PROPERTY_MONITORED}; + selected:{BooleanUtils.isTrue(bean.getMonitored())}; + _validatorLabel:{t("observe.content.setLongline.monitored")}; +} + +#lightsticksTypeLabel { + text:"observe.content.setLongline.lightsticksType"; + labelFor:{lightsticksType}; +} + +#lightsticksType { + property:{SetLonglineDto.PROPERTY_LIGHTSTICKS_TYPE}; + selectedItem:{bean.getLightsticksType()}; + _validatorLabel:{t("observe.content.setLongline.lightsticksType")}; +} + +#lightsticksColorLabel { + text:"observe.content.setLongline.lightsticksColor"; + labelFor:{lightsticksColor}; +} + +#lightsticksColor { + property:{SetLonglineDto.PROPERTY_LIGHTSTICKS_COLOR}; + selectedItem:{bean.getLightsticksColor()}; + _validatorLabel:{t("observe.content.setLongline.lightsticksColor")}; +} + +#timeBetweenHooksLabel { + text:"observe.content.setLongline.timeBetweenHooks"; + labelFor:{timeBetweenHooks}; +} + +#timeBetweenHooks { + property:{SetLonglineDto.PROPERTY_TIME_BETWEEN_HOOKS}; + model:{bean.getTimeBetweenHooks()}; + modelType:{Long.class}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.LONG_10_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.setLongline.timeBetweenHooks")}; +} + +#lightsticksPerBasketCountLabel { + text:"observe.content.setLongline.lightsticksPerBasketCount"; + labelFor:{lightsticksPerBasketCount}; +} + +#lightsticksPerBasketCount { + property:{SetLonglineDto.PROPERTY_LIGHTSTICKS_PER_BASKET_COUNT}; + model:{bean.getLightsticksPerBasketCount()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.setLongline.lightsticksPerBasketCount")}; +} + +#basketsPerSectionCountLabel { + text:"observe.content.setLongline.basketsPerSectionCount"; + labelFor:{basketsPerSectionCount}; +} + +#basketsPerSectionCount { + property:{SetLonglineDto.PROPERTY_BASKETS_PER_SECTION_COUNT}; + model:{bean.getBasketsPerSectionCount()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.setLongline.basketsPerSectionCount")}; +} + +#totalBasketsCountLabel { + text:"observe.content.setLongline.totalBasketsCount"; + labelFor:{totalBasketsCount}; +} + +#totalBasketsCount { + property:{SetLonglineDto.PROPERTY_TOTAL_BASKETS_COUNT}; + model:{bean.getTotalBasketsCount()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.setLongline.totalBasketsCount")}; +} + +#branchlinesPerBasketCountLabel { + text:"observe.content.setLongline.branchlinesPerBasketCount"; + labelFor:{branchlinesPerBasketCount}; +} + +#branchlinesPerBasketCount { + property:{SetLonglineDto.PROPERTY_BRANCHLINES_PER_BASKET_COUNT}; + model:{bean.getBranchlinesPerBasketCount()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.setLongline.branchlinesPerBasketCount")}; +} + +#totalSectionsCountLabel { + text:"observe.content.setLongline.totalSectionsCount"; + labelFor:{totalSectionsCount}; +} + +#totalSectionsCount { + property:{SetLonglineDto.PROPERTY_TOTAL_SECTIONS_COUNT}; + model:{bean.getTotalSectionsCount()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.setLongline.totalSectionsCount")}; +} + +#totalHooksCountLabel { + text:"observe.content.setLongline.totalHooksCount"; + labelFor:{totalHooksCount}; +} + +#totalHooksCount { + property:{SetLonglineDto.PROPERTY_TOTAL_HOOKS_COUNT}; + model:{bean.getTotalHooksCount()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.setLongline.totalHooksCount")}; +} + +/* ***************************************************************************** */ +/* HAULING TAB **************************************************************** */ +/* ***************************************************************************** */ + +#haulingTab { + title:{t("observe.content.setLongline.tab.hauling")}; + icon:{handler.getErrorIconIfFalse(model.isHaulingTabValid())}; +} + +#haulingDirectionSameAsSettingLabel { + text:"observe.content.setLongline.haulingDirectionSameAsSetting"; + labelFor:{haulingDirectionSameAsSetting}; +} + +#haulingDirectionSameAsSetting { + booleanValue:{bean.getHaulingDirectionSameAsSetting()}; + _propertyName: {SetLonglineDto.PROPERTY_HAULING_DIRECTION_SAME_AS_SETTING}; + _validatorLabel:{t("observe.content.setLongline.haulingDirectionSameAsSetting")}; +} + +#haulingStartTimeStamp { + label:{t("observe.content.setLongline.haulingStartTimeStamp")}; + date:{bean.getHaulingStartTimeStamp()}; + propertyDate: {SetLonglineDto.PROPERTY_HAULING_START_TIME_STAMP}; + _validatorLabel:{t("observe.content.setLongline.haulingStartTimeStamp")}; +} + +#haulingStartCoordinates { + propertyLatitude:{SetLonglineDto.PROPERTY_HAULING_START_LATITUDE}; + propertyLongitude:{SetLonglineDto.PROPERTY_HAULING_START_LONGITUDE}; + latitude:{bean.getHaulingStartLatitude()}; + longitude:{bean.getHaulingStartLongitude()}; + _validatorLabel:{t("observe.content.setLongline.haulingStartCoordinates")}; +} + +#haulingEndTimeStamp { + label:{t("observe.content.setLongline.haulingEndTimeStamp")}; + date:{bean.getHaulingEndTimeStamp()}; + propertyDate: {SetLonglineDto.PROPERTY_HAULING_END_TIME_STAMP}; + _validatorLabel:{t("observe.content.setLongline.haulingEndTimeStamp")}; +} + +#haulingEndCoordinates { + propertyLatitude:{SetLonglineDto.PROPERTY_HAULING_END_LATITUDE}; + propertyLongitude:{SetLonglineDto.PROPERTY_HAULING_END_LONGITUDE}; + latitude:{bean.getHaulingEndLatitude()}; + longitude:{bean.getHaulingEndLongitude()}; + _validatorLabel:{t("observe.content.setLongline.haulingEndCoordinates")}; +} + +#haulingBreaksLabel { + text:"observe.content.setLongline.haulingBreaks"; + labelFor:{haulingBreaks}; +} + +#haulingBreaks { + property:{SetLonglineDto.PROPERTY_HAULING_BREAKS}; + model:{bean.getHaulingBreaks()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.setLongline.haulingBreaks")}; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/SetLonglineUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/SetLonglineUIHandler.java new file mode 100644 index 0000000..905a4b1 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/SetLonglineUIHandler.java @@ -0,0 +1,470 @@ +package fr.ird.observe.application.swing.ui.content.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.longline.ActivityLonglineDto; +import fr.ird.observe.services.dto.longline.SetLonglineDto; +import fr.ird.observe.services.dto.longline.SetLonglineDtos; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.service.longline.SetLonglineService; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.ContentUIHandler; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import jaxx.runtime.swing.HidorButton; +import jaxx.runtime.validator.swing.SwingValidatorMessage; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; +import jaxx.runtime.validator.swing.SwingValidatorUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.jaxx.widgets.gis.CoordinateFormat; +import org.nuiton.jaxx.widgets.gis.absolute.CoordinatesEditorModel; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.event.TableModelListener; +import java.beans.PropertyChangeListener; +import java.util.HashSet; +import java.util.Set; + +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 9/1/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.7 + */ +public class SetLonglineUIHandler extends ContentUIHandler<SetLonglineDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(SetLonglineUIHandler.class); + + // Compute valid state of tab from the error table + protected final TableModelListener computeTabValidStateListener; + + // Change toogle target visible on all TimeEditors + protected final PropertyChangeListener onToogleTimeEditorSliderChangedListener; + + // Change toogle target visible on all TimeEditors + protected final PropertyChangeListener onCoordinateFormatChangedListener; + +// private final LogPropertyChanges logCoordinatesChanges; + + protected boolean toogleTimeEditorSliderIsChanging; + + protected boolean coordinateFormatChangedIsChanging; + +// static ImmutableSet<String> COORDINATES_PROPERTIES = ImmutableSet.of( +// SetLongline.PROPERTY_HAULING_START_LONGITUDE, +// SetLongline.PROPERTY_HAULING_START_LATITUDE, +// SetLongline.PROPERTY_HAULING_START_QUADRANT, +// SetLongline.PROPERTY_SETTING_START_LONGITUDE, +// SetLongline.PROPERTY_SETTING_START_LATITUDE, +// SetLongline.PROPERTY_SETTING_START_QUADRANT, +// SetLongline.PROPERTY_HAULING_END_LONGITUDE, +// SetLongline.PROPERTY_HAULING_END_LATITUDE, +// SetLongline.PROPERTY_HAULING_END_QUADRANT, +// SetLongline.PROPERTY_SETTING_END_LONGITUDE, +// SetLongline.PROPERTY_SETTING_END_LATITUDE, +// SetLongline.PROPERTY_SETTING_END_QUADRANT); + + public SetLonglineUIHandler(SetLonglineUI ui) { + super(ui, DataContextType.ActivityLongline, DataContextType.SetLongline); +// this.logCoordinatesChanges = new LogPropertyChanges(COORDINATES_PROPERTIES); + computeTabValidStateListener = e -> { + + SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); + computeTabValidState(source); + + }; + onToogleTimeEditorSliderChangedListener = evt -> { + Boolean newValue = (Boolean) evt.getNewValue(); + onToogleTimeEditorSliderChanged(newValue); + }; + onCoordinateFormatChangedListener = evt -> { + CoordinateFormat newValue = (CoordinateFormat) evt.getNewValue(); + onCoordinateFormatChanged(newValue); + }; + } + + @Override + public SetLonglineUI getUi() { + return (SetLonglineUI) super.getUi(); + } + + @Override + protected boolean computeCanWrite(ObserveSwingDataSource source) { + return source.canWriteData(); + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + String setId = getSelectedId(); + + if (setId == null) { + + // mode creation + return ContentMode.CREATE; + + } + + if (getOpenDataManager().isOpenActivityLongline(dataContext.getSelectedActivityLonglineId())) { + + // l'activité est ouverte, mode édition + return ContentMode.UPDATE; + + } + + // l'activité n'est pas ouverte, mode lecture + addMessage(getUi(), + NuitonValidatorScope.INFO, + getEntityLabel(ActivityLonglineDto.class), + t("observe.storage.activityLongline.message.not.open")); + + return ContentMode.READ; + + } + + @Override + public void initUI() { + + super.initUI(); + + getUi().getSettingStartTimeStamp().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); + getUi().getSettingEndTimeStamp().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); + getUi().getHaulingStartTimeStamp().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); + getUi().getHaulingEndTimeStamp().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); + + getUi().getSettingStartCoordinates().getModel().addPropertyChangeListener(CoordinatesEditorModel.PROPERTY_FORMAT, onCoordinateFormatChangedListener); + getUi().getSettingEndCoordinates().getModel().addPropertyChangeListener(CoordinatesEditorModel.PROPERTY_FORMAT, onCoordinateFormatChangedListener); + getUi().getHaulingStartCoordinates().getModel().addPropertyChangeListener(CoordinatesEditorModel.PROPERTY_FORMAT, onCoordinateFormatChangedListener); + getUi().getHaulingEndCoordinates().getModel().addPropertyChangeListener(CoordinatesEditorModel.PROPERTY_FORMAT, onCoordinateFormatChangedListener); + +// getBean().removePropertyChangeListener(logCoordinatesChanges); +// getBean().addPropertyChangeListener(logCoordinatesChanges); + } + + + @Override + public void openUI() { + + getUi().getSettingStartCoordinates().resetModel(); + getUi().getSettingEndCoordinates().resetModel(); + getUi().getHaulingStartCoordinates().resetModel(); + getUi().getHaulingEndCoordinates().resetModel(); + + // Reset quandrant + resetQuadrant(getUi().getSettingStartCoordinates()); + resetQuadrant(getUi().getSettingEndCoordinates()); + resetQuadrant(getUi().getHaulingStartCoordinates()); + resetQuadrant(getUi().getHaulingEndCoordinates()); + + if (log.isInfoEnabled()) { + log.info("OpenUI: " + getModel()); + } + super.openUI(); + + String activityId = getSelectedParentId(); + String setId = getSelectedId(); + + if (log.isInfoEnabled()) { + log.info("activityId = " + activityId); + log.info("setId = " + setId); + } + ContentMode mode = computeContentMode(); + + SetLonglineDto bean = getBean(); + + Form<SetLonglineDto> form; + if (setId == null) { + + // create mode + form = getSetLonglineService().preCreate(activityId); + + } else { + + // update mode + form = getSetLonglineService().loadForm(setId); + + } + + loadReferentialReferenceSetsInModel(form); + + getModel().setForm(form); + SetLonglineDtos.copySetLonglineDto(form.getObject(), bean); + + getUi().getSettingStartCoordinates().setLatitudeAndLongitude(bean.getSettingStartLatitude(), bean.getSettingStartLongitude()); + getUi().getSettingEndCoordinates().setLatitudeAndLongitude(bean.getSettingEndLatitude(), bean.getSettingEndLongitude()); + getUi().getHaulingStartCoordinates().setLatitudeAndLongitude(bean.getHaulingStartLatitude(), bean.getHaulingStartLongitude()); + getUi().getHaulingEndCoordinates().setLatitudeAndLongitude(bean.getHaulingEndLatitude(), bean.getHaulingEndLongitude()); + + // utilisation du mode requis + setContentMode(mode); + + // To be sure always remove listener (could prevent some leaks) + getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); + // listen messages to see if required to add + getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); + + SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); + computeTabValidState(errorTableModel); + + if (mode != ContentMode.READ) { + getUi().startEdit(null); + } + + } + + @Override + protected void closeSafeUI() { + + if (log.isInfoEnabled()) { + log.info("CloseUI: " + getModel()); + } + super.closeSafeUI(); + + // remove listener + getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); + + } + + @Override + public void startEditUI(String... binding) { + + ContentUIModel<SetLonglineDto> model = getModel(); + boolean create = model.getMode() == ContentMode.CREATE; + String contextName = getValidatorContextName(model.getMode()); + getUi().getValidator().setContext(contextName); + if (create) { + addInfoMessage(t("observe.content.setLongline.message.creating")); + } else { + addInfoMessage(t("observe.content.setLongline.message.updating")); + } + + super.startEditUI(SetLonglineUI.BINDING_COMMENT2_TEXT, + + // setting tab + SetLonglineUI.BINDING_HOME_ID_TEXT, + SetLonglineUI.BINDING_NUMBER_MODEL, + + SetLonglineUI.BINDING_SETTING_START_TIME_STAMP_DATE, + SetLonglineUI.BINDING_SETTING_START_COORDINATES_LATITUDE, + SetLonglineUI.BINDING_SETTING_START_COORDINATES_LONGITUDE, + + SetLonglineUI.BINDING_SETTING_END_TIME_STAMP_DATE, + SetLonglineUI.BINDING_SETTING_END_COORDINATES_LATITUDE, + SetLonglineUI.BINDING_SETTING_END_COORDINATES_LONGITUDE, + + // setting caracteristics tab + SetLonglineUI.BINDING_SETTING_VESSEL_SPEED_MODEL, + SetLonglineUI.BINDING_SHOOTER_USED_SELECTED, + SetLonglineUI.BINDING_SHOOTER_SPEED_MODEL, + SetLonglineUI.BINDING_TIME_BETWEEN_HOOKS_MODEL, + SetLonglineUI.BINDING_SETTING_SHAPE_SELECTED_ITEM, + SetLonglineUI.BINDING_WEIGHTED_SWIVEL_SELECTED, + SetLonglineUI.BINDING_SWIVEL_WEIGHT_MODEL, + SetLonglineUI.BINDING_WEIGHTED_SNAP_SELECTED, + SetLonglineUI.BINDING_SNAP_WEIGHT_MODEL, + SetLonglineUI.BINDING_LINE_TYPE_SELECTED_ITEM, + SetLonglineUI.BINDING_MAX_DEPTH_TARGETED_MODEL, + SetLonglineUI.BINDING_MONITORED_SELECTED, + SetLonglineUI.BINDING_LIGHTSTICKS_TYPE_SELECTED_ITEM, + SetLonglineUI.BINDING_LIGHTSTICKS_COLOR_SELECTED_ITEM, + SetLonglineUI.BINDING_LIGHTSTICKS_PER_BASKET_COUNT_MODEL, + SetLonglineUI.BINDING_BASKETS_PER_SECTION_COUNT_MODEL, + SetLonglineUI.BINDING_TOTAL_BASKETS_COUNT_MODEL, + SetLonglineUI.BINDING_BRANCHLINES_PER_BASKET_COUNT_MODEL, + SetLonglineUI.BINDING_TOTAL_SECTIONS_COUNT_MODEL, + SetLonglineUI.BINDING_TOTAL_HOOKS_COUNT_MODEL, + + // hauling tab + SetLonglineUI.BINDING_HAULING_DIRECTION_SAME_AS_SETTING_BOOLEAN_VALUE, + + SetLonglineUI.BINDING_HAULING_START_TIME_STAMP_DATE, + SetLonglineUI.BINDING_HAULING_START_COORDINATES_LATITUDE, + SetLonglineUI.BINDING_HAULING_START_COORDINATES_LONGITUDE, + + SetLonglineUI.BINDING_HAULING_END_TIME_STAMP_DATE, + SetLonglineUI.BINDING_HAULING_END_COORDINATES_LATITUDE, + SetLonglineUI.BINDING_HAULING_END_COORDINATES_LONGITUDE, + + SetLonglineUI.BINDING_HAULING_BREAKS_MODEL); + + model.setModified(create); + + } + + @Override + protected boolean doSave(SetLonglineDto bean) throws Exception { + + String activityId = getSelectedParentId(); + + SaveResultDto saveResult = getSetLonglineService().save(activityId, bean); + saveResult.toDto(bean); + + return true; + + } + + @Override + protected void afterSave(boolean refresh) { + + super.afterSave(refresh); + + SetLonglineDto bean = getBean(); + + SwingValidatorUtil.setValidatorChanged(getUi(), false); + + ObserveTreeHelper treeHelper = getTreeHelper(getUi()); + + ObserveNode node = treeHelper.getSelectedNode(); + boolean create = node.getId() == null; + + if (create) { + + getModel().setMode(ContentMode.UPDATE); + + // remove old node and recreate new node + ObserveNode parentNode = treeHelper.removeNode(node); + + DataReference<SetLonglineDto> beanRef = ObserveSwingApplicationContext.get().getReferenceBinderEngine().transformDataDtoToReference(getDecoratorService().getReferentialLocale(), bean); + node = treeHelper.addSetLongline(parentNode, beanRef); + + stopEditUI(); + treeHelper.selectNode(node); + + } else { + + // select ancestor node +// treeHelper.refreshNode(node, false); + treeHelper.reloadSelectedNode(false, false); + + } + + } + + @Override + protected boolean doDelete(SetLonglineDto bean) { + + if (askToDelete(bean)) { + return false; + } + + String activityId = getSelectedParentId(); + getSetLonglineService().delete(activityId, bean.getId()); + + return true; + + } + + protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { + + Set<String> errorProperties = new HashSet<>(); + int rowCount = errorTableModel.getRowCount(); + for (int i = 0; i < rowCount; i++) { + + SwingValidatorMessage row = errorTableModel.getRow(i); + if (NuitonValidatorScope.ERROR.equals(row.getScope())) { + errorProperties.add(row.getField()); + } + } + + boolean settingTabValid = !errorProperties.removeAll(SetLonglineUIModel.SETTING_TAB_PROPERTIES); + boolean settingCaracteristicsTabValid = !errorProperties.removeAll(SetLonglineUIModel.SETTING_CARACTERISTICS_TAB_PROPERTIES); + boolean haulingTabValid = !errorProperties.removeAll(SetLonglineUIModel.HAULING_TAB_PROPERTIES); + + SetLonglineUIModel model = (SetLonglineUIModel) getModel(); + model.setSettingTabValid(settingTabValid); + model.setSettingCaracteristicsTabValid(settingCaracteristicsTabValid); + model.setHaulingTabValid(haulingTabValid); + + } + + protected void onToogleTimeEditorSliderChanged(boolean newValue) { + + if (!toogleTimeEditorSliderIsChanging) { + + toogleTimeEditorSliderIsChanging = true; + + boolean selected = !newValue; + + try { + + getUi().getSettingStartTimeStamp().getSliderHidor().setSelected(selected); + getUi().getSettingStartTimeStamp().getSliderHidor().setTargetVisible(newValue); + + getUi().getSettingEndTimeStamp().getSliderHidor().setSelected(selected); + getUi().getSettingEndTimeStamp().getSliderHidor().setTargetVisible(newValue); + + getUi().getHaulingStartTimeStamp().getSliderHidor().setSelected(selected); + getUi().getHaulingStartTimeStamp().getSliderHidor().setTargetVisible(newValue); + + getUi().getHaulingEndTimeStamp().getSliderHidor().setSelected(selected); + getUi().getHaulingEndTimeStamp().getSliderHidor().setTargetVisible(newValue); + + } finally { + + toogleTimeEditorSliderIsChanging = false; + + } + + } + + } + + protected synchronized void onCoordinateFormatChanged(CoordinateFormat newValue) { + + if (!coordinateFormatChangedIsChanging) { + + coordinateFormatChangedIsChanging = true; + + try { + + getUi().getSettingStartCoordinates().setFormat(newValue); + getUi().getSettingEndCoordinates().setFormat(newValue); + + getUi().getHaulingStartCoordinates().setFormat(newValue); + getUi().getHaulingEndCoordinates().setFormat(newValue); + + } finally { + + coordinateFormatChangedIsChanging = false; + + } + + } + + } + + protected SetLonglineService getSetLonglineService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newSetLonglineService(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/SetLonglineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/SetLonglineUIModel.java new file mode 100644 index 0000000..e461066 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/longline/SetLonglineUIModel.java @@ -0,0 +1,132 @@ +package fr.ird.observe.application.swing.ui.content.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.ImmutableSet; +import fr.ird.observe.services.dto.longline.SetLonglineDto; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; + +import java.util.Set; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class SetLonglineUIModel extends ContentUIModel<SetLonglineDto> { + + public static final String PROPERTY_SETTING_TAB_VALID = "settingTabValid"; + + public static final String PROPERTY_SETTING_CARACTERISTICS_TAB_VALID = "settingCaracteristicsTabValid"; + + public static final String PROPERTY_HAULING_TAB_VALID = "haulingTabValid"; + + public static final Set<String> SETTING_TAB_PROPERTIES = + ImmutableSet.<String>builder().add( + SetLonglineDto.PROPERTY_HOME_ID, + SetLonglineDto.PROPERTY_NUMBER, + SetLonglineDto.PROPERTY_SETTING_START_TIME_STAMP, + SetLonglineDto.PROPERTY_SETTING_START_LATITUDE, + SetLonglineDto.PROPERTY_SETTING_START_LONGITUDE, + SetLonglineDto.PROPERTY_SETTING_END_TIME_STAMP, + SetLonglineDto.PROPERTY_SETTING_END_LATITUDE, + SetLonglineDto.PROPERTY_SETTING_END_LONGITUDE + ).build(); + + public static final Set<String> SETTING_CARACTERISTICS_TAB_PROPERTIES = + ImmutableSet.<String>builder().add( + SetLonglineDto.PROPERTY_SETTING_SHAPE, + SetLonglineDto.PROPERTY_LINE_TYPE, + SetLonglineDto.PROPERTY_LIGHTSTICKS_TYPE, + SetLonglineDto.PROPERTY_LIGHTSTICKS_COLOR, + SetLonglineDto.PROPERTY_SETTING_VESSEL_SPEED, + SetLonglineDto.PROPERTY_MAX_DEPTH_TARGETED, + SetLonglineDto.PROPERTY_SHOOTER_USED, + SetLonglineDto.PROPERTY_SHOOTER_SPEED, + SetLonglineDto.PROPERTY_WEIGHTED_SWIVEL, + SetLonglineDto.PROPERTY_SWIVEL_WEIGHT, + SetLonglineDto.PROPERTY_WEIGHTED_SNAP, + SetLonglineDto.PROPERTY_SNAP_WEIGHT, + SetLonglineDto.PROPERTY_MONITORED, + SetLonglineDto.PROPERTY_TIME_BETWEEN_HOOKS, + SetLonglineDto.PROPERTY_BASKETS_PER_SECTION_COUNT, + SetLonglineDto.PROPERTY_BRANCHLINES_PER_BASKET_COUNT, + SetLonglineDto.PROPERTY_LIGHTSTICKS_PER_BASKET_COUNT, + SetLonglineDto.PROPERTY_TOTAL_SECTIONS_COUNT, + SetLonglineDto.PROPERTY_TOTAL_BASKETS_COUNT, + SetLonglineDto.PROPERTY_TOTAL_HOOKS_COUNT + ).build(); + + public static final Set<String> HAULING_TAB_PROPERTIES = + ImmutableSet.<String>builder().add( + SetLonglineDto.PROPERTY_HAULING_DIRECTION_SAME_AS_SETTING, + SetLonglineDto.PROPERTY_HAULING_START_LATITUDE, + SetLonglineDto.PROPERTY_HAULING_START_LONGITUDE, + SetLonglineDto.PROPERTY_HAULING_START_TIME_STAMP, + SetLonglineDto.PROPERTY_HAULING_END_LATITUDE, + SetLonglineDto.PROPERTY_HAULING_END_LONGITUDE, + SetLonglineDto.PROPERTY_HAULING_END_TIME_STAMP, + SetLonglineDto.PROPERTY_HAULING_BREAKS + ).build(); + + private static final long serialVersionUID = 1L; + + protected boolean settingTabValid; + + protected boolean settingCaracteristicsTabValid; + + protected boolean haulingTabValid; + + public SetLonglineUIModel() { + super(SetLonglineDto.class); + } + + public boolean isHaulingTabValid() { + return haulingTabValid; + } + + public void setHaulingTabValid(boolean haulingTabValid) { + this.haulingTabValid = haulingTabValid; + firePropertyChange(PROPERTY_HAULING_TAB_VALID, null, haulingTabValid); + } + + public boolean isSettingCaracteristicsTabValid() { + return settingCaracteristicsTabValid; + } + + public void setSettingCaracteristicsTabValid(boolean settingCaracteristicsTabValid) { + this.settingCaracteristicsTabValid = settingCaracteristicsTabValid; + firePropertyChange(PROPERTY_SETTING_CARACTERISTICS_TAB_VALID, null, settingCaracteristicsTabValid); + } + + public boolean isSettingTabValid() { + return settingTabValid; + } + + public void setSettingTabValid(boolean settingTabValid) { + this.settingTabValid = settingTabValid; + firePropertyChange(PROPERTY_SETTING_TAB_VALID, null, settingTabValid); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/ActivitySeineObservedSystemUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/ActivitySeineObservedSystemUI.jaxx new file mode 100644 index 0000000..7353c8c --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/ActivitySeineObservedSystemUI.jaxx @@ -0,0 +1,113 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ContentUI superGenericType='ActivitySeineObservedSystemDto' contentTitle='{n("observe.storage.activitySeineObservedSystem.title")}'> + + <import> + fr.ird.observe.services.dto.seine.ActivitySeineObservedSystemDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.seine.ObservedSystemDto + fr.ird.observe.application.swing.ui.actions.shared.ResetEditUIAction + fr.ird.observe.application.swing.ui.actions.shared.SaveEditUIAction + + jaxx.runtime.swing.editor.NumberEditor + org.nuiton.jaxx.widgets.select.FilterableDoubleList + + java.util.List + java.util.ArrayList + java.util.Collection + + java.awt.Dimension + + javax.swing.DefaultListModel + javax.swing.ListSelectionModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <ActivitySeineObservedSystemUIHandler id='handler'/> + + <!-- model --> + <ActivitySeineObservedSystemUIModel id='model'/> + + <!-- edit bean --> + <ActivitySeineObservedSystemDto id='bean'/> + + <!-- validator --> + <BeanValidator id='validator' + beanClass='fr.ird.observe.services.dto.seine.ActivitySeineObservedSystemDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update'> + <field name='observedSystem' component='observedSystemPane'/> + <field name='observedSystemDistance'/> + <field name='comment'/> + </BeanValidator> + + <!-- formulaire --> + <JPanel id="body" layout='{new BorderLayout()}'> + <Table fill='both' constraints="BorderLayout.CENTER"> + <!-- systeme observe --> + <row> + <cell columns="2" fill="both" weighty="0.7"> + <JScrollPane id='observedSystemPane' onFocusGained='observedSystem.requestFocus()'> + <FilterableDoubleList id='observedSystem' + genericType='ReferentialReference<ObservedSystemDto>' + _entityClass='ObservedSystemDto.class'/> + </JScrollPane> + </cell> + </row> + <!-- distance au système observe --> + <row> + <cell anchor='west'> + <JLabel id='observedSystemDistanceLabel'/> + </cell> + <cell weightx="1" fill="both"> + <NumberEditor id='observedSystemDistance' constructorParams='this'/> + </cell> + </row> + <!-- comment --> + <row> + <cell columns='2' fill="both" weighty="0.3"> + <JScrollPane id='comment' + onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2' + onKeyReleased='getBean().setComment(comment2.getText())'/> + </JScrollPane> + </cell> + </row> + </Table> + </JPanel> + + <!-- actions --> + <Table id="actions" fill='both' weightx='1' insets='0'> + <row> + <cell weightx="0.5"> + <JButton id='reset'/> + </cell> + <cell weightx="0.5"> + <JButton id='save'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/ActivitySeineObservedSystemUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/ActivitySeineObservedSystemUI.jcss new file mode 100644 index 0000000..6d27625 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/ActivitySeineObservedSystemUI.jcss @@ -0,0 +1,78 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#model { + editable:true; + modified:{validator.isChanged()}; + valid:{validator.isValid()}; + enabled:{!model.isReadingMode()}; +} + +#observedSystemPane { + /*columnHeaderView:{new JLabel(t("observe.common.observedSystem"))};*/ + minimumSize:{new Dimension(10,150)}; +} + +#observedSystem { + bean:{bean}; + property: {ActivitySeineObservedSystemDto.PROPERTY_OBSERVED_SYSTEM}; + selected:{(Collection)bean.getObservedSystem()}; + _validatorLabel: {t("observe.common.observedSystem")}; + showListLabel: true; + universeLabel:{t("observe.storage.activityObservedSystem.availableObservedSystem")}; + selectedLabel:{t("observe.storage.activityObservedSystem.selectedObservedSystem")}; +} + +#observedSystemDistanceLabel { + text:"observe.common.observedSystemDistance"; + labelFor:{observedSystemDistance}; +} + +#observedSystemDistance { + bean:{bean}; + property: {ActivitySeineObservedSystemDto.PROPERTY_OBSERVED_SYSTEM_DISTANCE}; + model:{bean.getObservedSystemDistance()}; + useFloat:true; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL2_PATTERN}; +} + +#comment { + columnHeaderView:{new JLabel(t("observe.common.comment.activity"))}; + minimumSize:{new Dimension(10,50)}; +} + +#comment2 { + text:{getStringValue(bean.getComment())}; +} + +#reset { + _observeAction:{ResetEditUIAction.ACTION_NAME}; + visible:{model.isUpdatingMode()}; + enabled:{model.isModified()}; +} + +#save { + _observeAction:{SaveEditUIAction.ACTION_NAME}; + visible:{model.isEnabled()}; + enabled:{model.isModified() && model.isValid()}; +} + diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/ActivitySeineObservedSystemUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/ActivitySeineObservedSystemUIHandler.java new file mode 100644 index 0000000..5b46fb6 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/ActivitySeineObservedSystemUIHandler.java @@ -0,0 +1,123 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.impl.seine; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.dto.seine.ActivitySeineObservedSystemDto; +import fr.ird.observe.services.dto.seine.ActivitySeineObservedSystemDtos; +import fr.ird.observe.services.service.seine.ActivitySeineObservedSystemService; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.ContentUIHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import static org.nuiton.i18n.I18n.t; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class ActivitySeineObservedSystemUIHandler extends ContentUIHandler<ActivitySeineObservedSystemDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(ActivitySeineObservedSystemUIHandler.class); + + public ActivitySeineObservedSystemUIHandler(ActivitySeineObservedSystemUI ui) { + super(ui, DataContextType.ActivitySeine, null); + } + + @Override + public ActivitySeineObservedSystemUI getUi() { + return (ActivitySeineObservedSystemUI) super.getUi(); + } + + @Override + protected boolean computeCanWrite(ObserveSwingDataSource source) { + return source.canWriteData(); + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + if (getOpenDataManager().isOpenActivitySeine(dataContext.getSelectedActivitySeineId())) { + + // l'activity courante est ouverte, on peut modifier + return ContentMode.UPDATE; + } + + // activity courante non ouverte + addInfoMessage(t("observe.storage.activitySeine.message.not.open")); + + return ContentMode.READ; + } + + @Override + public void openUI() { + super.openUI(); + + String activityId = getSelectedParentId(); + + if (log.isInfoEnabled()) { + log.info("activityId = " + activityId); + } + + ContentMode mode = computeContentMode(); + + getModel().setMode(mode); + + Form<ActivitySeineObservedSystemDto> form = getActivitySeineObservedSystemService().loadForm(activityId); + + loadReferentialReferenceSetsInModel(form); + + getModel().setForm(form); + ActivitySeineObservedSystemDtos.copyActivitySeineObservedSystemDto(form.getObject(), getBean()); + + if (mode == ContentMode.UPDATE) { + getUi().startEdit(null); + } + } + + @Override + public void startEditUI(String... binding) { + addInfoMessage(t("observe.storage.activitySeine.message.updating")); + super.startEditUI(binding); + } + + @Override + protected boolean doSave(ActivitySeineObservedSystemDto bean) throws Exception { + + // on sauvegarde l'activity (mais pas la calée) + SaveResultDto saveResult = getActivitySeineObservedSystemService().save(bean); + saveResult.toDto(bean); + + return true; + } + + protected ActivitySeineObservedSystemService getActivitySeineObservedSystemService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivitySeineObservedSystemService(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/ActivitySeineObservedSystemUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/ActivitySeineObservedSystemUIModel.java new file mode 100644 index 0000000..7f49c74 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/ActivitySeineObservedSystemUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.seine.ActivitySeineObservedSystemDto; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ActivitySeineObservedSystemUIModel extends ContentUIModel<ActivitySeineObservedSystemDto> { + + private static final long serialVersionUID = 1L; + + public ActivitySeineObservedSystemUIModel() { + super(ActivitySeineObservedSystemDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUI.jaxx new file mode 100644 index 0000000..dff19f9 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUI.jaxx @@ -0,0 +1,257 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ContentUI superGenericType='FloatingObjectTransmittingBuoyDto' + contentTitle='{n("observe.content.floatingObjectTransmittingBuoyOperation.title")}'> + + <import> + fr.ird.observe.services.dto.seine.FloatingObjectTransmittingBuoyDto + fr.ird.observe.services.dto.seine.TransmittingBuoyDto + fr.ird.observe.services.dto.constants.seine.Ownership + fr.ird.observe.services.dto.constants.seine.TypeTransmittingBuoyOperation + fr.ird.observe.services.dto.referential.CountryDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.seine.TransmittingBuoyOperationDto + fr.ird.observe.services.dto.referential.seine.TransmittingBuoyTypeDto + fr.ird.observe.application.swing.ui.actions.shared.ResetEditUIAction + fr.ird.observe.application.swing.ui.actions.shared.SaveEditUIAction + fr.ird.observe.application.swing.ui.content.ContentUIModel + jaxx.runtime.swing.editor.bean.BeanComboBox + + java.awt.Dimension + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <FloatingObjectTransmittingBuoyOperationUIHandler id='handler'/> + + <!-- model --> + <FloatingObjectTransmittingBuoyOperationUIModel id='model'/> + + <!-- edit bean --> + <FloatingObjectTransmittingBuoyDto id='bean'/> + + <!-- transmittingBuoy1 edit bean --> + <TransmittingBuoyDto id='transmittingBuoy1' initializer='new TransmittingBuoyDto()'/> + + <!-- transmittingBuoy2 edit bean --> + <TransmittingBuoyDto id='transmittingBuoy2' initializer='new TransmittingBuoyDto()'/> + + <!-- validator --> + <BeanValidator id='validator' + autoField='true' + beanClass='fr.ird.observe.services.dto.seine.FloatingObjectTransmittingBuoyDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update-objectOperation'> + </BeanValidator> + + <BeanValidator id='validatorBalise1' + beanClass='fr.ird.observe.services.dto.seine.TransmittingBuoyDto' + errorTableModel='{getErrorTableModel()}' + parentValidator='{validator}' + context='ui-update'> + <field name="transmittingBuoyType" component="transmittingBuoyType1"/> + <field name="transmittingBuoyOperation" component="transmittingBuoyOperation1"/> + <field name="ownership" component="ownership1"/> + <field name="code" component="code1"/> + <field name="country" component="country1"/> + </BeanValidator> + + <BeanValidator id='validatorBalise2' + beanClass='fr.ird.observe.services.dto.seine.TransmittingBuoyDto' + errorTableModel='{getErrorTableModel()}' + parentValidator='{validator}' + context='ui-update'> + <field name="transmittingBuoyType" component="transmittingBuoyType2"/> + <field name="transmittingBuoyOperation" component="transmittingBuoyOperation2"/> + <field name="ownership" component="ownership2"/> + <field name="code" component="code2"/> + <field name="country" component="country2"/> + </BeanValidator> + + + <!-- formulaire --> + <JPanel id="body" layout='{new BorderLayout()}'> + + + <Table fill='both' constraints="BorderLayout.NORTH"> + <row> + <cell anchor='west'> + <JLabel id='typeOperationLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <EnumEditor id='typeOperation' + genericType='TypeTransmittingBuoyOperation' + constructorParams='TypeTransmittingBuoyOperation.class' + onItemStateChanged='if(event.getStateChange()==ItemEvent.SELECTED && model.isEditing()) { getHandler().changeTypeOperation(typeOperation.getSelectedItem(), true); model.setModified(true); }'/> + </cell> + </row> + </Table> + + <JPanel id="transmittingBuoys" constraints="BorderLayout.CENTER"/> + + <JScrollPane id='comment' constraints="BorderLayout.SOUTH" + onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2' + onKeyReleased='getBean().setComment(comment2.getText())'/> + </JScrollPane> + + </JPanel> + + <!-- actions --> + <Table id="actions" fill='both' weightx='1' insets='0'> + <row> + <cell weightx="0.5"> + <JButton id='reset'/> + </cell> + <cell weightx="0.5"> + <JButton id='save'/> + </cell> + </row> + </Table> + + <JPanel id="invisible"> + + <JLabel id='noBaliseEditor'/> + + <Table id='transmittingBuoy1Editor' fill="horizontal"> + <row> + <cell anchor='west'> + <JLabel id='transmittingBuoyOperation1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='transmittingBuoyOperation1' constructorParams='this' + genericType='ReferentialReference<TransmittingBuoyOperationDto>' + _entityClass='TransmittingBuoyOperationDto.class'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='transmittingBuoyType1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='transmittingBuoyType1' constructorParams='this' + genericType='ReferentialReference<TransmittingBuoyTypeDto>' + _entityClass='TransmittingBuoyTypeDto.class'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='ownership1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <EnumEditor id='ownership1' + constructorParams='Ownership.class' + onItemStateChanged='transmittingBuoy1.setOwnership((Ownership) ownership1.getSelectedItem())'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='country1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='country1' constructorParams='this' genericType='ReferentialReference<CountryDto>' _entityClass='CountryDto.class'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='code1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='code1' + onKeyReleased='transmittingBuoy1.setCode(code1.getText())'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='brand1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='brand1' + onKeyReleased='transmittingBuoy1.setBrand(brand1.getText())'/> + </cell> + </row> + </Table> + + <Table id='transmittingBuoy2Editor' fill="horizontal"> + <row> + <cell anchor='west'> + <JLabel id='transmittingBuoyOperation2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='transmittingBuoyOperation2' constructorParams='this' + genericType='ReferentialReference<TransmittingBuoyOperationDto>' + _entityClass='TransmittingBuoyOperationDto.class'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='transmittingBuoyType2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='transmittingBuoyType2' constructorParams='this' + genericType='ReferentialReference<TransmittingBuoyTypeDto>' + _entityClass='TransmittingBuoyTypeDto.class'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='ownership2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <EnumEditor id='ownership2' + constructorParams='Ownership.class' + onItemStateChanged='transmittingBuoy2.setOwnership((Ownership) ownership2.getSelectedItem())'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='country2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='country2' constructorParams='this' genericType='ReferentialReference<CountryDto>' _entityClass='CountryDto.class'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='code2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='code2' + onKeyReleased='transmittingBuoy2.setCode(code2.getText())'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='brand2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='brand2' + onKeyReleased='transmittingBuoy2.setBrand(brand2.getText())'/> + </cell> + </row> + </Table> + + </JPanel> +</fr.ird.observe.application.swing.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUIHandler.java new file mode 100644 index 0000000..e6e5b50 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUIHandler.java @@ -0,0 +1,376 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.impl.seine; + +import com.google.common.collect.Lists; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.constants.seine.Ownership; +import fr.ird.observe.services.dto.constants.seine.TypeTransmittingBuoyOperation; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.seine.TransmittingBuoyOperationDto; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.services.dto.seine.FloatingObjectTransmittingBuoyDto; +import fr.ird.observe.services.dto.seine.FloatingObjectTransmittingBuoyDtos; +import fr.ird.observe.services.dto.seine.TransmittingBuoyDto; +import fr.ird.observe.services.dto.seine.TransmittingBuoyDtos; +import fr.ird.observe.services.service.seine.TransmittingBuoyOperationService; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.ContentUIHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.JPanel; +import javax.swing.SwingUtilities; +import java.awt.GridLayout; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import static org.nuiton.i18n.I18n.t; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class FloatingObjectTransmittingBuoyOperationUIHandler extends ContentUIHandler<FloatingObjectTransmittingBuoyDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(FloatingObjectTransmittingBuoyOperationUIHandler.class); + + public FloatingObjectTransmittingBuoyOperationUIHandler(FloatingObjectTransmittingBuoyOperationUI ui) { + super(ui, DataContextType.FloatingObject, null); + } + + @Override + public FloatingObjectTransmittingBuoyOperationUI getUi() { + return (FloatingObjectTransmittingBuoyOperationUI) super.getUi(); + } + + @Override + public FloatingObjectTransmittingBuoyOperationUIModel getModel() { + return (FloatingObjectTransmittingBuoyOperationUIModel) super.getModel(); + } + + @Override + protected boolean computeCanWrite(ObserveSwingDataSource source) { + return source.canWriteData(); + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + if (getOpenDataManager().isOpenActivitySeine(dataContext.getSelectedActivitySeineId())) { + + // l'activity courante est ouverte, on peut modifier + return ContentMode.UPDATE; + } + + // activity courante non ouverte + addMessage(getUi(), + NuitonValidatorScope.INFO, + getEntityLabel(ActivitySeineDto.class), + t("observe.storage.activitySeine.message.not.open")); + + return ContentMode.READ; + } + + @Override + public void openUI() { + super.openUI(); + + ContentMode mode = computeContentMode(); + + String dcpId = getSelectedParentId(); + + if (log.isInfoEnabled()) { + log.info("dcpId = " + dcpId); + } + + FloatingObjectTransmittingBuoyDto bean = getBean(); + + bean.getTransmittingBuoy().clear(); + + // pour etre sur que rien ne va changer pendant le chargement de l'objet. + + getModel().setEditing(false); + + Form<FloatingObjectTransmittingBuoyDto> form = getTransmittingBuoyOperationService().loadForm(dcpId); + loadReferentialReferenceSetsInModel(form); + + getModel().setForm(form); + FloatingObjectTransmittingBuoyDtos.copyFloatingObjectTransmittingBuoyDto(form.getObject(), bean); + + if (bean.sizeTransmittingBuoy() >= 1) { + TransmittingBuoyDtos.copyTransmittingBuoyDto( + bean.getTransmittingBuoy(0), + getUi().getTransmittingBuoy1()); + + if (bean.sizeTransmittingBuoy() >= 2) { + TransmittingBuoyDtos.copyTransmittingBuoyDto( + bean.getTransmittingBuoy(1), + getUi().getTransmittingBuoy2()); + } + } + + getUi().processDataBinding( + FloatingObjectTransmittingBuoyOperationUI.BINDING_TYPE_OPERATION_SELECTED_ITEM); + + TypeTransmittingBuoyOperation typeOperation = + getUi().getTypeOperation().getSelectedItem(); + changeTypeOperation(typeOperation, false); + + getModel().setMode(mode); + + if (mode == ContentMode.UPDATE) { + getUi().startEdit(null); + } + } + + + @Override + public void startEditUI(String... binding) { + super.startEditUI( + FloatingObjectTransmittingBuoyOperationUI.BINDING_TRANSMITTING_BUOY_OPERATION1_SELECTED_ITEM, + FloatingObjectTransmittingBuoyOperationUI.BINDING_TRANSMITTING_BUOY_OPERATION2_SELECTED_ITEM, + FloatingObjectTransmittingBuoyOperationUI.BINDING_CODE1_TEXT, + FloatingObjectTransmittingBuoyOperationUI.BINDING_CODE2_TEXT, + FloatingObjectTransmittingBuoyOperationUI.BINDING_OWNERSHIP1_SELECTED_ITEM, + FloatingObjectTransmittingBuoyOperationUI.BINDING_OWNERSHIP2_SELECTED_ITEM, + FloatingObjectTransmittingBuoyOperationUI.BINDING_TRANSMITTING_BUOY_TYPE1_SELECTED_ITEM, + FloatingObjectTransmittingBuoyOperationUI.BINDING_TRANSMITTING_BUOY_TYPE2_SELECTED_ITEM, + FloatingObjectTransmittingBuoyOperationUI.BINDING_BRAND1_TEXT, + FloatingObjectTransmittingBuoyOperationUI.BINDING_BRAND2_TEXT, + FloatingObjectTransmittingBuoyOperationUI.BINDING_COUNTRY1_SELECTED_ITEM, + FloatingObjectTransmittingBuoyOperationUI.BINDING_COUNTRY2_SELECTED_ITEM, + FloatingObjectTransmittingBuoyOperationUI.BINDING_TYPE_OPERATION_SELECTED_ITEM + ); + + FloatingObjectTransmittingBuoyOperationUI ui = getUi(); + + addInfoMessage(t("observe.message.updating.floatingObject")); + + Collection<TransmittingBuoyDto> balises = getBean().getTransmittingBuoy(); + if (balises != null && !balises.isEmpty()) { + TransmittingBuoyDto transmittingBuoy1 = ui.getTransmittingBuoy1(); + ui.getValidatorBalise1().setBean(transmittingBuoy1); + + if (balises.size() == 2) { + TransmittingBuoyDto transmittingBuoy2 = ui.getTransmittingBuoy2(); + ui.getValidatorBalise2().setBean(transmittingBuoy2); + } + } + + UIHelper.processDataBinding( + ui, + FloatingObjectTransmittingBuoyOperationUI.BINDING_TRANSMITTING_BUOY_OPERATION1_SELECTED_ITEM, + FloatingObjectTransmittingBuoyOperationUI.BINDING_TRANSMITTING_BUOY_OPERATION2_SELECTED_ITEM, + FloatingObjectTransmittingBuoyOperationUI.BINDING_CODE1_TEXT, + FloatingObjectTransmittingBuoyOperationUI.BINDING_CODE2_TEXT, + FloatingObjectTransmittingBuoyOperationUI.BINDING_OWNERSHIP1_SELECTED_ITEM, + FloatingObjectTransmittingBuoyOperationUI.BINDING_OWNERSHIP2_SELECTED_ITEM, + FloatingObjectTransmittingBuoyOperationUI.BINDING_BRAND1_TEXT, + FloatingObjectTransmittingBuoyOperationUI.BINDING_BRAND2_TEXT, + FloatingObjectTransmittingBuoyOperationUI.BINDING_COUNTRY1_SELECTED_ITEM, + FloatingObjectTransmittingBuoyOperationUI.BINDING_COUNTRY2_SELECTED_ITEM, + FloatingObjectTransmittingBuoyOperationUI.BINDING_TRANSMITTING_BUOY_TYPE1_SELECTED_ITEM, + FloatingObjectTransmittingBuoyOperationUI.BINDING_TRANSMITTING_BUOY_TYPE2_SELECTED_ITEM); + getModel().setModified(false); + } + + public boolean isBalisePose(TransmittingBuoyOperationDto operation) { + return operation != null && "3".equals(operation.getCode()); + } + + public boolean isBalisePose(ReferentialReference<TransmittingBuoyOperationDto> operation) { + return operation != null && "3".equals(operation.getPropertyValue(TransmittingBuoyOperationDto.PROPERTY_CODE)); + } + + @Override + protected boolean doSave(FloatingObjectTransmittingBuoyDto bean) throws Exception { + + SaveResultDto saveResult = getTransmittingBuoyOperationService().save(bean); + saveResult.toDto(bean); + //FIXME, il faut declancher un evenement dans le cache du storage pour pouvoir redessiner le noeud + return true; + } + + @Override + protected void afterSave(boolean refresh) { + // rien a rafraichir ? + resetEditUI(); + } + + protected void changeTypeOperation(TypeTransmittingBuoyOperation typeOperation, boolean reset) { + + FloatingObjectTransmittingBuoyOperationUI ui = getUi(); + + if (log.isInfoEnabled()) { + log.info(typeOperation + " doReset ? " + reset); + } + int nbBalises = typeOperation.getNbBalises(); + + FloatingObjectTransmittingBuoyDto bean = getBean(); + + boolean hasBalise = !bean.isTransmittingBuoyEmpty(); + + List<TransmittingBuoyDto> objets = new ArrayList<>(); + if (!reset) { + if (hasBalise) { + objets.addAll(bean.getTransmittingBuoy()); + } + } + + if (hasBalise) { + // always reset balise lues of editBean to avoid side-effects + bean.getTransmittingBuoy().clear(); + } + + // clean container + JPanel editorPanel = ui.getTransmittingBuoys(); + editorPanel.removeAll(); + + String[] codeOperations = typeOperation.getCodeOperation(); + List<ReferentialReference<TransmittingBuoyOperationDto>> operations = + ui.getTransmittingBuoyOperation1().getData(); + + TransmittingBuoyDto transmittingBuoy; + ReferentialReference<TransmittingBuoyOperationDto> objectOperation; + switch (nbBalises) { + case 0: + // no balise + editorPanel.setLayout(new GridLayout()); + editorPanel.add(ui.getNoBaliseEditor()); + if (getModel().isEditing()) { + ui.getValidatorBalise1().setBean(null); + ui.getValidatorBalise2().setBean(null); + } + break; + + case 1: + + transmittingBuoy = reset ? null : objets.get(0); + + objectOperation = reset ? getObjectOperation(operations, codeOperations[0]) : null; + + bindEditBalise(ui.getTransmittingBuoy1(), objectOperation, transmittingBuoy); + + editorPanel.setLayout(new GridLayout(1, 0)); + editorPanel.add(ui.getTransmittingBuoy1Editor()); + if (getModel().isEditing()) { + ui.getValidatorBalise1().setBean(ui.getTransmittingBuoy1()); + ui.getValidatorBalise2().setBean(null); + } + break; + + case 2: + + transmittingBuoy = reset ? null : objets.get(0); + objectOperation = reset ? getObjectOperation(operations, codeOperations[0]) : null; + bindEditBalise(ui.getTransmittingBuoy1(), objectOperation, transmittingBuoy); + + transmittingBuoy = reset ? null : objets.get(1); + objectOperation = reset ? getObjectOperation(operations, codeOperations[1]) : null; + bindEditBalise(ui.getTransmittingBuoy2(), objectOperation, transmittingBuoy); + + editorPanel.setLayout(new GridLayout(2, 0)); + editorPanel.add(ui.getTransmittingBuoy1Editor()); + editorPanel.add(ui.getTransmittingBuoy2Editor()); + if (getModel().isEditing()) { + ui.getValidatorBalise1().setBean(ui.getTransmittingBuoy1()); + ui.getValidatorBalise2().setBean(ui.getTransmittingBuoy2()); + } + break; + } + + SwingUtilities.invokeLater(() -> { + + // recalcul de la disposition + getUi().revalidate(); + }); + + } + + protected void bindEditBalise(TransmittingBuoyDto editBean, + ReferentialReference<TransmittingBuoyOperationDto> transmittingBuoyOperation, + TransmittingBuoyDto transmittingBuoy) { + + if (transmittingBuoy == null) { + + TransmittingBuoyDtos.copyTransmittingBuoyDto(new TransmittingBuoyDto(), editBean); + + editBean.setTransmittingBuoyOperation(transmittingBuoyOperation); + + if (log.isDebugEnabled()) { + log.debug("Reuse an empty balise lue for objectOperation " + + transmittingBuoyOperation.getPropertyValue(TransmittingBuoyOperationDto.PROPERTY_LABEL1)); + } + + if (isBalisePose(transmittingBuoyOperation)) { + + // objectOperation de pose + // toujours appartient au navire + editBean.setOwnership(Ownership.ceVessel); + } + + } else { + + TransmittingBuoyDtos.copyTransmittingBuoyDto(editBean, transmittingBuoy); + + } + + FloatingObjectTransmittingBuoyDto bean = getBean(); + + if (bean.getTransmittingBuoy() == null) { + bean.setTransmittingBuoy(Lists.newArrayList()); + } + bean.getTransmittingBuoy().add(editBean); + } + + protected ReferentialReference<TransmittingBuoyOperationDto> getObjectOperation(List<ReferentialReference<TransmittingBuoyOperationDto>> objectOperations, + String codeOperation) { + ReferentialReference<TransmittingBuoyOperationDto> objectOperation = null; + for (ReferentialReference<TransmittingBuoyOperationDto> op : objectOperations) { + if (codeOperation.equals(op.getPropertyValue(TransmittingBuoyOperationDto.PROPERTY_CODE))) { + objectOperation = op; + break; + } + } + if (objectOperation == null) { + throw new IllegalArgumentException( + "could not find a " + + TransmittingBuoyOperationDto.class + " with code " + codeOperation); + } + return objectOperation; + } + + protected TransmittingBuoyOperationService getTransmittingBuoyOperationService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTransmittingBuoyOperationService(); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUIModel.java new file mode 100644 index 0000000..da91c90 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.seine.FloatingObjectTransmittingBuoyDto; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class FloatingObjectTransmittingBuoyOperationUIModel extends ContentUIModel<FloatingObjectTransmittingBuoyDto> { + + private static final long serialVersionUID = 1L; + + public FloatingObjectTransmittingBuoyOperationUIModel() { + super(FloatingObjectTransmittingBuoyDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectUI.jaxx new file mode 100644 index 0000000..301fedf --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectUI.jaxx @@ -0,0 +1,136 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ContentUI superGenericType='FloatingObjectDto' contentTitle='{n("observe.content.floatingObject.title")}'> + + <import> + fr.ird.observe.services.dto.seine.FloatingObjectDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.seine.ObjectFateDto + fr.ird.observe.services.dto.referential.seine.ObjectOperationDto + fr.ird.observe.services.dto.referential.seine.ObjectTypeDto + fr.ird.observe.application.swing.ui.actions.shared.CancelCreateUIAction + fr.ird.observe.application.swing.ui.actions.shared.DeleteDataUIAction + fr.ird.observe.application.swing.ui.actions.shared.ResetEditUIAction + fr.ird.observe.application.swing.ui.actions.shared.SaveEditUIAction + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + java.awt.Dimension + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <FloatingObjectUIHandler id='handler'/> + + <!-- model --> + <FloatingObjectUIModel id='model'/> + + <!-- edit bean --> + <FloatingObjectDto id='bean'/> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' context='ui-create' + beanClass='fr.ird.observe.services.dto.seine.FloatingObjectDto' + errorTableModel='{getErrorTableModel()}'/> + + <!-- formulaire --> + <JPanel id="body" layout='{new BorderLayout()}'> + <Table fill='both' constraints="BorderLayout.CENTER"> + <row> + <cell anchor='west'> + <JLabel id='objectOperationLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='objectOperation' constructorParams='this' genericType='ReferentialReference<ObjectOperationDto>' _entityClass='ObjectOperationDto.class'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='objectTypeLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='objectType' constructorParams='this' genericType='ReferentialReference<ObjectTypeDto>' _entityClass='ObjectTypeDto.class'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='objectFateLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='objectFate' constructorParams='this' genericType='ReferentialReference<ObjectFateDto>' _entityClass='ObjectFateDto.class'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='daysAtSeaCountLabel'/> + </cell> + <cell anchor='east' weightx="1"> + <NumberEditor id='daysAtSeaCount' constructorParams='this'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='supportVesselNameLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel layout='{new BorderLayout()}'> + <JToolBar id='supportVesselNameToolbar' constraints='BorderLayout.WEST'> + <JButton id='resetSupportVesselName' constraints='BorderLayout.WEST' styleClass='resetButton'/> + </JToolBar> + <JTextField id='supportVesselName' constraints='BorderLayout.CENTER'/> + </JPanel> + </cell> + </row> + <row> + <cell columns='2' fill="both" weighty="0.7"> + <JScrollPane id='comment' + onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2' + onKeyReleased='getBean().setComment(comment2.getText())'/> + </JScrollPane> + </cell> + </row> + </Table> + </JPanel> + + <!-- actions --> + <Table id="actions" fill='both' weightx='1' insets='0'> + <row> + <cell weightx="0.5" fill="both"> + <JButton id='cancel'/> + </cell> + <cell weightx="0.5"> + <JButton id='reset'/> + </cell> + <cell weightx="0.5"> + <JButton id='save'/> + </cell> + <cell weightx="0.5"> + <JButton id='delete'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectUI.jcss new file mode 100644 index 0000000..bd68713 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectUI.jcss @@ -0,0 +1,126 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +BeanComboBox { + bean:{bean}; + showReset:true; +} + +#model { + editable:true; + modified:{validator.isChanged()}; + valid:{validator.isValid()}; + enabled:{!model.isReadingMode()}; +} + +#objectOperationLabel { + text:"observe.common.objectOperation"; + labelFor:{objectOperation}; +} + +#objectOperation { + property:{FloatingObjectDto.PROPERTY_OBJECT_OPERATION}; + selectedItem:{bean.getObjectOperation()}; +} + +#objectTypeLabel { + text:"observe.common.objectType"; + labelFor:{objectType}; +} + +#objectType { + property:{FloatingObjectDto.PROPERTY_OBJECT_TYPE}; + selectedItem:{bean.getObjectType()}; +} + +#objectFateLabel { + text:"observe.common.objectFate"; + labelFor:{objectFate}; +} + +#objectFate { + property:{FloatingObjectDto.PROPERTY_OBJECT_FATE}; + selectedItem:{bean.getObjectFate()}; +} + +#daysAtSeaCountLabel { + text:"observe.common.daysAtSeaCount"; + labelFor:{daysAtSeaCount}; +} + +#daysAtSeaCount { + bean:{bean}; + property:{FloatingObjectDto.PROPERTY_DAYS_AT_SEA_COUNT}; + model:{bean.getDaysAtSeaCount()}; + autoPopup:{config.isAutoPopupNumberEditor()}; + showPopupButton:{config.isShowNumberEditorButton()}; + showReset:true; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; +} + +#supportVesselNameLabel { + text:"observe.common.supportVesselName"; + labelFor:{supportVesselName}; +} + +#supportVesselName { + _propertyName:{FloatingObjectDto.PROPERTY_SUPPORT_VESSEL_NAME}; + text:{getStringValue(bean.getSupportVesselName())}; + _validatorLabel:{"observe.common.supportVesselName"}; +} + +#resetSupportVesselName{ + toolTipText:"observe.content.action.reset.supportVesselName.tip"; + _resetPropertyName:{FloatingObjectDto.PROPERTY_SUPPORT_VESSEL_NAME}; +} + +#comment { + columnHeaderView:{new JLabel(t("observe.common.comment.floatingObject"))}; + minimumSize:{new Dimension(10,50)}; +} + +#comment2 { + text:{getStringValue(bean.getComment())}; +} + +#cancel { + _observeAction:{CancelCreateUIAction.ACTION_NAME}; + visible:{model.isCreatingMode()}; +} + +#reset { + _observeAction:{ResetEditUIAction.ACTION_NAME}; + visible:{model.isUpdatingMode()}; + enabled:{model.isModified()}; +} + +#save { + _observeAction:{SaveEditUIAction.ACTION_NAME}; + visible:{!model.isReadingMode()}; + enabled:{model.isModified() && model.isValid()}; +} + +#delete { + _observeAction:{DeleteDataUIAction.ACTION_NAME}; + visible:{model.isUpdatingMode()}; + _toolTipText:{t("observe.action.delete.floatingObject.tip")}; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectUIHandler.java new file mode 100644 index 0000000..dd84add --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectUIHandler.java @@ -0,0 +1,225 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.impl.seine; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.services.dto.seine.FloatingObjectDto; +import fr.ird.observe.services.dto.seine.FloatingObjectDtos; +import fr.ird.observe.services.service.seine.FloatingObjectService; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.ContentUIHandler; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.validator.NuitonValidatorScope; + +import static org.nuiton.i18n.I18n.t; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class FloatingObjectUIHandler extends ContentUIHandler<FloatingObjectDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(FloatingObjectUIHandler.class); + + public FloatingObjectUIHandler(FloatingObjectUI ui) { + super(ui, DataContextType.ActivitySeine, DataContextType.FloatingObject); + } + + @Override + public FloatingObjectUI getUi() { + return (FloatingObjectUI) super.getUi(); + } + + @Override + protected boolean computeCanWrite(ObserveSwingDataSource source) { + return source.canWriteData(); + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + String dcpId = getSelectedId(); + + if (dcpId == null) { + + // mode création + return ContentMode.CREATE; + } + + // dcp existant + + if (getOpenDataManager().isOpenActivitySeine(dataContext.getSelectedActivitySeineId())) { + + // mode mise a jour + return ContentMode.UPDATE; + } + + // l'activité n'est pas ouverte + addMessage( + getUi(), + NuitonValidatorScope.INFO, + getEntityLabel(ActivitySeineDto.class), + t("observe.storage.activitySeine.message.not.open")); + + return ContentMode.READ; + } + + @Override + public void openUI() { + super.openUI(); + + String activityId = getSelectedParentId(); + String dcpId = getSelectedId(); + + if (log.isInfoEnabled()) { + log.info("activityId = " + activityId); + log.info("dcpId = " + dcpId); + } + + ContentMode mode = computeContentMode(); + + FloatingObjectDto bean = getBean(); + + Form<FloatingObjectDto> form; + if (dcpId == null) { + + // create mode + form = getFloatingObjectService().preCreate(activityId); + + } else { + + // update mode + form = getFloatingObjectService().loadForm(dcpId); + + } + loadReferentialReferenceSetsInModel(form); + + getModel().setForm(form); + FloatingObjectDtos.copyFloatingObjectDto(form.getObject(), bean); + + // utilisation du mode requis + setContentMode(mode); + + if (mode != ContentMode.READ) { + getUi().startEdit(null); + } + } + + @Override + public void startEditUI(String... binding) { + ContentUIModel<FloatingObjectDto> contentUIModel = getModel(); + boolean create = contentUIModel.getMode() == ContentMode.CREATE; + String contextName = getValidatorContextName(contentUIModel.getMode()); + getUi().getValidator().setContext(contextName); + if (create) { + addMessage(getUi(), + NuitonValidatorScope.INFO, + getEntityLabel(FloatingObjectDto.class), + t("observe.content.floatingObject.message.creating")); + } else { + addMessage(getUi(), + NuitonValidatorScope.INFO, + getEntityLabel(FloatingObjectDto.class), + t("observe.content.floatingObject.message.updating")); + } + super.startEditUI(FloatingObjectUI.BINDING_DAYS_AT_SEA_COUNT_MODEL, + FloatingObjectUI.BINDING_OBJECT_TYPE_SELECTED_ITEM, + FloatingObjectUI.BINDING_OBJECT_FATE_SELECTED_ITEM, + FloatingObjectUI.BINDING_SUPPORT_VESSEL_NAME_TEXT, + FloatingObjectUI.BINDING_COMMENT2_TEXT); + contentUIModel.setModified(create); + } + + @Override + protected boolean doSave(FloatingObjectDto bean) throws Exception { + + String activityId = getSelectedParentId(); + + SaveResultDto saveResult = getFloatingObjectService().save(activityId, bean); + saveResult.toDto(bean); + + return true; + + } + + @Override + protected void afterSave(boolean refresh) { + super.afterSave(refresh); + FloatingObjectDto bean = getBean(); + + ObserveTreeHelper treeHelper = getTreeHelper(getUi()); + + ObserveNode node = treeHelper.getSelectedNode(); + boolean create = node.getId() == null; + + if (create) { + + getModel().setMode(ContentMode.UPDATE); + + // remove old node and recreate new node + ObserveNode parentNode = treeHelper.removeNode(node); + + DataReference<FloatingObjectDto> beanRef = ObserveSwingApplicationContext.get().getReferenceBinderEngine().transformDataDtoToReference(getDecoratorService().getReferentialLocale(), bean); + node = treeHelper.addFloatingObject(parentNode, beanRef); + stopEditUI(); + if (refresh) { + treeHelper.selectNode(node); + } + } else { + + // select ancestor node +// treeHelper.refreshNode(node, false); + treeHelper.reloadSelectedNode(false, false); + } + } + + @Override + protected boolean doDelete(FloatingObjectDto bean) { + + if (askToDelete(bean)) { + return false; + } + + if (bean.getId() != null) { + + String activityId = getSelectedParentId(); + getFloatingObjectService().delete(activityId, bean.getId()); + } + return true; + } + + protected FloatingObjectService getFloatingObjectService() { + return getDataSource().newFloatingObjectService(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectUIModel.java new file mode 100644 index 0000000..51782b9 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/FloatingObjectUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.seine.FloatingObjectDto; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class FloatingObjectUIModel extends ContentUIModel<FloatingObjectDto> { + + private static final long serialVersionUID = 1L; + + public FloatingObjectUIModel() { + super(FloatingObjectDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/SetSeineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/SetSeineUI.jaxx new file mode 100644 index 0000000..7bd31e0 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/SetSeineUI.jaxx @@ -0,0 +1,255 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ContentUI superGenericType='SetSeineDto' contentTitle='{n("observe.content.setSeine.title")}'> + + <import> + fr.ird.observe.services.dto.CommentableDto + fr.ird.observe.services.dto.seine.SetSeineDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.seine.ReasonForNullSetDto + fr.ird.observe.application.swing.ui.actions.shared.CancelCreateUIAction + fr.ird.observe.application.swing.ui.actions.shared.DeleteDataUIAction + fr.ird.observe.application.swing.ui.actions.shared.ResetEditUIAction + fr.ird.observe.application.swing.ui.actions.shared.SaveEditUIAction + fr.ird.observe.application.swing.ui.util.BooleanEditor + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + org.nuiton.jaxx.widgets.datetime.DateTimeEditor + + org.jdesktop.swingx.JXDatePicker + + java.awt.Dimension + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <style source="../../Common.jcss"/> + + <!-- handler --> + <SetSeineUIHandler id='handler'/> + + <!-- model --> + <SetSeineUIModel id='model'/> + + <!-- edit bean --> + <SetSeineDto id='bean'/> + + <!-- validator --> + <BeanValidator id='validator' + autoField='true' + beanClass='fr.ird.observe.services.dto.seine.SetSeineDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update'> + </BeanValidator> + + <!-- formulaire --> + <JPanel id="body" layout='{new BorderLayout()}'> + <Table insets="0" fill="both" constraints='BorderLayout.CENTER'> + <row> + <cell anchor="north" weightx="1"> + <JTabbedPane id='fishingOperationTabPane'> + <tab id='generalTab'> + <Table fill="both"> + <row> + <cell weightx="1" columns="2"> + <DateTimeEditor id='startTime' constructorParams='this'/> + </cell> + </row> + <row> + <cell weightx="1" columns="2"> + <DateTimeEditor id='endPursingTimeStamp' constructorParams='this'/> + </cell> + </row> + <row> + <cell weightx="1" columns="2"> + <DateTimeEditor id='endSetTimeStamp' constructorParams='this'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='reasonForNullSetLabel'/> + </cell> + <cell anchor='east' fill='both'> + <BeanComboBox id='reasonForNullSet' genericType='ReferentialReference<ReasonForNullSetDto>' _entityClass='ReasonForNullSetDto.class' constructorParams='this'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='supportVesselNameLabel'/> + </cell> + <cell anchor='east' fill="both"> + <JPanel layout='{new BorderLayout()}'> + <JToolBar id='supportVesselNameToolbar' constraints='BorderLayout.WEST'> + <JButton id='resetSupportVesselName' constraints='BorderLayout.WEST' styleClass='resetButton'/> + </JToolBar> + <JTextField id='supportVesselName' constraints='BorderLayout.CENTER'/> + </JPanel> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='targetDiscardedLabel'/> + </cell> + <cell anchor='east' fill="both"> + <BooleanEditor id='targetDiscarded'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='nonTargetDiscardedLabel'/> + </cell> + <cell anchor='east' fill="both"> + <BooleanEditor id='nonTargetDiscarded'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='schoolTypeLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JLabel id="schoolType"/> + </cell> + </row> + </Table> + </tab> + <tab id='measurementsTab'> + <Table fill="both" weightx="1"> + <row> + <cell columns='2'> + <Table id='sonarUsedAvantSetPane'> + <row> + <cell anchor='west'> + <JLabel id='schoolThicknessLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <NumberEditor id='schoolThickness' constructorParams='this'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='schoolMeanDepthLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <NumberEditor id='schoolMeanDepth' constructorParams='this'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='schoolTopDepthLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <NumberEditor id='schoolTopDepth' constructorParams='this'/> + </cell> + </row> + </Table> + </cell> + </row> + + <row> + <cell columns='2'> + <Table> + <row> + <cell anchor='west'> + <JLabel id='currentSpeedLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <NumberEditor id='currentSpeed' constructorParams='this'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='currentDirectionLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <NumberEditor id='currentDirection' constructorParams='this'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='currentMeasureDepthLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <NumberEditor id='currentMeasureDepth' constructorParams='this'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='maxGearDepthLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <NumberEditor id='maxGearDepth' constructorParams='this'/> + </cell> + </row> + <row> + <cell columns='2' anchor="west"> + <JCheckBox id='sonarUsed'/> + </cell> + </row> + </Table> + </cell> + </row> + + <row> + <cell columns="2" weighty="1"> + <JLabel/> + </cell> + </row> + </Table> + </tab> + + </JTabbedPane> + </cell> + </row> + + <row> + <cell columns='2' fill="both" weighty="1"> + <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2'/> + </JScrollPane> + </cell> + </row> + </Table> + </JPanel> + + <!-- actions --> + <Table id="actions" fill='both' weightx='1' insets='0'> + <row> + <cell weightx="0.5" fill="both"> + <JButton id='cancel'/> + </cell> + <cell weightx="0.5"> + <JButton id='reset'/> + </cell> + <cell weightx="0.5"> + <JButton id='save'/> + </cell> + <cell weightx="0.5"> + <JButton id='delete'/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/SetSeineUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/SetSeineUI.jcss new file mode 100644 index 0000000..510232c --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/SetSeineUI.jcss @@ -0,0 +1,226 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#model { + editable:true; + modified:{validator.isChanged()}; + valid:{validator.isValid()}; + enabled:{!model.isReadingMode()}; +} + +#generalTab { + title:{t("observe.content.setSeine.tab.general")}; + icon:{getHandler().getErrorIconIfFalse(model.isGeneralTabValid())}; +} + +#measurementsTab { + title:{t("observe.content.setSeine.tab.measurements")}; + icon:{getHandler().getErrorIconIfFalse(model.isMeasurementsTabValid())}; +} + +#startTime { + propertyDate:{SetSeineDto.PROPERTY_START_TIME}; + label:{t("observe.content.setSeine.startTime")}; + date:{bean.getStartTime()}; + dateEditable:false; + _validatorLabel:{"observe.content.setSeine.startTime"}; +} + +#endPursingTimeStamp { + propertyDate: {SetSeineDto.PROPERTY_END_PURSING_TIME_STAMP}; + propertyDayDate: {SetSeineDto.PROPERTY_END_PURSING_DATE}; + propertyTimeDate: {SetSeineDto.PROPERTY_END_PURSING_TIME}; + label:{t("observe.content.setSeine.endPursingTimeStamp")}; + date:{bean.getEndPursingTimeStamp()}; + _validatorLabel:{t("observe.content.setSeine.endPursingTimeStamp")}; +} + +#endSetTimeStamp { + propertyDate: {SetSeineDto.PROPERTY_END_SET_TIME_STAMP}; + propertyDayDate: {SetSeineDto.PROPERTY_END_SET_DATE}; + propertyTimeDate: {SetSeineDto.PROPERTY_END_SET_TIME}; + label:{t("observe.content.setSeine.endSetTimeStamp")}; + date:{bean.getEndSetTimeStamp()}; + _validatorLabel:{t("observe.content.setSeine.endSetTimeStamp")}; +} + +#reasonForNullSetLabel { + text:"observe.content.setSeine.reasonForNullSet"; + labelFor:{reasonForNullSet}; +} + +#reasonForNullSet { + property:{SetSeineDto.PROPERTY_REASON_FOR_NULL_SET}; + selectedItem:{bean.getReasonForNullSet()}; + _validatorLabel:{t("observe.content.setSeine.reasonForNullSet")}; +} + +#supportVesselNameLabel { + text:"observe.content.setSeine.supportVesselName"; + labelFor:{supportVesselName}; +} + +#supportVesselName { + _propertyName:{SetSeineDto.PROPERTY_SUPPORT_VESSEL_NAME}; + text:{getStringValue(bean.getSupportVesselName())}; + _validatorLabel:{t("observe.content.setSeine.supportVesselName")}; +} + +#resetSupportVesselName{ + toolTipText:"observe.content.action.reset.supportVesselName.tip"; + _resetPropertyName:{SetSeineDto.PROPERTY_SUPPORT_VESSEL_NAME}; +} + +#targetDiscardedLabel { + text:"observe.content.setSeine.targetDiscarded"; + labelFor:{targetDiscarded}; +} + +#targetDiscarded { + _propertyName:{SetSeineDto.PROPERTY_TARGET_DISCARDED}; + booleanValue:{bean.getTargetDiscarded()}; + _validatorLabel:{t("observe.content.setSeine.targetDiscarded")}; +} + +#nonTargetDiscardedLabel { + text:"observe.content.setSeine.nonTargetDiscarded"; + labelFor:{nonTargetDiscarded}; +} + +#nonTargetDiscarded { + _propertyName:{SetSeineDto.PROPERTY_NON_TARGET_DISCARDED}; + booleanValue:{bean.getNonTargetDiscarded()}; + _validatorLabel:{t("observe.content.setSeine.nonTargetDiscarded")}; +} + +#schoolTypeLabel { + actionIcon:information; + text:"observe.content.setSeine.schoolType"; + toolTipText:"observe.content.setSeine.message.information.schoolType"; + labelFor:{schoolType}; +} + +#schoolType { + font-weight:bold; + text:{getHandler().updateTypeValue(bean.getSchoolType())}; + _validatorLabel:{t("observe.content.setSeine.schoolType")}; +} + +#sonarUsedAvantSetPane { + border:{new TitledBorder(null, t("observe.content.setSeine.sonarUsedAvantSet", 1, 0, getFont()))}; +} + +#schoolThicknessLabel { + text:"observe.content.setSeine.schoolThickness"; + labelFor:{schoolThickness}; +} + +#schoolThickness { + property:{SetSeineDto.PROPERTY_SCHOOL_THICKNESS}; + model:{bean.getSchoolThickness()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.setSeine.schoolThickness")}; +} + +#schoolMeanDepthLabel { + text:"observe.content.setSeine.schoolMeanDepth"; + labelFor:{schoolMeanDepth}; +} + +#schoolMeanDepth { + property:{SetSeineDto.PROPERTY_SCHOOL_MEAN_DEPTH}; + model:{bean.getSchoolMeanDepth()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.setSeine.schoolMeanDepth")}; +} + +#schoolTopDepthLabel { + text:"observe.content.setSeine.schoolTopDepth"; + labelFor:{schoolTopDepth}; +} + +#schoolTopDepth { + property:{SetSeineDto.PROPERTY_SCHOOL_TOP_DEPTH}; + model:{bean.getSchoolTopDepth()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.setSeine.schoolTopDepth")}; +} + +#currentMeasureDepthLabel { + text:"observe.content.setSeine.currentMeasureDepth"; + labelFor:{currentMeasureDepth}; +} + +#currentMeasureDepth { + property:{SetSeineDto.PROPERTY_CURRENT_MEASURE_DEPTH}; + model:{bean.getCurrentMeasureDepth()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.setSeine.currentMeasureDepth")}; +} + +#currentSpeedLabel { + text:"observe.content.setSeine.currentSpeed"; + labelFor:{currentSpeed}; +} + +#currentSpeed { + property:{SetSeineDto.PROPERTY_CURRENT_SPEED}; + model:{bean.getCurrentSpeed()}; + useFloat:true; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL1_PATTERN}; + _validatorLabel:{t("observe.content.setSeine.currentSpeed")}; +} + +#currentDirectionLabel { + text:"observe.content.setSeine.currentDirection"; + labelFor:{currentDirection}; +} + +#currentDirection { + property:{SetSeineDto.PROPERTY_CURRENT_DIRECTION}; + model:{bean.getCurrentDirection()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_3_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.setSeine.currentDirection")}; +} + +#maxGearDepthLabel { + text:"observe.content.setSeine.maxGearDepth"; + labelFor:{maxGearDepth}; +} + +#maxGearDepth { + property:{SetSeineDto.PROPERTY_MAX_GEAR_DEPTH}; + model:{bean.getMaxGearDepth()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.setSeine.maxGearDepth")}; +} + +#sonarUsed { + _propertyName:{SetSeineDto.PROPERTY_SONAR_USED}; + text:"observe.content.setSeine.sonarUsed"; + selected:{bean.isSonarUsed()}; + _validatorLabel:{t("observe.content.setSeine.sonarUsed")}; +} + +#delete { + _toolTipText:{t("observe.action.delete.set.tip")}; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/SetSeineUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/SetSeineUIHandler.java new file mode 100644 index 0000000..afa82ab --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/SetSeineUIHandler.java @@ -0,0 +1,345 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.impl.seine; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.constants.seine.SchoolType; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.services.dto.seine.SetSeineDto; +import fr.ird.observe.services.dto.seine.SetSeineDtos; +import fr.ird.observe.services.service.seine.RouteService; +import fr.ird.observe.services.service.seine.SetSeineService; +import fr.ird.observe.services.util.I18nEnumUtil; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.ContentUIHandler; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import jaxx.runtime.swing.HidorButton; +import jaxx.runtime.validator.swing.SwingValidatorMessage; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; +import jaxx.runtime.validator.swing.SwingValidatorUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.util.DateUtil; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.event.TableModelListener; +import java.beans.PropertyChangeListener; +import java.util.Date; +import java.util.HashSet; +import java.util.Set; + +import static org.nuiton.i18n.I18n.t; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class SetSeineUIHandler extends ContentUIHandler<SetSeineDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(SetSeineUIHandler.class); + + // Compute valid state of tab from the error table + protected final TableModelListener computeTabValidStateListener; + + // Change toogle target visible on all TimeEditors + protected final PropertyChangeListener onToogleTimeEditorSliderChangedListener; + + protected boolean toogleTimeEditorSliderIsChanging; + + public SetSeineUIHandler(SetSeineUI ui) { + super(ui, DataContextType.ActivitySeine, DataContextType.SetSeine); + computeTabValidStateListener = e -> { + + SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); + computeTabValidState(source); + + }; + onToogleTimeEditorSliderChangedListener = evt -> { + Boolean newValue = (Boolean) evt.getNewValue(); + onToogleTimeEditorSliderChanged(newValue); + }; + } + + @Override + public SetSeineUI getUi() { + return (SetSeineUI) super.getUi(); + } + + public String updateTypeValue(SchoolType schoolType) { + if (schoolType == null) { + return t("observe.content.setSeine.schoolType.not.fill"); + } + return I18nEnumUtil.getLabel(schoolType); + } + + @Override + protected boolean computeCanWrite(ObserveSwingDataSource source) { + return source.canWriteData(); + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + String setId = getSelectedId(); + + if (setId == null) { + + // mode creation + return ContentMode.CREATE; + } + + if (getOpenDataManager().isOpenActivitySeine(dataContext.getSelectedActivitySeineId())) { + + // l'activity est ouverte, mode édition + return ContentMode.UPDATE; + } + + // l'activity n'est pas ouverte, mode lecture + addMessage(getUi(), + NuitonValidatorScope.INFO, + getEntityLabel(ActivitySeineDto.class), + t("observe.storage.activitySeine.message.not.open")); + return ContentMode.READ; + } + + @Override + public void initUI() { + + super.initUI(); + + // To be sure always remove listener (could prevent some leaks) + getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); + // listen messages to see if required to add + getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); + + getUi().getStartTime().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); + getUi().getEndPursingTimeStamp().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); + getUi().getEndSetTimeStamp().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); + + } + + @Override + public void openUI() { + super.openUI(); + + String activityId = getSelectedParentId(); + String setId = getSelectedId(); + String selectedRouteId = getDataContext().getSelectedRouteId(); + + if (log.isInfoEnabled()) { + log.info("activityId = " + activityId); + log.info("setId = " + setId); + } + ContentMode mode = computeContentMode(); + + SetSeineDto bean = getBean(); + + Form<SetSeineDto> form; + if (setId == null) { + + // create mode + form = getSetSeineService().preCreate(selectedRouteId, activityId); + + } else { + + // update mode + form = getSetSeineService().loadForm(setId); + + } + + // utilisation du mode requis + setContentMode(mode); + + loadReferentialReferenceSetsInModel(form); + + getModel().setForm(form); + SetSeineDtos.copySetSeineDto(form.getObject(), bean); + + RouteService routeService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newRouteService(); + + RouteDto route = routeService.loadDto(selectedRouteId); + + Date time = bean.getStartTime(); + + Date date = route.getDate(); + + Date dateAndTime = DateUtil.getDateAndTime(date, time, false, false); + + getUi().getStartTime().setDate(dateAndTime); + + SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); + computeTabValidState(errorTableModel); + + if (mode != ContentMode.READ) { + getUi().startEdit(null); + } + } + + @Override + public void startEditUI(String... binding) { + ContentUIModel<SetSeineDto> model = getModel(); + boolean create = model.getMode() == ContentMode.CREATE; + String contextName = getValidatorContextName(model.getMode()); + getUi().getValidator().setContext(contextName); + if (create) { + addInfoMessage(t("observe.content.setSeine.message.creating")); + } else { + addInfoMessage(t("observe.content.setSeine.message.updating")); + } + + super.startEditUI(SetSeineUI.BINDING_SUPPORT_VESSEL_NAME_TEXT, + SetSeineUI.BINDING_COMMENT2_TEXT, + SetSeineUI.BINDING_START_TIME_DATE, + SetSeineUI.BINDING_END_SET_TIME_STAMP_DATE, + SetSeineUI.BINDING_END_SET_TIME_STAMP_DATE, + SetSeineUI.BINDING_END_PURSING_TIME_STAMP_DATE, + SetSeineUI.BINDING_CURRENT_SPEED_MODEL, + SetSeineUI.BINDING_CURRENT_DIRECTION_MODEL, + SetSeineUI.BINDING_REASON_FOR_NULL_SET_SELECTED_ITEM, + SetSeineUI.BINDING_SONAR_USED_SELECTED, + SetSeineUI.BINDING_CURRENT_SPEED_MODEL, + SetSeineUI.BINDING_NON_TARGET_DISCARDED_BOOLEAN_VALUE, + SetSeineUI.BINDING_TARGET_DISCARDED_BOOLEAN_VALUE, + SetSeineUI.BINDING_SCHOOL_THICKNESS_MODEL, + SetSeineUI.BINDING_SCHOOL_TYPE_TEXT, + SetSeineUI.BINDING_MAX_GEAR_DEPTH_MODEL, + SetSeineUI.BINDING_SCHOOL_MEAN_DEPTH_MODEL, + SetSeineUI.BINDING_SCHOOL_TOP_DEPTH_MODEL); + model.setModified(create); + } + + @Override + protected boolean doSave(SetSeineDto bean) throws Exception { + + String activityId = getSelectedParentId(); + + SaveResultDto saveResult = getSetSeineService().save(activityId, bean); + saveResult.toDto(bean); + + return true; + } + + @Override + protected void afterSave(boolean refresh) { + + super.afterSave(refresh); + + SetSeineDto bean = getBean(); + + SwingValidatorUtil.setValidatorChanged(getUi(), false); + + ObserveTreeHelper treeHelper = getTreeHelper(getUi()); + + ObserveNode node = treeHelper.getSelectedNode(); + boolean create = node.getId() == null; + + if (create) { + getModel().setMode(ContentMode.UPDATE); + + // remove old node and recreate new node + ObserveNode parentNode = treeHelper.removeNode(node); + + DataReference<SetSeineDto> beanRef = ObserveSwingApplicationContext.get().getReferenceBinderEngine().transformDataDtoToReference(getDecoratorService().getReferentialLocale(), bean); + node = treeHelper.addSetSeine(parentNode, beanRef); + + stopEditUI(); + treeHelper.selectNode(node); + } else { + // select ancestor node +// treeHelper.refreshNode(node, false); + treeHelper.reloadSelectedNode(false, false); + } + } + + protected boolean doDelete(SetSeineDto bean) { + + if (askToDelete(bean)) { + return false; + } + + String activityId = getSelectedParentId(); + getSetSeineService().delete(activityId, bean.getId()); + return true; + } + + protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { + + Set<String> errorProperties = new HashSet<>(); + int rowCount = errorTableModel.getRowCount(); + for (int i = 0; i < rowCount; i++) { + + SwingValidatorMessage row = errorTableModel.getRow(i); + if (NuitonValidatorScope.ERROR.equals(row.getScope())) { + errorProperties.add(row.getField()); + } + } + + boolean generalTabValid = !errorProperties.removeAll(SetSeineUIModel.GENERAL_TAB_PROPERTIES); + boolean measurementsTabValid = !errorProperties.removeAll(SetSeineUIModel.MEASUREMENTS_TAB_PROPERTIES); + + SetSeineUIModel model = (SetSeineUIModel) getModel(); + model.setGeneralTabValid(generalTabValid); + model.setMeasurementsTabValid(measurementsTabValid); + + } + + protected void onToogleTimeEditorSliderChanged(boolean newValue) { + + if (!toogleTimeEditorSliderIsChanging) { + + toogleTimeEditorSliderIsChanging = true; + + try { + + getUi().getStartTime().getSliderHidor().setSelected(!newValue); + getUi().getStartTime().getSliderHidor().setTargetVisible(newValue); + + getUi().getEndPursingTimeStamp().getSliderHidor().setSelected(!newValue); + getUi().getEndPursingTimeStamp().getSliderHidor().setTargetVisible(newValue); + + getUi().getEndSetTimeStamp().getSliderHidor().setSelected(!newValue); + getUi().getEndSetTimeStamp().getSliderHidor().setTargetVisible(newValue); + + } finally { + + toogleTimeEditorSliderIsChanging = false; + + } + + } + + } + + protected SetSeineService getSetSeineService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newSetSeineService(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/SetSeineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/SetSeineUIModel.java new file mode 100644 index 0000000..262b97e --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/SetSeineUIModel.java @@ -0,0 +1,94 @@ +package fr.ird.observe.application.swing.ui.content.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.ImmutableSet; +import fr.ird.observe.services.dto.seine.SetSeineDto; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; + +import java.util.Set; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class SetSeineUIModel extends ContentUIModel<SetSeineDto> { + + public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; + + public static final String PROPERTY_MEASUREMENTS_TAB_VALID = "measurementsTabValid"; + + public static final Set<String> GENERAL_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(SetSeineDto.PROPERTY_START_TIME, + SetSeineDto.PROPERTY_END_PURSING_TIME_STAMP, + SetSeineDto.PROPERTY_END_SET_TIME_STAMP, + SetSeineDto.PROPERTY_REASON_FOR_NULL_SET, + SetSeineDto.PROPERTY_SUPPORT_VESSEL_NAME, + SetSeineDto.PROPERTY_TARGET_DISCARDED, + SetSeineDto.PROPERTY_NON_TARGET_DISCARDED, + SetSeineDto.PROPERTY_SCHOOL_TYPE).build(); + + public static final Set<String> MEASUREMENTS_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(SetSeineDto.PROPERTY_SCHOOL_THICKNESS, + SetSeineDto.PROPERTY_SCHOOL_MEAN_DEPTH, + SetSeineDto.PROPERTY_SCHOOL_TOP_DEPTH, + SetSeineDto.PROPERTY_CURRENT_SPEED, + SetSeineDto.PROPERTY_CURRENT_DIRECTION, + SetSeineDto.PROPERTY_CURRENT_MEASURE_DEPTH, + SetSeineDto.PROPERTY_MAX_GEAR_DEPTH, + SetSeineDto.PROPERTY_SONAR_USED).build(); + + private static final long serialVersionUID = 1L; + + protected boolean generalTabValid; + + protected boolean measurementsTabValid; + + + public SetSeineUIModel() { + super(SetSeineDto.class); + } + + public boolean isMeasurementsTabValid() { + return measurementsTabValid; + } + + public void setMeasurementsTabValid(boolean measurementsTabValid) { + Object oldValue = isMeasurementsTabValid(); + this.measurementsTabValid = measurementsTabValid; + firePropertyChange(PROPERTY_MEASUREMENTS_TAB_VALID, oldValue, measurementsTabValid); + } + + public boolean isGeneralTabValid() { + return generalTabValid; + } + + public void setGeneralTabValid(boolean generalTabValid) { + Object oldValue = isGeneralTabValid(); + this.generalTabValid = generalTabValid; + firePropertyChange(PROPERTY_GENERAL_TAB_VALID, oldValue, generalTabValid); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/package.html b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/package.html similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/package.html rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/impl/seine/package.html diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/ContentListUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/ContentListUI.jaxx new file mode 100644 index 0000000..730faf5 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/ContentListUI.jaxx @@ -0,0 +1,119 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ContentUI + abstract='true' + superGenericType='E' + genericType='E extends IdDto, C extends DataDto'> + + <import> + fr.ird.observe.application.swing.ui.actions.shared.ReOpenUIAction + fr.ird.observe.application.swing.ui.actions.shared.SelectNodeUIAction + + fr.ird.observe.services.dto.IdDto + fr.ird.observe.services.dto.DataDto + fr.ird.observe.services.dto.DataReference + + jaxx.runtime.swing.editor.bean.BeanListHeader + + java.awt.Dimension + + javax.swing.DefaultListSelectionModel + javax.swing.ListSelectionModel + + java.util.List + + static org.nuiton.i18n.I18n.t + </import> + <java.lang.String id='listText' javaBean='""'/> + + <java.lang.String id='emptyListMessage' javaBean='""'/> + + <ContentListUIModel id='model' genericType='E, C'/> + + <ListSelectionModel id='listSelectionModel' + initializer='new DefaultListSelectionModel()' + onValueChanged='if (!event.getValueIsAdjusting()) getModel().setSelectedDatas(getSelectedDatas());'/> + + <ContentListUIHandler id='handler' genericType='E, C'/> + + <script><![CDATA[ + +public final DataReference<C> getSelectedData() { + return (DataReference<C>) getSelectedBean(list); +} + +public final List<DataReference<C>> getSelectedDatas() { + return (List<DataReference<C>>) list.getSelectedValuesList(); +} + +]]></script> + + <JPanel id='body'> + + <JScrollPane id='listPane' constraints='BorderLayout.CENTER' + onFocusGained='list.requestFocus()' + columnHeaderView='{listHeader}'> + + <JList id='list' onMouseClicked='getHandler().onDataSelected(event)'/> + + <BeanListHeader id='listHeader' genericType='DataReference< C >' _entityClass="getModel().getChildType()"/> + + </JScrollPane> + + </JPanel> + + <Table id="actions" fill='both' weightx='1' insets='0'> + <row> + <cell fill='both' columns="3"> + <JButton id='gotoSelectedChild'/> + </cell> + </row> + <row> + <cell fill='both' columns="3"> + <JButton id='reopenChild'/> + </cell> + </row> + <row weighty="1" weightx="1" fill="both"> + <cell> + <JButton id='gotoOpenChild'/> + </cell> + <cell> + <JButton id='gotoOpenChild2'/> + </cell> + <cell> + <JButton id='createChild' onActionPerformed='getHandler().addChild()'/> + </cell> + </row> + <row> + <cell fill="both" columns="3"> + <Table id='extraActions' fill="both" weightx="1" insets='2'/> + </cell> + </row> + <row> + <cell fill='both' columns="3"> + <JButton id='moveSelectedChildren'/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/ContentListUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/ContentListUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/ContentListUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/ContentListUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/ContentListUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/ContentListUIHandler.java new file mode 100644 index 0000000..9eba5a6 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/ContentListUIHandler.java @@ -0,0 +1,283 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.list; + +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.AbstractReference; +import fr.ird.observe.services.dto.DataDto; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.application.swing.ui.actions.shared.SelectNodeUIAction; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.ContentUIHandler; +import fr.ird.observe.application.swing.ui.tree.AbstractObserveTreeCellRenderer; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import jaxx.runtime.swing.editor.bean.BeanListHeader; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.DefaultListCellRenderer; +import javax.swing.Icon; +import javax.swing.JButton; +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.ListCellRenderer; +import java.awt.Color; +import java.awt.Component; +import java.awt.event.MouseEvent; +import java.util.List; + +import static org.nuiton.i18n.I18n.t; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.5 + */ +public abstract class ContentListUIHandler<E extends IdDto, C extends DataDto> extends ContentUIHandler<E> { + + /** Logger */ + private static final Log log = LogFactory.getLog(ContentListUIHandler.class); + + public ContentListUIHandler(ContentListUI<E, C> ui, + DataContextType parentType, + DataContextType type) { + super(ui, parentType, type); + } + + /** + * Obtain the list of entities to display on ui from his container + * {@code bean}. + * + * @param parentId the parent id of entities to display + * @return the list of entities to display + */ + protected abstract List<DataReference<C>> getChilds(String parentId); + + @Override + protected boolean computeCanWrite(ObserveSwingDataSource source) { + return source.canWriteData(); + } + + @Override + public ContentListUI<E, C> getUi() { + return (ContentListUI<E, C>) super.getUi(); + } + + @Override + public final ContentListUIModel<E, C> getModel() { + return (ContentListUIModel<E, C>) super.getModel(); + } + + @Override + public void initUI() { + super.initUI(); + + // on installe un renderer sur la liste pour afficher les couleurs + + // icones comme dans l'arbre + ListCellRenderer renderer = getUi().getList().getCellRenderer(); + ObserveTreeHelper treeHelper = getTreeHelper(getUi()); + + ListCellRenderer renderer2 = new EntityListCellRenderer(renderer, treeHelper); + + getUi().getList().setCellRenderer(renderer2); + } + + @Override + public final void openUI() { + + super.openUI(); + + // init renderer + EntityListCellRenderer renderer = (EntityListCellRenderer) + getUi().getList().getCellRenderer(); + renderer.init(); + + ContentListUIModel<E, C> model = getModel(); + + String selectedId = getSelectedParentId(); + + if (log.isInfoEnabled()) { + log.info(prefix + "selectedId = " + selectedId); + } + + ContentMode mode = computeContentMode(); + + if (log.isInfoEnabled()) { + log.info(prefix + "content mode = " + mode); + } + + // We want to force the bindings on "mode" to be triggered each time we open a list ui. + // + // The ui mode can already be set to the mode we're currently applying now. + // As the state of the buttons is bound to that mode, + // we need to force a mode change to ensure the buttons state will be refreshed. + // + // For example : + // The button of the activities list of a route "Go to the open activity of another road" may need to disapear + // because that road has just been deleted.. + // + // As the ui state of the buttons is usually only bound to the mode of the model + // and as the state of those buttons usually not only depends on that mode (but also on attributes of the data context for instance, such as a route/activity/trip is open or not), + // we need to force the buttons to recompute their state by forcing the mode's listeners to be triggered. + model.setMode(null); + model.setMode(mode); + + boolean canReopen = mode == ContentMode.CREATE; + if (log.isInfoEnabled()) { + log.info(prefix + "canReopen = " + canReopen); + } + model.setCanReopen(canReopen); + + // il n'est pas nécessaire de charger le bean car seuls ses enfants nous sont utile dans cette ecran + + List<DataReference<C>> data = getChilds(getSelectedParentId()); + + model.setData(data); + + if (!model.isEmpty()) { + + // select first data + getUi().getListSelectionModel().setSelectionInterval(0, 0); + + } + + // finalize openUI with specified code + finalizeOpenUI(); + } + + public void addChild() { + addChild(getModel().getChildType()); + } + + /** + * When a data has been selected in the list. + * + * @param event the mouse event fired + */ + public void onDataSelected(MouseEvent event) { + DataReference<C> selectedData = getUi().getSelectedData(); + if (event.getClickCount() > 1) { + gotoChild(selectedData); + return; + } + ObserveNode node = null; + if (selectedData != null) { + + // obtain the node corresponding to the selected data + String id = selectedData.getId(); + ObserveTreeHelper helper = getTreeHelper(getUi()); + ObserveNode selectedNode = helper.getSelectedNode(); + node = helper.findNode(selectedNode, id); + } + + // attach the node to action + JButton button = getUi().getGotoSelectedChild(); + button.putClientProperty(SelectNodeUIAction.NODE, node); + } + + public <E> List<E> updateList(BeanListHeader<E> list, List<E> data) { + String message = t(getUi().getEmptyListMessage()); + return updateList(list, data, message); + } + + /** + * Pour effectuer un traitement supplémantaire à la fin de la méthode + * {@link #openUI()}. + */ + protected void finalizeOpenUI() { + // rien par default + } + + /** + * Un renderer de liste d'entité qui reprendre la cosmétique de l'arbre + * de navigation. + * + * @since 1.5 + */ + private static class EntityListCellRenderer extends DefaultListCellRenderer { + + private static final long serialVersionUID = 1L; + + protected final transient ListCellRenderer delegate; + + protected final transient ObserveTreeHelper treeHelper; + + protected final AbstractObserveTreeCellRenderer treeRenderer; + + protected ObserveNode containerNode; + + public EntityListCellRenderer(ListCellRenderer delegate, + ObserveTreeHelper treeHelper) { + this.delegate = delegate; + this.treeHelper = treeHelper; + this.treeRenderer = treeHelper.getTreeCellRenderer(); + } + + public void init() { + containerNode = treeHelper.getSelectedNode(); + } + + @Override + public Component getListCellRendererComponent(JList list, + Object value, + int index, + boolean isSelected, + boolean cellHasFocus) { + + // obtain the text from the delegate renderer + JLabel comp = (JLabel) + delegate.getListCellRendererComponent(list, + value, + index, + isSelected, + cellHasFocus + ); + + if (value == null || + !(value instanceof AbstractReference) || + containerNode == null) { + + // rien de plus a faire + return comp; + } + + // recuperation du noeud correspondant dans l'arbre + ObserveNode node = + treeHelper.findNode(containerNode, ((AbstractReference) value).getId()); + + if (node == null) { + + // noeud non trouve (cela ne devrait jamais arrive + return comp; + } + + Icon icon = treeRenderer.getNavigationIcon(node); + comp.setIcon(icon); + Color color = treeRenderer.getNavigationTextColor(node); + comp.setForeground(color); + return comp; + } + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/ContentListUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/ContentListUIModel.java new file mode 100644 index 0000000..8e901c3 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/ContentListUIModel.java @@ -0,0 +1,134 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.list; + +import fr.ird.observe.services.dto.DataDto; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.List; + +/** + * Le modèle pour un écran d'édition avec des fils. + * + * @author Tony Chemit - chemit@codelutin.com + * @since .14 + */ +public abstract class ContentListUIModel<E extends IdDto, C extends DataDto> extends ContentUIModel<E> { + + public static final String PROPERTY_DATA = "data"; + + public static final String PROPERTY_SELECTED_DATAS = "selectedDatas"; + public static final String PROPERTY_ONE_SELECTED_DATA = "oneSelectedData"; + public static final String PROPERTY_ONE_OR_MORE_SELECTED_DATA = "oneOrMoreSelectedData"; + + public static final String PROPERTY_EMPTY = "empty"; + + public static final String PROPERTY_CAN_REOPEN = "canReopen"; + + private static final long serialVersionUID = 1L; + + /** Logger */ + static private final Log log = LogFactory.getLog(ContentListUIModel.class); + + /** type des entites */ + protected final Class<C> childType; + + /** liste des entites */ + protected List<DataReference<C>> data; + + /** entités sélectionnées dans la liste */ + protected List<DataReference<C>> selectedDatas; + + /** un drapeau pour savoir si on peut reouvrir l'un des données de la liste. */ + protected boolean canReopen; + + public ContentListUIModel(Class<E> beanType, Class<C> childType) { + super(beanType); + this.childType = childType; + } + + public Class<C> getChildType() { + return childType; + } + + public List<DataReference<C>> getData() { + return data; + } + + public void setData(List<DataReference<C>> data) { + boolean wasEmpty = isEmpty(); + this.data = data; + // on force toujours la propagation de la liste + firePropertyChange(PROPERTY_DATA, null, data); + firePropertyChange(PROPERTY_EMPTY, wasEmpty, isEmpty()); + setSelectedDatas(null); + } + + public DataReference<C> getSelectedData() { + return CollectionUtils.isNotEmpty(selectedDatas) ? selectedDatas.get(0) : null; + } + + public List<DataReference<C>> getSelectedDatas() { + return selectedDatas; + } + + public void setSelectedDatas(List<DataReference<C>> selectedDatas) { + boolean oldOneSelectedData = isOneSelectedData(); + boolean oldOneOrMoreSelectedData = isOneOrMoreSelectedData(); + List<DataReference<C>> old = getSelectedDatas(); + this.selectedDatas = selectedDatas; + if (log.isDebugEnabled()) { + log.debug("New selected datas : " + selectedDatas); + } + firePropertyChange(PROPERTY_SELECTED_DATAS, old, selectedDatas); + firePropertyChange(PROPERTY_ONE_SELECTED_DATA, oldOneSelectedData, isOneSelectedData()); + firePropertyChange(PROPERTY_ONE_OR_MORE_SELECTED_DATA, oldOneOrMoreSelectedData, isOneOrMoreSelectedData()); + } + + public boolean isOneSelectedData() { + return selectedDatas != null && selectedDatas.size() == 1; + } + + public boolean isOneOrMoreSelectedData() { + return CollectionUtils.isNotEmpty(selectedDatas ); + } + + public boolean isCanReopen() { + return canReopen; + } + + public void setCanReopen(boolean canReopen) { + boolean old = isCanReopen(); + this.canReopen = canReopen; + firePropertyChange(PROPERTY_CAN_REOPEN, old, canReopen); + } + + public boolean isEmpty() { + return data == null || data.isEmpty(); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/ActivityLonglinesUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/ActivityLonglinesUI.jaxx new file mode 100644 index 0000000..6ca6c37 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/ActivityLonglinesUI.jaxx @@ -0,0 +1,69 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.list.ContentListUI superGenericType='TripLonglineDto, ActivityLonglineDto' + contentTitle='{n("observe.storage.activityLonglines.title")}' listText='{n("observe.common.activities.list")}' + emptyListMessage='{n("observe.message.no.activity.for.trip")}'> + + <import> + fr.ird.observe.services.dto.longline.ActivityLonglineDto + fr.ird.observe.services.dto.longline.TripLonglineDto + fr.ird.observe.application.swing.ui.actions.shared.CloseAndCreateUIAction + fr.ird.observe.application.swing.ui.actions.shared.CloseOpenUIAction + fr.ird.observe.application.swing.ui.actions.shared.SelectOpenNodeUIAction + fr.ird.observe.application.swing.ui.actions.shared.MoveActivityLonglinesUIAction + + static org.nuiton.i18n.I18n.n + </import> + + <style source="CommonListUI.jcss"/> + + <!-- handler --> + <ActivityLonglinesUIHandler id='handler' constructorParams='this'/> + + <!-- model --> + <ActivityLonglinesUIModel id='model'/> + + <!-- edit bean --> + <TripLonglineDto id='bean'/> + + <!-- override generic actions --> + <JButton id='gotoSelectedChild'/> + <JButton id='reopenChild'/> + <JButton id='gotoOpenChild' styleClass='gotoOpenActivity'/> + <JButton id='gotoOpenChild2' styleClass='gotoOpenActivity2'/> + <JButton id='createChild'/> + <JButton id='moveSelectedChildren'/> + + <!-- extra actions --> + <Table id='extraActions' fill="both" weightx="1" insets='2'> + <row> + <cell weightx="0.5" fill="both"> + <JButton id='close'/> + </cell> + <cell weightx="0.5"> + <JButton id='closeAndCreate'/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.list.ContentListUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/ActivityLonglinesUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/ActivityLonglinesUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/ActivityLonglinesUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/ActivityLonglinesUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/ActivityLonglinesUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/ActivityLonglinesUIHandler.java new file mode 100644 index 0000000..0dee371 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/ActivityLonglinesUIHandler.java @@ -0,0 +1,126 @@ +package fr.ird.observe.application.swing.ui.content.list.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.DataReferenceSet; +import fr.ird.observe.services.dto.longline.ActivityLonglineDto; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.service.longline.ActivityLonglineService; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.list.ContentListUIHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.ArrayList; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; + +/** + * Created on 8/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.7 + */ +public class ActivityLonglinesUIHandler extends ContentListUIHandler<TripLonglineDto, ActivityLonglineDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(ActivityLonglinesUIHandler.class); + + public ActivityLonglinesUIHandler(ActivityLonglinesUI ui) { + super(ui, DataContextType.TripLongline, DataContextType.ActivityLongline); + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + String openTripLonglineId = dataContext.getOpenTripId(); + + if (openTripLonglineId == null) { + + // pas de marée ouverte, donc on ne peut pas ouvrir une activité + addInfoMessage(n("observe.content.tripLongline.message.no.active.found")); + return ContentMode.READ; + } + + // + // il existe une marée ouverte + // + + boolean openActivity = dataContext.isOpenActivity(); + + if (dataContext.isSelectedOpen(TripLonglineDto.class)) { + + // + // la marée courante est ouverte + // + + // l'activité courante est ouverte + if (openActivity) { + + // il existe une activite d'ouverte dans la maree courante + addInfoMessage(n("observe.storage.activityLongline.message.active.found")); + return ContentMode.UPDATE; + } + + // pas d'activité ouverte, on peut en ouvrir une + addInfoMessage(n("observe.storage.activityLongline.message.no.active.found")); + return ContentMode.CREATE; + } + + // + // la marée ouverte n'est pas la marée courante + // + + if (openActivity) { + + // il existe une activité ouverte dans la marée ouverte + addInfoMessage(n("observe.storage.activityLongline.message.active.found.for.other.trip")); + } else { + + // il n'existe pas d'activité ouverte dans la marée ouverte + addInfoMessage(n("observe.storage.activityLongline.message.no.active.found.for.other.trip")); + } + + return ContentMode.READ; + + } + + @Override + protected List<DataReference<ActivityLonglineDto>> getChilds(String parentId) { + + ActivityLonglineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivityLonglineService(); + DataReferenceSet<ActivityLonglineDto> activityLonglineStubByRoute = service.getActivityLonglineByTripLongline(parentId); + + if (log.isDebugEnabled()) { + log.debug("Will use " + activityLonglineStubByRoute.sizeReference() + " activities."); + } + + return new ArrayList<>(activityLonglineStubByRoute.getReferences()); + + } +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/ActivityLonglinesUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/ActivityLonglinesUIModel.java new file mode 100644 index 0000000..9d618d8 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/ActivityLonglinesUIModel.java @@ -0,0 +1,43 @@ +package fr.ird.observe.application.swing.ui.content.list.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.longline.ActivityLonglineDto; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.application.swing.ui.content.list.ContentListUIModel; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ActivityLonglinesUIModel extends ContentListUIModel<TripLonglineDto, ActivityLonglineDto> { + + private static final long serialVersionUID = 1L; + + public ActivityLonglinesUIModel() { + super(TripLonglineDto.class, ActivityLonglineDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/CommonListUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/CommonListUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/CommonListUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/CommonListUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/TripLonglinesUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/TripLonglinesUI.jaxx new file mode 100644 index 0000000..f58dc2c --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/TripLonglinesUI.jaxx @@ -0,0 +1,67 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.list.ContentListUI superGenericType='ProgramDto, TripLonglineDto' + listText='{n("observe.common.trips.list")}' + emptyListMessage='{n("observe.message.no.trip.for.program")}'> + + <import> + fr.ird.observe.services.dto.longline.ActivityLonglineDto + fr.ird.observe.services.dto.longline.TripLonglineDto + fr.ird.observe.services.dto.referential.ProgramDto + fr.ird.observe.application.swing.ui.actions.shared.SelectOpenNodeUIAction + fr.ird.observe.application.swing.ui.actions.shared.MoveTripLonglinesUIAction + + static org.nuiton.i18n.I18n.n + </import> + + <style source="CommonListUI.jcss"/> + + <!-- handler --> + <TripLonglinesUIHandler id='handler' constructorParams='this'/> + + <!-- model --> + <TripLonglinesUIModel id='model'/> + + <!-- edit bean --> + <ProgramDto id='bean'/> + + <!-- override generic actions --> + <JButton id='gotoSelectedChild'/> + <JButton id='reopenChild'/> + <JButton id='gotoOpenChild' styleClass='gotoOpenTrip'/> + <JButton id='gotoOpenChild2' styleClass='gotoOpenTrip2'/> + <JButton id='createChild'/> + <JButton id='moveSelectedChildren'/> + + <!-- extra actions --> + <Table id="extraActions" fill='both' weightx='1' weighty='1' insets='0'> + <row weighty="1" weightx="1"> + <cell> + <JButton id='gotoOpenActivity' styleClass='gotoOpenActivity'/> + </cell> + <cell> + <JButton id='gotoOpenActivity2' styleClass='gotoOpenActivity2'/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.list.ContentListUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/TripLonglinesUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/TripLonglinesUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/TripLonglinesUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/TripLonglinesUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/TripLonglinesUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/TripLonglinesUIHandler.java new file mode 100644 index 0000000..db65ed1 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/TripLonglinesUIHandler.java @@ -0,0 +1,112 @@ +package fr.ird.observe.application.swing.ui.content.list.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.DataReferenceSet; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.service.longline.TripLonglineService; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.list.ContentListUIHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.ArrayList; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; + +/** + * Created on 8/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.7 + */ +public class TripLonglinesUIHandler extends ContentListUIHandler<ProgramDto, TripLonglineDto> { + + /** Logger */ + static private final Log log = LogFactory.getLog(TripLonglinesUIHandler.class); + + public TripLonglinesUIHandler(TripLonglinesUI ui) { + super(ui, DataContextType.Program, DataContextType.TripLongline); + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + String openProgramId = dataContext.getOpenProgramId(); + + if (openProgramId == null) { + + // pas de program ouvert (donc pas de maree ouverte) + // on peut reouvrir une maree + addInfoMessage(n("observe.content.tripLongline.message.no.active.found")); + return ContentMode.CREATE; + } + + // + // il existe un maree ouverte + // + + if (dataContext.isSelectedOpen(ProgramDto.class)) { + + // le programme courant a une maree ouverte + addInfoMessage(n("observe.content.tripLongline.message.active.found")); + return ContentMode.UPDATE; + } + + // + // la marée ouverte est dans un autre programme + // + + addInfoMessage(n("observe.content.tripLongline.message.active.found.for.other.program")); + return ContentMode.READ; + } + + @Override + protected void finalizeOpenUI() { + Class referenceType = ProgramDto.class; + ReferentialReference<ProgramDto> programRef = getDataSource().getReferentialReference(referenceType, getSelectedParentId()); + String title = getDecoratorService().getReferentialReferenceDecorator(referenceType).toString(programRef); + getUi().setContentTitle(title); + } + + @Override + protected List<DataReference<TripLonglineDto>> getChilds(String parentId) { + + TripLonglineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripLonglineService(); + DataReferenceSet<TripLonglineDto> tripLonglineByProgram = service.getTripLonglineByProgram( parentId); + + if (log.isDebugEnabled()) { + log.debug("Will use " + tripLonglineByProgram.sizeReference() + " trips."); + } + + return new ArrayList<>(tripLonglineByProgram.getReferences()); + } +} + diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/TripLonglinesUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/TripLonglinesUIModel.java new file mode 100644 index 0000000..a071294 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/longline/TripLonglinesUIModel.java @@ -0,0 +1,51 @@ +package fr.ird.observe.application.swing.ui.content.list.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.application.swing.ui.content.list.ContentListUIModel; + +import java.util.List; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class TripLonglinesUIModel extends ContentListUIModel<ProgramDto, TripLonglineDto> { + + private static final long serialVersionUID = 1L; + + public TripLonglinesUIModel() { + super(ProgramDto.class, TripLonglineDto.class); + } + + @Override + public void setData(List<DataReference<TripLonglineDto>> data) { + super.setData(data); + setSelectedDatas(null); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/ActivitySeinesUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/ActivitySeinesUI.jaxx new file mode 100644 index 0000000..a8611f9 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/ActivitySeinesUI.jaxx @@ -0,0 +1,69 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.list.ContentListUI superGenericType='RouteDto, ActivitySeineDto' + contentTitle='{n("observe.storage.activitySeines.title")}' listText='{n("observe.common.activities.list")}' + emptyListMessage='{n("observe.message.no.activity.for.route")}'> + + <import> + fr.ird.observe.services.dto.seine.ActivitySeineDto + fr.ird.observe.services.dto.seine.RouteDto + fr.ird.observe.application.swing.ui.actions.shared.CloseAndCreateUIAction + fr.ird.observe.application.swing.ui.actions.shared.CloseOpenUIAction + fr.ird.observe.application.swing.ui.actions.shared.SelectOpenNodeUIAction + fr.ird.observe.application.swing.ui.actions.shared.MoveActivitySeinesUIAction + + static org.nuiton.i18n.I18n.n + </import> + + <style source="CommonListUI.jcss"/> + + <!-- handler --> + <ActivitySeinesUIHandler id='handler' constructorParams='this'/> + + <!-- model --> + <ActivitySeinesUIModel id='model'/> + + <!-- edit bean --> + <RouteDto id='bean'/> + + <!-- override generic actions --> + <JButton id='gotoSelectedChild'/> + <JButton id='reopenChild'/> + <JButton id='gotoOpenChild' styleClass='gotoOpenActivity'/> + <JButton id='gotoOpenChild2' styleClass='gotoOpenActivity2'/> + <JButton id='createChild'/> + <JButton id='moveSelectedChildren'/> + + <!-- extra actions --> + <Table id='extraActions' fill="both" weightx="1" insets='2'> + <row> + <cell weightx="0.5" fill="both"> + <JButton id='close'/> + </cell> + <cell weightx="0.5"> + <JButton id='closeAndCreate'/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.list.ContentListUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/ActivitySeinesUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/ActivitySeinesUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/ActivitySeinesUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/ActivitySeinesUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/ActivitySeinesUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/ActivitySeinesUIHandler.java new file mode 100644 index 0000000..bf2eeb0 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/ActivitySeinesUIHandler.java @@ -0,0 +1,123 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.list.impl.seine; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.DataReferenceSet; +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.services.service.seine.ActivitySeineService; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.list.ContentListUIHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.ArrayList; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class ActivitySeinesUIHandler extends ContentListUIHandler<RouteDto, ActivitySeineDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(ActivitySeinesUIHandler.class); + + public ActivitySeinesUIHandler(ActivitySeinesUI ui) { + super(ui, DataContextType.Route, DataContextType.ActivitySeine); + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + String openRouteId = dataContext.getOpenRouteId(); + + if (openRouteId == null) { + + // pas de route ouverte, donc on ne peut pas ouvrir une activité + addInfoMessage(n("observe.content.route.message.no.active.found")); + return ContentMode.READ; + } + + // + // il existe une route ouverte + // + + boolean openActivity = dataContext.isOpenActivity(); + + + if (dataContext.isSelectedOpen(RouteDto.class)) { + + // + // la route courante est ouverte + // + + // la route courante est ouverte + if (openActivity) { + + // il existe une activité ouverte dans la route courante + addInfoMessage(n("observe.storage.activitySeine.message.active.found")); + return ContentMode.UPDATE; + } + + // pas d'activité ouverte, on peut en ouvrir une + addInfoMessage(n("observe.storage.activitySeine.message.no.active.found")); + return ContentMode.CREATE; + } + + // + // la route ouverte est dans une autre maree + // + + if (openActivity) { + + // il existe une activité ouverte dans la route ouverte + addInfoMessage(n("observe.storage.activitySeine.message.active.found.for.other.route")); + } else { + + // il n'existe pas d'activité ouverte dans la route ouverte + addInfoMessage(n("observe.storage.activitySeine.message.no.active.found.for.other.route")); + } + + return ContentMode.READ; + + } + + @Override + protected List<DataReference<ActivitySeineDto>> getChilds(String parentId) { + + ActivitySeineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivitySeineService(); + DataReferenceSet<ActivitySeineDto> activitySeineByRoute = service.getActivitySeineByRoute(parentId); + + if (log.isDebugEnabled()) { + log.debug("Will use " + activitySeineByRoute.sizeReference() + " activities."); + } + + return new ArrayList<>(activitySeineByRoute.getReferences()); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/ActivitySeinesUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/ActivitySeinesUIModel.java new file mode 100644 index 0000000..c38e89b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/ActivitySeinesUIModel.java @@ -0,0 +1,43 @@ +package fr.ird.observe.application.swing.ui.content.list.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.application.swing.ui.content.list.ContentListUIModel; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ActivitySeinesUIModel extends ContentListUIModel<RouteDto, ActivitySeineDto> { + + private static final long serialVersionUID = 1L; + + public ActivitySeinesUIModel() { + super(RouteDto.class, ActivitySeineDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/CommonListUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/CommonListUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/CommonListUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/CommonListUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/RoutesUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/RoutesUI.jaxx new file mode 100644 index 0000000..d7aa5ef --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/RoutesUI.jaxx @@ -0,0 +1,68 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.list.ContentListUI superGenericType='TripSeineDto, RouteDto' + contentTitle='{n("observe.content.routes.title")}' listText='{n("observe.common.routes.list")}' + emptyListMessage='{n("observe.message.no.route.for.maree")}'> + + <import> + fr.ird.observe.services.dto.seine.ActivitySeineDto + fr.ird.observe.services.dto.seine.TripSeineDto + fr.ird.observe.services.dto.seine.RouteDto + fr.ird.observe.application.swing.ui.actions.shared.SelectOpenNodeUIAction + fr.ird.observe.application.swing.ui.actions.shared.MoveRoutesUIAction + + static org.nuiton.i18n.I18n.n + </import> + + <style source="CommonListUI.jcss"/> + + <!-- handler --> + <RoutesUIHandler id='handler' constructorParams='this'/> + + <!-- model --> + <RoutesUIModel id='model'/> + + <!-- edit bean --> + <TripSeineDto id='bean'/> + + <!-- override generic actions --> + <JButton id='gotoSelectedChild'/> + <JButton id='reopenChild'/> + <JButton id='gotoOpenChild' styleClass='gotoOpenRoute'/> + <JButton id='gotoOpenChild2' styleClass='gotoOpenRoute2'/> + <JButton id='createChild'/> + <JButton id='moveSelectedChildren'/> + + <!-- extra actions --> + <Table id='extraActions' fill="both" weightx="1" insets='2'> + <row weighty="1" weightx="1"> + <cell> + <JButton id='gotoOpenActivity' styleClass='gotoOpenActivity'/> + </cell> + <cell> + <JButton id='gotoOpenActivity2' styleClass='gotoOpenActivity2'/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.list.ContentListUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/RoutesUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/RoutesUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/RoutesUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/RoutesUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/RoutesUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/RoutesUIHandler.java new file mode 100644 index 0000000..dc884ee --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/RoutesUIHandler.java @@ -0,0 +1,121 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.list.impl.seine; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.DataReferenceSet; +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.services.service.seine.RouteService; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.list.ContentListUIHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.ArrayList; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class RoutesUIHandler extends ContentListUIHandler<TripSeineDto, RouteDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(RoutesUIHandler.class); + + public RoutesUIHandler(RoutesUI ui) { + super(ui, DataContextType.TripSeine, DataContextType.Route); + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + // autorisé à écrire + + String openTripId = dataContext.getOpenTripId(); + + if (openTripId == null) { + + // pas de marée d'ouverte, donc on ne peut pas ouvrir une route + addInfoMessage(n("observe.content.tripSeine.message.no.active.found")); + return ContentMode.READ; + } + + // + // il existe une marée ouverte + // + + boolean openRoute = dataContext.isOpenRoute(); + + if (dataContext.isSelectedOpen(TripSeineDto.class)) { + + // la marée courante est ouverte + + if (openRoute) { + + // il existe une route ouverte dans la marée courante + addInfoMessage(n("observe.content.route.message.active.found")); + return ContentMode.UPDATE; + } + + // pas de route ouverte, on peut en ouvrir une + addInfoMessage(n("observe.content.route.message.no.active.found")); + return ContentMode.CREATE; + } + + // + // la marée ouverte est dans un autre program + // + + if (openRoute) { + + //il existe une route existe dans la maree ouverte + addInfoMessage(n("observe.content.route.message.active.found.for.other.trip")); + } else { + + // pas de route ouverte dans la maree ouverte + addInfoMessage(n("observe.content.route.message.no.active.found.for.other.trip")); + } + + return ContentMode.READ; + } + + @Override + protected List<DataReference<RouteDto>> getChilds(String parentId) { + + RouteService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newRouteService(); + DataReferenceSet<RouteDto> routeByTripSeine = service.getRouteByTripSeine(parentId); + + if (log.isDebugEnabled()) { + log.debug("Will use " + routeByTripSeine.sizeReference() + " routes."); + } + + return new ArrayList<>(routeByTripSeine.getReferences()); + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/RoutesUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/RoutesUIModel.java new file mode 100644 index 0000000..2c3a069 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/RoutesUIModel.java @@ -0,0 +1,43 @@ +package fr.ird.observe.application.swing.ui.content.list.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.application.swing.ui.content.list.ContentListUIModel; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class RoutesUIModel extends ContentListUIModel<TripSeineDto, RouteDto> { + + private static final long serialVersionUID = 1L; + + public RoutesUIModel() { + super(TripSeineDto.class, RouteDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/TripSeinesUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/TripSeinesUI.jaxx new file mode 100644 index 0000000..a7375f0 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/TripSeinesUI.jaxx @@ -0,0 +1,77 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.list.ContentListUI + superGenericType='ProgramDto, TripSeineDto' + listText='{n("observe.common.trips.list")}' + emptyListMessage='{n("observe.message.no.trip.for.program")}'> + + <import> + fr.ird.observe.services.dto.seine.ActivitySeineDto + fr.ird.observe.services.dto.seine.TripSeineDto + fr.ird.observe.services.dto.seine.RouteDto + fr.ird.observe.services.dto.referential.ProgramDto + fr.ird.observe.application.swing.ui.actions.shared.SelectOpenNodeUIAction + fr.ird.observe.application.swing.ui.actions.shared.MoveTripSeinesUIAction + + static org.nuiton.i18n.I18n.n + </import> + + <style source="CommonListUI.jcss"/> + + <!-- handler --> + <TripSeinesUIHandler id='handler' constructorParams='this'/> + + <!-- model --> + <TripSeinesUIModel id='model'/> + + <!-- edit bean --> + <ProgramDto id='bean'/> + + <!-- override generic actions --> + <JButton id='gotoSelectedChild'/> + <JButton id='reopenChild'/> + <JButton id='gotoOpenChild' styleClass='gotoOpenTrip'/> + <JButton id='gotoOpenChild2' styleClass='gotoOpenTrip2'/> + <JButton id='createChild'/> + <JButton id='moveSelectedChildren'/> + + <!-- extra actions --> + <Table id="extraActions" fill='both' weightx='1' weighty='1' insets='0'> + <row weighty="1" weightx="1"> + <cell> + <JButton id='gotoOpenRoute' styleClass='gotoOpenRoute'/> + </cell> + <cell> + <JButton id='gotoOpenRoute2' styleClass='gotoOpenRoute2'/> + </cell> + </row> + <row weighty="1" weightx="1"> + <cell> + <JButton id='gotoOpenActivity' styleClass='gotoOpenActivity'/> + </cell> + <cell> + <JButton id='gotoOpenActivity2' styleClass='gotoOpenActivity2'/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.list.ContentListUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/TripSeinesUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/TripSeinesUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/TripSeinesUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/TripSeinesUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/TripSeinesUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/TripSeinesUIHandler.java new file mode 100644 index 0000000..106229c --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/TripSeinesUIHandler.java @@ -0,0 +1,109 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.list.impl.seine; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.DataReferenceSet; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.services.service.seine.TripSeineService; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.list.ContentListUIHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.ArrayList; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class TripSeinesUIHandler extends ContentListUIHandler<ProgramDto, TripSeineDto> { + + /** Logger */ + static private final Log log = LogFactory.getLog(TripSeinesUIHandler.class); + + public TripSeinesUIHandler(TripSeinesUI ui) { + super(ui, DataContextType.Program, DataContextType.TripSeine); + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + String openProgramId = dataContext.getOpenProgramId(); + + if (openProgramId == null) { + + // pas de program ouvert (donc pas de maree ouverte) + // on peut reouvrir une maree + addInfoMessage(n("observe.content.tripSeine.message.no.active.found")); + return ContentMode.CREATE; + } + + // + // il existe un maree ouverte + // + + if (dataContext.isSelectedOpen(ProgramDto.class)) { + + // le program courant a une maree ouverte + addInfoMessage(n("observe.content.tripSeine.message.active.found")); + return ContentMode.UPDATE; + } + + // + // la marée ouverte est dans un autre program + // + + addInfoMessage(n("observe.content.tripSeine.message.active.found.for.other.program")); + return ContentMode.READ; + } + + @Override + protected void finalizeOpenUI() { + Class referenceType = ProgramDto.class; + ReferentialReference<ProgramDto> programRef = getDataSource().getReferentialReference(referenceType, getSelectedParentId()); + String title = getDecoratorService().getReferentialReferenceDecorator(referenceType).toString(programRef); + getUi().setContentTitle(title); + } + + @Override + protected List<DataReference<TripSeineDto>> getChilds(String parentId) { + + TripSeineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripSeineService(); + DataReferenceSet<TripSeineDto> tripSeineByProgram = service.getTripSeineByProgram(parentId); + + if (log.isDebugEnabled()) { + log.debug("Will use " + tripSeineByProgram.sizeReference() + " trips."); + } + + return new ArrayList<>(tripSeineByProgram.getReferences()); + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/TripSeinesUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/TripSeinesUIModel.java new file mode 100644 index 0000000..a1774a4 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/impl/seine/TripSeinesUIModel.java @@ -0,0 +1,52 @@ +package fr.ird.observe.application.swing.ui.content.list.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.application.swing.ui.content.list.ContentListUIModel; + +import java.util.List; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class TripSeinesUIModel extends ContentListUIModel<ProgramDto, TripSeineDto> { + + private static final long serialVersionUID = 1L; + + public TripSeinesUIModel() { + super(ProgramDto.class, TripSeineDto.class); + } + + @Override + public void setData(List<DataReference<TripSeineDto>> data) { + super.setData(data); + setSelectedDatas(null); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/package.html b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/package.html similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/package.html rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/list/package.html diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/ContentOpenableUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/ContentOpenableUI.jaxx new file mode 100644 index 0000000..af8cbea --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/ContentOpenableUI.jaxx @@ -0,0 +1,114 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ContentUI + abstract='true' + superGenericType='E' + genericType='E extends IdDto' + > + + <import> + fr.ird.observe.services.dto.AbstractObserveDto + fr.ird.observe.services.dto.IdDto + + fr.ird.observe.application.swing.ui.actions.shared.CancelCreateUIAction + fr.ird.observe.application.swing.ui.actions.shared.CloseAndCreateUIAction + fr.ird.observe.application.swing.ui.actions.shared.CloseOpenUIAction + fr.ird.observe.application.swing.ui.actions.shared.DeleteDataUIAction + fr.ird.observe.application.swing.ui.actions.shared.ReOpenUIAction + fr.ird.observe.application.swing.ui.actions.shared.ResetEditUIAction + fr.ird.observe.application.swing.ui.actions.shared.SaveEditUIAction + + javax.swing.SwingConstants + + </import> + + <!-- handler --> + <ContentOpenableUIHandler id='handler' genericType='E'/> + + <!-- model --> + <ContentOpenableUIModel id='model' genericType='E' + enabled='{!model.isReadingMode()}'/> + + <script><![CDATA[ + + public void openData() { + getHandler().openDataUI(); + } + + public void closeData() { + getHandler().closeDataUI(); + } + + public void closeAndCreateData() { + getHandler().closeAndCreateDataUI(); + } + ]]> + </script> + + <!-- actions --> + <Table id="actions" weightx='1' insets='0'> + <row> + <cell fill="both"> + <Table id='editActions' fill="both" weightx="1" insets='2'> + <row> + <cell weightx="0.5" fill="both"> + <JButton id='cancel'/> + </cell> + <cell weightx="0.5"> + <JButton id='reset'/> + </cell> + <cell weightx="0.5"> + <JButton id='save'/> + </cell> + <cell weightx="0.5"> + <JButton id='delete'/> + </cell> + </row> + </Table> + </cell> + </row> + <row insets='0'> + <cell fill='both'> + <Table id='extraActions' fill="both" weightx="1" insets='2' + visible='{model.isUpdatingMode()}'/> + </cell> + </row> + <row> + <cell fill="both"> + <Table id='openActions' fill="both" weightx="1" insets='2'> + <row> + <cell weightx="0.5"> + <JButton id='reopen'/> + </cell> + <cell weightx="0.5" fill="both"> + <JButton id='close'/> + </cell> + <cell weightx="0.5"> + <JButton id='closeAndCreate'/> + </cell> + </row> + </Table> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/ContentOpenableUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/ContentOpenableUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/ContentOpenableUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/ContentOpenableUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/ContentOpenableUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/ContentOpenableUIHandler.java new file mode 100644 index 0000000..fde7a30 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/ContentOpenableUIHandler.java @@ -0,0 +1,314 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.open; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.ContentUIHandler; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import fr.ird.observe.application.swing.validation.ValidationContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.validator.NuitonValidatorScope; + +import static org.nuiton.i18n.I18n.t; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public abstract class ContentOpenableUIHandler<E extends IdDto> extends ContentUIHandler<E> { + + protected static final String POSITION_OPENABLE = "positionOpenable"; + + /** Logger */ + static private final Log log = LogFactory.getLog(ContentOpenableUIHandler.class); + + protected final String closeMessage; + + public ContentOpenableUIHandler(ContentOpenableUI<E> ui, + DataContextType parentType, + DataContextType type, + String closeMessage) { + super(ui, parentType, type); + this.closeMessage = closeMessage; + } + + protected abstract boolean obtainCanReopen(boolean create); + + @Override + public ContentOpenableUI<E> getUi() { + return (ContentOpenableUI<E>) super.getUi(); + } + + @Override + public ContentOpenableUIModel<E> getModel() { + return (ContentOpenableUIModel<E>) super.getModel(); + } + + @Override + protected boolean computeCanWrite(ObserveSwingDataSource source) { + return source.canWriteData(); + } + + protected abstract boolean doOpenData(); + + public final void openDataUI() { + boolean ok = false; + try { + ok = doOpenData(); + } catch (Exception e) { + UIHelper.handlingError(e); + } finally { + + if (ok) { + afterOpenData(); + } + } + } + + public final void afterOpenData() { + + ContentOpenableUI<E> ui = getUi(); + + // On charge les ensembles de références utilisées dans les combobox + updateUiWithReferenceSetsFromModel(); + + // on repaint le parent (le program devient alors ouvert) + ObserveTreeHelper treeHelper = getTreeHelper(ui); + treeHelper.reloadSelectedNode(true, true); +// ObserveNode node = treeHelper.getSelectedNode(); +// treeHelper.refreshNode(node.getParent(), true); + + // on chage l'état 'canReopen' du model + ui.getModel().setCanReopen(false); + + // on lance l'édition + ui.restartEdit(); + } + + public final void closeDataUI() { + boolean ok = false; + try { + ok = doCloseData(); + } catch (Exception e) { + UIHelper.handlingError(e); + } finally { + + if (ok) { + afterCloseData(); + } + } + } + + public abstract boolean doCloseData(); + + public final void afterCloseData() { + + ContentOpenableUI<E> ui = getUi(); + + ContentOpenableUIModel<E> model = getModel(); + + model.setCanReopen(true); + E bean = getBean(); + + ui.stopEdit(); + model.setMode(ContentMode.READ); + + removeAllMessages(ui); + addMessage(ui, NuitonValidatorScope.INFO, + getEntityLabel(bean.getClass()), t(closeMessage)); + + ObserveTreeHelper treeHelper = getTreeHelper(ui); +// ObserveNode selectedNode = treeHelper.getSelectedNode(); +// if (bean instanceof Trip) { +// // le program peut change d'etat open +// selectedNode = selectedNode.getParent(); +// } +// treeHelper.refreshNode(selectedNode, true); + treeHelper.reloadSelectedNode(bean instanceof TripSeineDto || bean instanceof TripLonglineDto, true); + updateActions(); + } + + @Override + protected void afterSave(boolean refresh) { + + super.afterSave(refresh); + + ContentOpenableUI<E> ui = getUi(); + + int position = ui.getContextValue(Integer.class, POSITION_OPENABLE); + ObserveTreeHelper treeHelper = getTreeHelper(ui); + + ObserveNode node = treeHelper.getSelectedNode(); + ObserveNode parentNode = node.getParent(); + boolean create = node.getId() == null; + + E bean = getBean(); + + int oldPosition; + if (create) { + oldPosition = parentNode.getChildCount(); + } else { + oldPosition = parentNode.getIndex(node); + } + + if (create) { + + // on passe en mode mise à jour + getModel().setMode(ContentMode.UPDATE); + + // on supprime le noeud temporaire + treeHelper.removeNode(node); + + // on crée le noeud final de la marée + node = treeHelper.addOpenable(parentNode, bean); + + // arrêt de l'édition de l'écran courant + stopEditUI(); + + if (oldPosition != position) { + + // on doit repositionner le noeud + treeHelper.moveNode(parentNode, node, position); + } + + // on sélectionne le nouveau noeud + treeHelper.selectNode(node); + } else { + if (oldPosition != position) { + + // on doit repositionner le noeud + treeHelper.moveNode(parentNode, node, position); + + // et le selectionner + treeHelper.selectNode(node); + } + + // on repaint le noeud et ses enfants +// treeHelper.refreshNode(node, true); + treeHelper.reloadSelectedNode(false, true); + +// treeHelper.refreshNode(node, false); + } + } + + /** + * Clôturer la marée ouverte puis en créer une nouvelle. + * + * @since 1.5 + */ + public final void closeAndCreateDataUI() { + + // fermeture de la donnée + try { + boolean b = doCloseData(); + if (!b) { + + // la fermeture a ete abandonnee + if (log.isInfoEnabled()) { + log.info(prefix + "Stop closing data..."); + } + return; + } + } catch (Exception eee) { + UIHelper.handlingError("Could not close current data", eee); + } + + stopEditUI(); + + // création d'une nouvelle donnée + + ObserveTreeHelper treeHelper = getTreeHelper(getUi()); + + treeHelper.reloadSelectedNode(false, true); + + ObserveNode parentNode = treeHelper.getSelectedNode().getParent(); + if (log.isDebugEnabled()) { + log.debug("PARENT NODE = " + parentNode); + } + treeHelper.addUnsavedNode(parentNode, getBeanType()); + } + + protected final void obtainChildPosition(E bean){ + + String containerId = getSelectedParentId(); + + int position = getOpenablePosition(containerId, bean); + + if (log.isDebugEnabled()) { + log.debug("Position of child : " + position); + } + + getUi().setContextValue(position, POSITION_OPENABLE); + } + + protected abstract int getOpenablePosition(String parentId, E bean); + + protected final void finalizeOpenUI(ContentMode mode, boolean create) { + +// // utilisation du mode requis +// setContentMode(mode); + + boolean historicalData = false; + + ContentOpenableUIModel<E> model = getUi().getModel(); + + if (!create) { + + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ValidationContext context = applicationContext.getValidationContext(); + TripSeineDto currentTripSeine = context.getCurrentTripSeine(); + + if (currentTripSeine != null && currentTripSeine.isHistoricalData()) { + + if (log.isInfoEnabled()) { + log.info(prefix + "Using a historical fish trip " + currentTripSeine.getId()); + } + historicalData = true; + } + + } + + model.setHistoricalData(historicalData); + + boolean canReopen = obtainCanReopen(create); + + if (log.isInfoEnabled()) { + log.info(prefix + "historical data ? = " + historicalData); + log.info(prefix + "can reopen ? = " + canReopen); + } + model.setCanReopen(canReopen); + + if (mode != ContentMode.READ) { + getUi().startEdit(null); + } + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/ContentOpenableUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/ContentOpenableUIModel.java new file mode 100644 index 0000000..3037a20 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/ContentOpenableUIModel.java @@ -0,0 +1,68 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.open; + +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; + +/** + * Le modèle pour un écran d'édition avec des fils. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.5 + */ +public abstract class ContentOpenableUIModel<E extends IdDto> extends ContentUIModel<E> { + + public static final String PROPERTY_CAN_REOPEN = "canReopen"; + + public static final String PROPERTY_HISTORICAL_DATA = "historicalData"; + + private static final long serialVersionUID = 1L; + + protected boolean canReopen; + + protected boolean historicalData; + + public ContentOpenableUIModel(Class<E> beanType) { + super(beanType); + } + + public boolean isCanReopen() { + return canReopen; + } + + public void setCanReopen(boolean canReopen) { + boolean old = isCanReopen(); + this.canReopen = canReopen; + firePropertyChange(PROPERTY_CAN_REOPEN, old, canReopen); + } + + public boolean isHistoricalData() { + return historicalData; + } + + public void setHistoricalData(boolean historicalData) { + boolean old = isHistoricalData(); + this.historicalData = historicalData; + firePropertyChange(PROPERTY_HISTORICAL_DATA, old, historicalData); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/ActivityLonglineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/ActivityLonglineUI.jaxx new file mode 100644 index 0000000..f8ab337 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/ActivityLonglineUI.jaxx @@ -0,0 +1,147 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.open.ContentOpenableUI superGenericType='ActivityLonglineDto' + contentTitle='{n("observe.storage.activityLongline.title")}'> + + <style source="../../../Common.jcss"/> + + <import> + fr.ird.observe.services.dto.CommentableDto + fr.ird.observe.services.dto.longline.ActivityLonglineDto + fr.ird.observe.services.dto.longline.SetLonglineDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.FpaZoneDto + fr.ird.observe.services.dto.referential.longline.VesselActivityLonglineDto + fr.ird.observe.application.swing.ui.actions.shared.DeleteDataUIAction + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + org.nuiton.jaxx.widgets.datetime.DateTimeEditor + org.nuiton.jaxx.widgets.gis.absolute.CoordinatesEditor + + java.awt.Dimension + + javax.swing.SwingConstants + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <ActivityLonglineUIHandler id='handler'/> + + <!-- model --> + <ActivityLonglineUIModel id='model'/> + + <!-- edit bean --> + <ActivityLonglineDto id='bean'/> + + <!-- validator --> + <BeanValidator id='validator' + autoField='true' + beanClass='fr.ird.observe.services.dto.longline.ActivityLonglineDto' + errorTableModel='{getErrorTableModel()}' + context='ui-create'> + + <field name='longitude' component='coordinatesEditor'/> + <field name='latitude' component='coordinatesEditor'/> + <field name='quadrant' component='coordinatesEditor'/> + + </BeanValidator> + + <!-- formulaire --> + <JPanel id="body" layout='{new BorderLayout()}'> + <Table fill='both' constraints="BorderLayout.CENTER"> + + <!-- date - time --> + <row> + <cell columns="2" weightx="1"> + <DateTimeEditor id='timeStamp' constructorParams='this'/> + </cell> + </row> + + <!-- position --> + <row> + <cell columns="2" weightx="1"> + <CoordinatesEditor id='coordinatesEditor' constructorParams='this'/> + </cell> + </row> + + <!-- activity vessel --> + <row> + <cell anchor='west'> + <JLabel id='vesselActivityLonglineLabel'/> + </cell> + <cell anchor='east' fill="both"> + <BeanComboBox id='vesselActivityLongline' genericType='ReferentialReference<VesselActivityLonglineDto>' _entityClass='VesselActivityLonglineDto.class' constructorParams='this'/> + </cell> + </row> + + <row> + <cell anchor='west'> + <JLabel id='fpaZoneLabel'/> + </cell> + <cell anchor='east' fill="both"> + <BeanComboBox id='fpaZone' genericType='ReferentialReference<FpaZoneDto>' _entityClass='FpaZoneDto.class' constructorParams='this'/> + </cell> + </row> + + <!-- température de surface --> + <row> + <cell anchor='west'> + <JLabel id='seaSurfaceTemperatureLabel'/> + </cell> + <cell anchor='east' fill="both"> + <NumberEditor id='seaSurfaceTemperature' constructorParams='this'/> + </cell> + </row> + + <!-- comment --> + <row> + <cell columns='2' weighty="1"> + <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2'/> + </JScrollPane> + </cell> + </row> + </Table> + </JPanel> + + <!-- surcharge des actions (pour appliquer la css specifique) --> + <JButton id='delete'/> + <JButton id='reopen'/> + <JButton id='close'/> + <JButton id='closeAndCreate'/> + <JButton id='actionDown'/> + + <Table id='extraActions' fill="both" weightx="1" insets='2' visible='{model.isUpdatingMode()}'> + <row> + <cell weightx="0.5" fill="both"> + <JButton id='addSet' + onActionPerformed='getHandler().addChild(SetLonglineDto.class)'/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.open.ContentOpenableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/ActivityLonglineUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/ActivityLonglineUI.jcss new file mode 100644 index 0000000..78d3299 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/ActivityLonglineUI.jcss @@ -0,0 +1,100 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#model { + editable:true; + modified:{validator.isChanged()}; + valid:{validator.isValid()}; +} + +#timeStamp { + propertyDate:{ActivityLonglineDto.PROPERTY_TIME_STAMP}; + propertyDayDate:{ActivityLonglineUIModel.PROPERTY_DATE}; + propertyTimeDate:{ActivityLonglineUIModel.PROPERTY_TIME}; + label:{t("observe.storage.activityLongline.timeStamp")}; + date:{bean.getTimeStamp()}; +} + +#coordinatesEditor { + propertyLatitude:{ActivityLonglineDto.PROPERTY_LATITUDE}; + propertyLongitude:{ActivityLonglineDto.PROPERTY_LONGITUDE}; + propertyQuadrant:{ActivityLonglineDto.PROPERTY_QUADRANT}; +} + +#vesselActivityLonglineLabel { + text:"observe.storage.activityLongline.vesselActivityLongline"; + labelFor:{vesselActivityLongline}; +} + +#vesselActivityLongline { + property:{ActivityLonglineDto.PROPERTY_VESSEL_ACTIVITY_LONGLINE}; + selectedItem:{bean.getVesselActivityLongline()}; + enabled:{!model.isUpdatingMode()}; +} + +#fpaZoneLabel { + text:"observe.storage.activityLongline.fpaZone"; + labelFor:{fpaZone}; +} + +#fpaZone { + property:{ActivityLonglineDto.PROPERTY_FPA_ZONE}; + selectedItem:{bean.getFpaZone()}; +} + +#seaSurfaceTemperatureLabel { + text:"observe.storage.activityLongline.seaSurfaceTemperature"; + labelFor:{seaSurfaceTemperature}; +} + +#seaSurfaceTemperature { + property:{ActivityLonglineDto.PROPERTY_SEA_SURFACE_TEMPERATURE}; + model:{bean.getSeaSurfaceTemperature()}; + useFloat:true; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL2_PATTERN}; +} + +#reopen { + _toolTipText:{t("observe.content.action.reopen.activity.tip")}; +} + +#close { + enabled:{!model.isModified() && (model.isHistoricalData() || model.isValid())}; + _toolTipText:{t("observe.action.close.activity.tip")}; +} + +#closeAndCreate { + enabled:{!model.isModified() && (model.isHistoricalData() || model.isValid())}; + _text:{t("observe.content.action.closeAndCreate.activity")}; + _toolTipText:{t("observe.content.action.closeAndCreate.activity.tip")}; +} + +#delete { + _toolTipText:{t("observe.action.delete.activity.tip")}; +} + +#addSet { + actionIcon:add; + text:"observe.action.add.setLongline"; + toolTipText:"observe.action.add.setLongline.tip"; + enabled:{!model.isModified() && model.isValid() && model.isSetOperation() && ! bean.isHasSetLongline()}; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/ActivityLonglineUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/ActivityLonglineUIHandler.java new file mode 100644 index 0000000..4caacdc --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/ActivityLonglineUIHandler.java @@ -0,0 +1,363 @@ +package fr.ird.observe.application.swing.ui.content.open.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.longline.ActivityLonglineDto; +import fr.ird.observe.services.dto.longline.ActivityLonglineDtos; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.dto.result.TripChildSaveResultDto; +import fr.ird.observe.services.service.longline.ActivityLonglineService; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; +import fr.ird.observe.application.swing.ui.content.open.ContentOpenableUIHandler; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.validator.NuitonValidatorScope; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 8/29/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.7 + */ +public class ActivityLonglineUIHandler extends ContentOpenableUIHandler<ActivityLonglineDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(ActivityLonglineUIHandler.class); + + static { + + n("observe.common.latitude"); + n("observe.common.longitude"); + + } + +// static ImmutableSet<String> COORDINATES_PROPERTIES = ImmutableSet.of(ActivityLongline.PROPERTY_QUADRANT, +// ActivityLongline.PROPERTY_LATITUDE, +// ActivityLongline.PROPERTY_LONGITUDE); + +// private LogPropertyChanges logCoordinatesChanges; + + public ActivityLonglineUIHandler(ActivityLonglineUI ui) { + super(ui, + DataContextType.TripLongline, + DataContextType.ActivityLongline, + n("observe.storage.activityLongline.message.not.open")); +// this.logCoordinatesChanges = new LogPropertyChanges(COORDINATES_PROPERTIES); + } + + @Override + public ActivityLonglineUI getUi() { + return (ActivityLonglineUI) super.getUi(); + } + + @Override + protected boolean doOpenData() { + boolean result = getOpenDataManager().canOpenActivityLongline(getSelectedParentId()); + if (result) { + getOpenDataManager().openActivityLongline(getSelectedParentId(), getSelectedId()); + } + return result; + } + + @Override + public boolean doCloseData() { + boolean result = getOpenDataManager().isOpenActivityLongline(getSelectedId()); + if (result) { + getOpenDataManager().closeActivityLongline(getSelectedId()); + } + return result; + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + String activityId = getSelectedId(); + + if (activityId == null) { + + // mode creation + return ContentMode.CREATE; + } + + // l'activity existe en base + if (getOpenDataManager().isOpenActivityLongline(getSelectedId())) { + + // l'activity est ouverte, donc modifiable + return ContentMode.UPDATE; + } + + ActivityLonglineUI ui = getUi(); + + // l'activity n'est pas ouverte, donc pas éditable + if (!getOpenDataManager().isOpenTripLongline(getSelectedParentId())) { + + // la marée n'est pas ouverte + addMessage(ui, + NuitonValidatorScope.INFO, + getEntityLabel(TripLonglineDto.class), + t("observe.content.tripLongline.message.not.open")); + + if (getModel().isHistoricalData()) { + + addInfoMessage(t("observe.message.historical.data")); + } + + } else { + + // seule l'activity n'est pas ouverte + addInfoMessage(t(closeMessage)); + } + + return ContentMode.READ; + } + +// @Override +// public void initUI() { +// super.initUI(); +// getBean().removePropertyChangeListener(logCoordinatesChanges); +// getBean().addPropertyChangeListener(logCoordinatesChanges); +// } + + @Override + public void openUI() { + super.openUI(); + + getUi().getCoordinatesEditor().resetModel(); + + String tripId = getSelectedParentId(); + String activityId = getSelectedId(); + + if (log.isInfoEnabled()) { + log.info(prefix + "tripId = " + tripId); + log.info(prefix + "activityId = " + activityId); + } + + ContentMode mode = computeContentMode(); + if (log.isInfoEnabled()) { + log.info(prefix + "content mode " + mode); + } + ActivityLonglineDto bean = getBean(); + + boolean create = activityId == null; + + Form<ActivityLonglineDto> form; + if (create) { + + // create mode + form = getActivityLonglineService().preCreate(tripId); + + } else { + + // update mode + form = getActivityLonglineService().loadForm(activityId); + + } + + setContentMode(mode); + + loadReferentialReferenceSetsInModel(form); + + getModel().setForm(form); + ActivityLonglineDtos.copyActivityLonglineDto(form.getObject(), bean); + + if (log.isDebugEnabled()) { + log.debug(" long - lat = " + bean.getLongitude() + + " - " + bean.getLatitude()); + } + finalizeOpenUI(mode, create); + + // Mise à jour du composant de coordonnées + // 1. Mise à jour latitude/longitude: + getUi().getCoordinatesEditor().setLatitudeAndLongitude(bean.getLatitude(), bean.getLongitude()); + + // 2. Mise à jour du quadrant : + // Si le bean de données contient un quadrant, on met simplement à jour le composant de coordonnées pour sélectionner le quadrant voulu + // sinon, on réinitialise les quadrants du composant afin qu'aucun d'eux ne soit sélectionné (par exemple dans le cas de la création de la première activité d'une marée) + if (bean.getQuadrant() != null) { + getUi().getCoordinatesEditor().setQuadrant(bean.getQuadrant()); + } else { + resetQuadrant(getUi().getCoordinatesEditor()); + } + + getUi().getCoordinatesEditor().setQuadrant(bean.getQuadrant()); + + // on annule la modification engendree par ce binding + getModel().setModified(create); + } + + @Override + public void startEditUI(String... binding) { + ActivityLonglineUI ui = getUi(); + + ContentUIModel<ActivityLonglineDto> model = getModel(); + + boolean create = model.getMode() == ContentMode.CREATE; + String contextName = getValidatorContextName(model.getMode()); + ui.getValidator().setContext(contextName); + if (create) { + addMessage(ui, + NuitonValidatorScope.INFO, + getEntityLabel(ActivityLonglineDto.class), + t("observe.storage.activityLongline.message.creating")); + } else { + addMessage(ui, + NuitonValidatorScope.INFO, + getEntityLabel(ActivityLonglineDto.class), + t("observe.storage.activityLongline.message.updating")); + } + + super.startEditUI( + ActivityLonglineUI.BINDING_TIME_STAMP_DATE, + ActivityLonglineUI.BINDING_SEA_SURFACE_TEMPERATURE_MODEL, + ActivityLonglineUI.BINDING_COMMENT2_TEXT, + ActivityLonglineUI.BINDING_VESSEL_ACTIVITY_LONGLINE_SELECTED_ITEM, + ActivityLonglineUI.BINDING_FPA_ZONE_SELECTED_ITEM, + ActivityLonglineUI.BINDING_CLOSE_ENABLED, + ActivityLonglineUI.BINDING_CLOSE_AND_CREATE_ENABLED); + model.setModified(create); + } + + @Override + protected boolean doSave(ActivityLonglineDto bean) throws Exception { + + boolean notPersisted = bean.isNotPersisted(); + + if (log.isDebugEnabled()) { + log.debug(" long - lat = " + bean.getLongitude() + " - " + bean.getLatitude()); + } + + String tripId = getSelectedParentId(); + + TripChildSaveResultDto saveResult = getActivityLonglineService().save(tripId, getModel().getBean()); + saveResult.toDto(bean); + + setUpdateMareeNodeTag(saveResult.isTripEndDateUpdated()); + + obtainChildPosition(bean); + + // ouverture de l'activité après création + if (notPersisted) { + getOpenDataManager().openActivityLongline(getSelectedParentId(), bean.getId()); + } + + return true; + } + + @Override + protected int getOpenablePosition(String parentId, ActivityLonglineDto bean) { + int position = getActivityLonglineService().getActivityLonglinePositionInTripLongline(parentId, bean.getId()); + return position; + } + + @Override + protected boolean doDelete(ActivityLonglineDto bean) { + + if (askToDelete(bean)) { + return false; + } + if (log.isInfoEnabled()) { + log.info("Will delete Activity " + bean.getId()); + } + + String tripId = getSelectedParentId(); + boolean wasTripEndDateUpdated = getActivityLonglineService().delete(tripId, bean.getId()); + if (log.isInfoEnabled()) { + log.info("Delete done for Activity " + bean.getId()); + } + getOpenDataManager().closeActivityLongline(bean.getId()); + + setUpdateMareeNodeTag(wasTripEndDateUpdated); + return true; + + } + + @Override + protected void afterSave(boolean refresh) { + super.afterSave(refresh); + repaintTripNode(); + } + + @Override + protected void afterDelete() { + super.afterDelete(); + repaintTripNode(); + } + + @Override + protected boolean obtainCanReopen(boolean create) { + + boolean canReopen = !create && getOpenDataManager().canOpenActivityLongline(getSelectedParentId()); + return canReopen; + + } + + public static final String UPDATE_TRIP_NODE = "updateTripNode"; + + protected void setUpdateMareeNodeTag(boolean wasUpdated) { + + if (wasUpdated) { + + // la date de fin a ete modifiee, il faut : redessiner le noeud de la maree le repositionner + getUi().setContextValue(Boolean.TRUE, UPDATE_TRIP_NODE); + + } else { + + getUi().removeContextValue(Boolean.class, UPDATE_TRIP_NODE); + + } + + } + + protected void repaintTripNode() { + + Boolean updateTripNode = getUi().getContextValue(Boolean.class, UPDATE_TRIP_NODE); + + getUi().removeContextValue(Boolean.class, UPDATE_TRIP_NODE); + + if (updateTripNode == null || !updateTripNode) { + return; + } + + ObserveTreeHelper treeHelper = getTreeHelper(getUi()); + ObserveNode tripNode = treeHelper.getSelectedNode().getParent().getParent(); + if (log.isInfoEnabled()) { + log.info("Refresh trip node : " + tripNode); + } + treeHelper.reloadNode(tripNode, false); + + } + + protected ActivityLonglineService getActivityLonglineService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivityLonglineService(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/ActivityLonglineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/ActivityLonglineUIModel.java new file mode 100644 index 0000000..94ffcfe --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/ActivityLonglineUIModel.java @@ -0,0 +1,89 @@ +package fr.ird.observe.application.swing.ui.content.open.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.longline.ActivityLonglineDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.longline.VesselActivityLonglineDto; +import fr.ird.observe.services.dto.referential.longline.VesselActivityLonglineDtos; +import fr.ird.observe.application.swing.ui.content.open.ContentOpenableUIModel; +import org.nuiton.util.DateUtil; + +import java.util.Date; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ActivityLonglineUIModel extends ContentOpenableUIModel<ActivityLonglineDto> { + + private static final long serialVersionUID = 1L; + + public static final String PROPERTY_SET_OPERATION = "setOperation"; + + public static final String PROPERTY_DATE = "date"; + + public static final String PROPERTY_TIME = "time"; + + public ActivityLonglineUIModel() { + super(ActivityLonglineDto.class); + + getBean().addPropertyChangeListener(ActivityLonglineDto.PROPERTY_VESSEL_ACTIVITY_LONGLINE, evt -> { + boolean oldValue = VesselActivityLonglineDtos.isSetOperation((ReferentialReference<VesselActivityLonglineDto>) evt.getOldValue()); + boolean newValue = VesselActivityLonglineDtos.isSetOperation((ReferentialReference<VesselActivityLonglineDto>) evt.getNewValue()); + firePropertyChange(PROPERTY_SET_OPERATION, oldValue, newValue); + }); + } + + public boolean isSetOperation() { + return VesselActivityLonglineDtos.isSetOperation(bean.getVesselActivityLongline()); + } + + public Date getDate() { + Date timeStamp = bean.getTimeStamp(); + return timeStamp == null ? null : DateUtil.getDay(timeStamp); + } + + public Date getTime() { + Date timeStamp = bean.getTimeStamp(); + return timeStamp == null ? null : DateUtil.getTime(timeStamp, false, false); + } + + public void setDate(Date date) { + Date timeStamp = bean.getTimeStamp(); + if (timeStamp != null) { + Date dateAndTime = date == null ? timeStamp : DateUtil.getDateAndTime(date, timeStamp, true, false); + bean.setTimeStamp(dateAndTime); + } + } + + public void setTime(Date time) { + Date timeStamp = bean.getTimeStamp(); + if (timeStamp != null) { + Date dateAndTime = time == null ? timeStamp : DateUtil.getDateAndTime(timeStamp, time, false, false); + bean.setTimeStamp(dateAndTime); + } + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/TripLonglineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/TripLonglineUI.jaxx new file mode 100644 index 0000000..4919b79 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/TripLonglineUI.jaxx @@ -0,0 +1,242 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.open.ContentOpenableUI superGenericType='TripLonglineDto' + contentTitle='{n("observe.content.tripLongline.title")}'> + + <style source="../../../Common.jcss"/> + + <import> + fr.ird.observe.services.dto.CommentableDto + fr.ird.observe.services.dto.longline.TripLonglineDto + fr.ird.observe.services.dto.longline.ActivityLonglineDto + fr.ird.observe.services.dto.longline.TripLonglineActivityDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.HarbourDto + fr.ird.observe.services.dto.referential.PersonDtos + fr.ird.observe.services.dto.referential.VesselDto + fr.ird.observe.services.dto.referential.VesselDtos + fr.ird.observe.services.dto.referential.PersonDto + fr.ird.observe.services.dto.referential.OceanDto + fr.ird.observe.services.dto.referential.longline.TripTypeDto + fr.ird.observe.application.swing.ui.actions.shared.DeleteDataUIAction + fr.ird.observe.application.swing.ui.util.tripMap.TripMapUI + + org.jdesktop.swingx.JXDatePicker + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + java.awt.Dimension + java.beans.PropertyChangeEvent + java.beans.PropertyChangeListener + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.apache.commons.lang3.StringUtils.isEmpty + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <TripLonglineUIHandler id='handler'/> + + <!-- model --> + <TripLonglineUIModel id='model'/> + + <!-- edit bean --> + <TripLonglineDto id='bean'/> + + <!-- validator --> + <BeanValidator id='validator' + beanClass='fr.ird.observe.services.dto.longline.TripLonglineDto' + errorTableModel='{getErrorTableModel()}' + autoField='true' + context='ui-update'> + <field name='activityLongline' component='{actionDown}'/> + </BeanValidator> + + <script><![CDATA[ + +protected boolean canEditOcean(java.util.LinkedHashSet<TripLonglineActivityDto> activities) { + return activities == null || activities.isEmpty(); +} + +]]> + </script> + + <!-- formulaire --> + <JPanel id="body" layout='{new BorderLayout()}'> + <JTabbedPane id='tripLonglineTabPane' constraints='BorderLayout.CENTER'> + <tab id='generalTab'> + <Table fill="both"> + + <!-- tripType --> + <row> + <cell anchor='west'> + <JLabel id='tripTypeLabel'/> + </cell> + <cell anchor='east'> + <BeanComboBox id='tripType' constructorParams='this' genericType='ReferentialReference<TripTypeDto>' _entityClass='TripTypeDto.class'/> + </cell> + </row> + + <!-- captain --> + <row> + <cell anchor='west'> + <JLabel id='captainLabel'/> + </cell> + <cell anchor='east'> + <BeanComboBox id='captain' constructorParams='this' genericType='ReferentialReference<PersonDto>' _entityClass='PersonDto.class'/> + </cell> + </row> + + <!-- observer --> + <row> + <cell anchor='west'> + <JLabel id='observerLabel'/> + </cell> + <cell anchor='east'> + <BeanComboBox id='observer' constructorParams='this' genericType='ReferentialReference<PersonDto>' _entityClass='PersonDto.class'/> + </cell> + </row> + + <!-- dataEntryOperator --> + <row> + <cell anchor='west'> + <JLabel id='dataEntryOperatorLabel'/> + </cell> + <cell anchor='east'> + <BeanComboBox id='dataEntryOperator' constructorParams='this' genericType='ReferentialReference<PersonDto>' _entityClass='PersonDto.class'/> + </cell> + </row> + + <!-- vessel --> + <row> + <cell anchor='west'> + <JLabel id='vesselLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='vessel' constructorParams='this' genericType='ReferentialReference<VesselDto>' _entityClass='VesselDto.class'/> + </cell> + </row> + + <!-- ocean (editable uniquement si pas de route saisie) --> + <row> + <cell anchor='west'> + <JLabel id='oceanLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='ocean' genericType='ReferentialReference<OceanDto>' _entityClass='OceanDto.class' constructorParams='this'/> + </cell> + </row> + + <!-- departureHarbour --> + <row> + <cell anchor='west'> + <JLabel id='departureHarbourLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='departureHarbour' genericType='ReferentialReference<HarbourDto>' _entityClass='HarbourDto.class' constructorParams='this'/> + </cell> + </row> + + <!-- landingHarbour --> + <row> + <cell anchor='west'> + <JLabel id='landingHarbourLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='landingHarbour' genericType='ReferentialReference<HarbourDto>' _entityClass='HarbourDto.class' constructorParams='this'/> + </cell> + </row> + + <!-- homeId --> + <row> + + <cell anchor='west'> + <JLabel id='homeIdLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel layout='{new BorderLayout()}'> + <JToolBar id='homeIdToolbar' constraints='BorderLayout.WEST'> + <JButton id='resetHomeId' styleClass='resetButton'/> + </JToolBar> + <JTextField id='homeId' constraints='BorderLayout.CENTER'/> + </JPanel> + </cell> + </row> + + <!-- totalFishingOperationsNumber --> + <row> + <cell anchor='west'> + <JLabel id='totalFishingOperationsNumberLabel'/> + </cell> + <cell anchor='west' weightx="0.5"> + <NumberEditor id='totalFishingOperationsNumber' constructorParams='this'/> + </cell> + </row> + + <!-- startDate --> + <row> + <cell anchor='west'> + <JLabel id='startDateLabel'/> + </cell> + <cell anchor='west' weightx="0.5"> + <JXDatePicker id='startDate'/> + </cell> + </row> + + <!-- endDate --> + <row> + <cell anchor='west'> + <JLabel id='endDateLabel'/> + </cell> + <cell anchor='west' weightx="0.5"> + <JXDatePicker id='endDate'/> + </cell> + </row> + + <!-- comment --> + <row> + <cell columns='2' fill='both' weighty="1"> + <JScrollPane id='comment' + onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2' + onKeyReleased='getModel().getBean().setComment(comment2.getText())'/> + </JScrollPane> + </cell> + </row> + </Table> + </tab> + <tab id="mapTab"> + <TripMapUI id="tripMap"/> + </tab> + </JTabbedPane> + </JPanel> + + <!-- surcharge des actions (pour appliquer la css specifique) --> + <JButton id='delete'/> + <JButton id='reopen'/> + <JButton id='close'/> + <JButton id='closeAndCreate'/> + <JButton id='actionDown'/> + +</fr.ird.observe.application.swing.ui.content.open.ContentOpenableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/TripLonglineUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/TripLonglineUI.jcss new file mode 100644 index 0000000..3ba29c5 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/TripLonglineUI.jcss @@ -0,0 +1,196 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +NumberEditor { + bean:{bean}; + useFloat:false; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; +} + +#generalTab { + title: {t("observe.content.tripLongline.tab.general")}; +} + +#mapTab { + title: {t("observe.content.tripLongline.tab.map")}; +} + +#model { + editable:true; + modified:{validator.isChanged()}; + valid:{validator.isValid()}; +} + +#observerLabel { + text:"observe.content.tripLongline.observer"; + labelFor:{observer}; +} + +#observer { + property:{TripLonglineDto.PROPERTY_OBSERVER}; + selectedItem:{bean.getObserver()}; +} + +#captainLabel { + text:"observe.content.tripLongline.captain"; + labelFor:{captain}; +} + +#captain { + property:{TripLonglineDto.PROPERTY_CAPTAIN}; + selectedItem:{bean.getCaptain()}; +} + +#dataEntryOperatorLabel { + text:"observe.content.tripLongline.dataEntryOperator"; + labelFor:{dataEntryOperator}; +} + +#dataEntryOperator { + property:{TripLonglineDto.PROPERTY_DATA_ENTRY_OPERATOR}; + selectedItem:{bean.getDataEntryOperator()}; +} + +#tripTypeLabel{ + text:"observe.content.tripLongline.tripType"; + labelFor:{tripType}; +} + +#tripType { + property:{TripLonglineDto.PROPERTY_TRIP_TYPE}; + selectedItem:{bean.getTripType()}; +} + +#vesselLabel{ + text:"observe.content.tripLongline.vessel"; + labelFor:{vessel}; +} + +#vessel { + property:{TripLonglineDto.PROPERTY_VESSEL}; + selectedItem:{bean.getVessel()}; +} + +#oceanLabel{ + text:"observe.content.tripLongline.ocean"; + labelFor:{ocean}; +} + +#ocean { + property:{TripLonglineDto.PROPERTY_OCEAN}; + selectedItem:{bean.getOcean()}; + enabled:{canEditOcean(bean.getActivityLongline())}; +} + +#departureHarbourLabel { + text:"observe.common.departureHarbour"; + labelFor:{departureHarbour}; +} + +#departureHarbour { + property:{TripLonglineDto.PROPERTY_DEPARTURE_HARBOUR}; + selectedItem:{bean.getDepartureHarbour()}; +} + +#landingHarbourLabel { + text:"observe.common.landingHarbour"; + labelFor:{landingHarbour}; +} + +#landingHarbour { + property:{TripLonglineDto.PROPERTY_LANDING_HARBOUR}; + selectedItem:{bean.getLandingHarbour()}; +} + +#totalFishingOperationsNumberLabel{ + text:"observe.content.tripLongline.totalFishingOperationsNumber"; + labelFor:{totalFishingOperationsNumber}; +} + +#totalFishingOperationsNumber { + property:{TripLonglineDto.PROPERTY_TOTAL_FISHING_OPERATIONS_NUMBER}; + model:{bean.getTotalFishingOperationsNumber()}; + useFloat:false; +} + +#homeIdLabel { + text:"observe.content.tripLongline.homeId"; + labelFor:{homeId}; +} + +#resetHomeId { + toolTipText:"observe.content.action.reset.homeId.tip"; + _resetPropertyName: {TripLonglineDto.PROPERTY_HOME_ID}; +} + +#homeId { + text:{getStringValue(bean.getHomeId())}; + _propertyName: {TripLonglineDto.PROPERTY_HOME_ID}; +} + +#startDateLabel { + text:"observe.content.tripLongline.startDate"; + labelFor:{startDate}; +} + +#startDate { + date:{bean.getStartDate()}; + _propertyName: {TripLonglineDto.PROPERTY_START_DATE}; +} + +#endDateLabel { + text:"observe.content.tripLongline.endDate"; + labelFor:{endDate}; +} + +#endDate { + date:{bean.getEndDate()}; + _propertyName: {TripLonglineDto.PROPERTY_END_DATE}; +} + +#comment { + columnHeaderView:{new JLabel(t("observe.common.comment"))}; + minimumSize:{new Dimension(10,50)}; +} + +#comment2 { + text:{getStringValue(bean.getComment())}; +} + +#reopen { + _toolTipText:{t("observe.content.action.reopen.maree.tip")}; +} + +#close { + enabled:{!model.isModified() && (model.isHistoricalData() || model.isValid()) && !dataContext.isOpenActivity()}; + _toolTipText:{t("observe.action.close.maree.tip")}; +} + +#closeAndCreate { + enabled:{!model.isModified() && (model.isHistoricalData() || model.isValid()) && !dataContext.isOpenActivity()}; + _text:{t("observe.content.action.closeAndCreate.maree")}; + _toolTipText:{t("observe.content.action.closeAndCreate.maree.tip")}; +} + +#delete { + _toolTipText:{t("observe.action.delete.maree.tip")}; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/TripLonglineUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/TripLonglineUIHandler.java new file mode 100644 index 0000000..167e7e5 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/TripLonglineUIHandler.java @@ -0,0 +1,373 @@ +package fr.ird.observe.application.swing.ui.content.open.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.TripMapDto; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.dto.longline.TripLonglineDtos; +import fr.ird.observe.services.dto.referential.PersonDtos; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.VesselDtos; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.service.longline.TripLonglineService; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.open.ContentOpenableUIHandler; +import fr.ird.observe.application.swing.ui.content.open.ContentOpenableUIModel; +import fr.ird.observe.application.swing.ui.util.tripMap.TripMapUI; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.util.DateUtil; + +import javax.swing.JTabbedPane; +import javax.swing.SwingUtilities; +import java.util.Collection; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 8/27/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.7 + */ +public class TripLonglineUIHandler extends ContentOpenableUIHandler<TripLonglineDto> { + + /** Logger */ + static private final Log log = LogFactory.getLog(TripLonglineUIHandler.class); + + protected boolean buildTripMap = true; + + public TripLonglineUIHandler(TripLonglineUI ui) { + super(ui, + DataContextType.Program, + DataContextType.TripLongline, + n("observe.content.tripLongline.message.not.open")); + } + + @Override + public TripLonglineUI getUi() { + return (TripLonglineUI) super.getUi(); + } + + @Override + public boolean doCloseData() { + boolean result = getOpenDataManager().isOpenTripLongline(getSelectedId()); + if (result) { + getOpenDataManager().closeTripLongline(getSelectedId()); + } + return result; + } + + @Override + public void initUI() { + super.initUI(); + + TripLonglineUI ui = getUi(); + TripMapUI tripMap = ui.getTripMap(); + ObserveSwingApplicationConfig config = ObserveSwingApplicationContext.get().getConfig(); + + tripMap.getHandler().setConfig(config); + + getUi().getTripLonglineTabPane().addChangeListener(e -> { + JTabbedPane tripLonglineTabPane = (JTabbedPane) e.getSource(); + TripLonglineUI ui1 = getUi(); + TripMapUI tripMap1 = ui1.getTripMap(); + if (tripLonglineTabPane.getSelectedComponent().equals(tripMap1)) { + ui1.getActions().setVisible(false); + + if (buildTripMap) { + SwingUtilities.invokeLater(() -> { + + TripLonglineUI ui11 = getUi(); + TripMapUI tripMap11 = ui11.getTripMap(); + + TripMapDto tripLonglineMap = getTripLonglineService().getTripLonglineMap(getSelectedId()); + + tripMap11.getHandler().doOpenMap(tripLonglineMap); + }); + buildTripMap = false; + } + + } else { + ui1.getActions().setVisible(true); + } + }); + + } + + @Override + public void openUI() { + super.openUI(); + + ContentMode mode = computeContentMode(); + + String programId = getSelectedParentId(); + String tripId = getSelectedId(); + + if (log.isInfoEnabled()) { + log.info(prefix + "programId = " + programId); + log.info(prefix + "tripId = " + tripId); + log.info(prefix + "mode = " + mode); + } + + TripLonglineDto bean = getBean(); + + boolean create = tripId == null; + + Form<TripLonglineDto> form; + if (create) { + + if (log.isInfoEnabled()) { + log.info(prefix + "create a new trip"); + } + // create mode + form = getTripLonglineService().preCreate(programId); + + } else { + + // update mode + if (log.isInfoEnabled()) { + log.info(prefix + "using existing trip " + tripId); + } + + // update mode + form = getTripLonglineService().loadForm(tripId); + } + + setContentMode(mode); + + loadReferentialReferenceSetsInModel(form); + + getModel().setForm(form); + TripLonglineDtos.copyTripLonglineDto(form.getObject(), bean); + + getUi().getTripLonglineTabPane().setSelectedIndex(0); + getUi().getTripMap().getHandler().doCloseMap(); + buildTripMap = true; + + finalizeOpenUI(mode, create); + } + + @Override + public void startEditUI(String... binding) { + + TripLonglineUI ui = getUi(); + + ContentOpenableUIModel<TripLonglineDto> model = getModel(); + + ContentMode mode = model.getMode(); + + boolean create = mode == ContentMode.CREATE; + + String contextName = getValidatorContextName(mode); + ui.getValidator().setContext(contextName); + + if (create) { + addInfoMessage(t("observe.content.tripLongline.message.creating")); + } else { + addInfoMessage(t("observe.content.tripLongline.message.updating")); + if (model.isHistoricalData()) { + + addInfoMessage(t("observe.message.historical.data")); + } + } + // date is current day + if (model.getMode() == ContentMode.UPDATE) { + if (getBean().getEndDate() == null) { + Date date = DateUtil.getEndOfDay(new Date()); + getBean().setEndDate(date); + if (log.isDebugEnabled()) { + log.debug("date fin " + date); + } + } + } + + super.startEditUI(TripLonglineUI.BINDING_VESSEL_SELECTED_ITEM, + TripLonglineUI.BINDING_OBSERVER_SELECTED_ITEM, + TripLonglineUI.BINDING_CAPTAIN_SELECTED_ITEM, + TripLonglineUI.BINDING_TRIP_TYPE_SELECTED_ITEM, + TripLonglineUI.BINDING_DATA_ENTRY_OPERATOR_SELECTED_ITEM, + TripLonglineUI.BINDING_TOTAL_FISHING_OPERATIONS_NUMBER_MODEL, + TripLonglineUI.BINDING_OCEAN_SELECTED_ITEM, + TripLonglineUI.BINDING_START_DATE_DATE, + TripLonglineUI.BINDING_END_DATE_DATE, + TripLonglineUI.BINDING_COMMENT2_TEXT, + TripLonglineUI.BINDING_HOME_ID_TEXT, + TripLonglineUI.BINDING_CLOSE_ENABLED, + TripLonglineUI.BINDING_CLOSE_AND_CREATE_ENABLED); + model.setModified(create); + } + + @Override + protected boolean doOpenData() { + boolean result = getOpenDataManager().canOpenTripLongline(); + if (result) { + getOpenDataManager().openTripLongline(getSelectedParentId(), getSelectedId()); + } + return result; + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + String tripLongLineId = getSelectedId(); + + if (tripLongLineId == null) { + + // maree en cours de creation + return ContentMode.CREATE; + } + + if (getOpenDataManager().isOpenTripLongline(tripLongLineId)) { + + // maree ouverte + return ContentMode.UPDATE; + } + + addInfoMessage(t(closeMessage)); + return ContentMode.READ; + } + + @Override + protected boolean doSave(TripLonglineDto bean) throws Exception { + + boolean notPersisted = bean.isNotPersisted(); + + // on force toujours la date a etre sans heure, minute,... + Date startDate = DateUtil.getDay(bean.getStartDate()); + if (log.isDebugEnabled()) { + log.debug("startDate = " + startDate); + } + bean.setStartDate(startDate); + + Date endDate = bean.getEndDate(); + if (log.isDebugEnabled()) { + log.debug("endDate = " + endDate); + } + + SaveResultDto saveResult = getTripLonglineService().save(bean); + saveResult.toDto(bean); + + // recuperation de la position de la maree dans le program + obtainChildPosition(bean); + + // ouverture de la marée + if (notPersisted) { + getOpenDataManager().openTripLongline(getSelectedParentId(), bean.getId()); + } + return true; + } + + @Override + protected int getOpenablePosition(String parentId, TripLonglineDto bean) { + + int position = getTripLonglineService().getTripLonglinePositionInProgram(parentId, bean.getId()); + + return position; + } + + @Override + protected boolean doDelete(TripLonglineDto bean) { + + if (askToDelete(bean)) { + return false; + } + if (log.isInfoEnabled()) { + log.info("Will delete Trip " + bean.getId()); + } + + getTripLonglineService().delete(bean.getId()); + getOpenDataManager().closeTripLongline(bean.getId()); + + if (log.isInfoEnabled()) { + log.info("Delete done for Trip " + bean.getId()); + } + return true; + } + + @Override + protected boolean obtainCanReopen(boolean create) { + + return !create && getOpenDataManager().canOpenTripLongline(); + + } + + @Override + protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { + + Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); + + switch (propertyName) { + + case TripLonglineDto.PROPERTY_CAPTAIN: { + result = (List) PersonDtos.filterCaptainReferences((List) result); + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + } + break; + + case TripLonglineDto.PROPERTY_OBSERVER: { + result = (List) PersonDtos.filterObserverReferences((List) result); + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + } + break; + + case TripLonglineDto.PROPERTY_DATA_ENTRY_OPERATOR: { + result = (List) PersonDtos.filterDataEntryOperatorReferences((List) result); + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + } + break; + + case TripLonglineDto.PROPERTY_VESSEL: { + ObserveSwingApplicationConfig config = ObserveSwingApplicationContext.get().getConfig(); + result = (List) VesselDtos.filterVesselReferencesByVesselTypeIds((List) result, config.getLonglineVesselTypeIds()); + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + } + break; + + } + + return result; + } + + protected TripLonglineService getTripLonglineService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripLonglineService(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/TripLonglineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/TripLonglineUIModel.java new file mode 100644 index 0000000..cc236dc --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/longline/TripLonglineUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.open.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.application.swing.ui.content.open.ContentOpenableUIModel; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class TripLonglineUIModel extends ContentOpenableUIModel<TripLonglineDto> { + + private static final long serialVersionUID = 1L; + + public TripLonglineUIModel() { + super(TripLonglineDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/ActivitySeineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/ActivitySeineUI.jaxx new file mode 100644 index 0000000..e17acb4 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/ActivitySeineUI.jaxx @@ -0,0 +1,290 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.open.ContentOpenableUI superGenericType='ActivitySeineDto' + contentTitle='{n("observe.storage.activitySeine.title")}'> + + <style source="../../../Common.jcss"/> + + <import> + fr.ird.observe.services.dto.CommentableDto + fr.ird.observe.services.dto.seine.ActivitySeineDto + fr.ird.observe.services.dto.seine.SetSeineDto + fr.ird.observe.services.dto.seine.FloatingObjectDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.FpaZoneDto + fr.ird.observe.services.dto.referential.seine.VesselActivitySeineDto + fr.ird.observe.services.dto.referential.seine.SurroundingActivityDto + fr.ird.observe.services.dto.referential.seine.ReasonForNoFishingDto + fr.ird.observe.services.dto.referential.seine.DetectionModeDto + fr.ird.observe.services.dto.referential.seine.WindDto + + fr.ird.observe.application.swing.ui.actions.shared.DeleteDataUIAction + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + jaxx.runtime.swing.CardLayout2Ext + + org.nuiton.jaxx.widgets.datetime.TimeEditor + org.nuiton.jaxx.widgets.gis.absolute.CoordinatesEditor + + java.awt.Dimension + + javax.swing.SwingConstants + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <ActivitySeineUIHandler id='handler' constructorParams='this'/> + + <!-- model --> + <ActivitySeineUIModel id='model'/> + + <!-- edit bean --> + <ActivitySeineDto id='bean'/> + + <!-- validator --> + <BeanValidator id='validator' + autoField='true' + beanClass='fr.ird.observe.services.dto.seine.ActivitySeineDto' + errorTableModel='{getErrorTableModel()}' + context='ui-create'> + + <field name='observedSystemEmpty' component='{actionDown}'/> + <field name='observedSystemDistance' component='{actionDown}'/> + <field name='longitude' component='coordinatesEditor'/> + <field name='latitude' component='coordinatesEditor'/> + <field name='quadrant' component='coordinatesEditor'/> + <field name='floatingObjectEmpty' component='addDCP'/> + + </BeanValidator> + + <script><![CDATA[ + +void $afterCompleteSetup() { + String label = getHandler().getActivity6Label(); + String text = t("observe.common.vesselActivitySeine.comment", label); + vesselActivityInformation.setText(text); + vesselActivityInformation.setToolTipText(text); +} + +]]> + </script> + + <!-- formulaire --> + <JPanel id="body" layout='{new BorderLayout()}'> + <Table insets="0" fill="both" constraints='BorderLayout.CENTER'> + <row> + <cell anchor="north" weightx="1"> + <JTabbedPane id='fishingOperationTabPane'> + <tab id='generalTab'> + <Table fill="both"> + <!-- heure observation --> + <row> + <cell columns="2" weightx="1"> + <TimeEditor id='time' constructorParams='this'/> + </cell> + </row> + + <!-- position --> + <row> + <cell anchor='west'> + <JLabel id='coordinatesLabel'/> + </cell> + <cell anchor='east' fill="both"> + <CoordinatesEditor id='coordinatesEditor' constructorParams='this'/> + </cell> + </row> + + <!-- activity vessel --> + <row> + <cell anchor='west' columns="2"> + <JLabel id='vesselActivityInformation'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='vesselActivitySeineLabel'/> + </cell> + <cell anchor='east' weightx="1"> + <BeanComboBox id='vesselActivitySeine' genericType='ReferentialReference<VesselActivitySeineDto>' _entityClass='VesselActivitySeineDto.class' constructorParams='this'/> + </cell> + </row> + + <!-- activity environnante --> + <row> + <cell anchor='west'> + <JLabel id='surroundingActivityLabel'/> + </cell> + <cell anchor='east' weightx="1"> + <BeanComboBox id='surroundingActivity' constructorParams='this' genericType='ReferentialReference<SurroundingActivityDto>' _entityClass='SurroundingActivityDto.class'/> + </cell> + </row> + + <!-- previousFpaZone --> + <row> + <cell anchor='west'> + <JLabel id='previousFpaZoneLabel'/> + </cell> + <cell anchor='east' weightx="1"> + <BeanComboBox id='previousFpaZone' constructorParams='this' genericType='ReferentialReference<FpaZoneDto>' _entityClass='FpaZoneDto.class'/> + </cell> + </row> + + <!-- currentFpaZone --> + <row> + <cell anchor='west'> + <JLabel id='currentFpaZoneLabel'/> + </cell> + <cell anchor='east' weightx="1"> + <BeanComboBox id='currentFpaZone' constructorParams='this' genericType='ReferentialReference<FpaZoneDto>' _entityClass='FpaZoneDto.class'/> + </cell> + </row> + + <!-- nextFpaZone --> + <row> + <cell anchor='west'> + <JLabel id='nextFpaZoneLabel'/> + </cell> + <cell anchor='east' weightx="1"> + <BeanComboBox id='nextFpaZone' constructorParams='this' genericType='ReferentialReference<FpaZoneDto>' _entityClass='FpaZoneDto.class'/> + </cell> + </row> + + <!-- id ers --> + <row> + + <cell anchor='west'> + <JLabel id='ersIdLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel layout='{new BorderLayout()}'> + <JToolBar id='ersIdToolbar' constraints='BorderLayout.WEST'> + <JButton id='resetErsId' constraints='BorderLayout.WEST' styleClass='resetButton'/> + </JToolBar> + <JTextField id='ersId' constraints='BorderLayout.CENTER'/> + </JPanel> + </cell> + </row> + </Table> + </tab> + + <tab id='measurementsTab'> + <Table fill="both"> + <!-- vitesse vessel --> + <row> + <cell anchor='west'> + <JLabel id='vesselSpeedLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <NumberEditor id='vesselSpeed' constructorParams='this'/> + </cell> + </row> + + <!-- température de surface --> + <row> + <cell anchor='west'> + <JLabel id='seaSurfaceTemperatureLabel'/> + </cell> + <cell anchor='east' fill="both"> + <NumberEditor id='seaSurfaceTemperature' constructorParams='this'/> + </cell> + </row> + + <!-- vent beaufort --> + <row> + <cell anchor='west'> + <JLabel id='windLabel'/> + </cell> + <cell anchor='east'> + <BeanComboBox id='wind' genericType='ReferentialReference<WindDto>' _entityClass='WindDto.class' constructorParams='this'/> + </cell> + </row> + + <!-- mode de détection --> + <row> + <cell anchor='west'> + <JLabel id='detectionModeLabel'/> + </cell> + <cell anchor='east'> + <BeanComboBox id='detectionMode' genericType='ReferentialReference<DetectionModeDto>' _entityClass='DetectionModeDto.class' constructorParams='this'/> + </cell> + </row> + + <!-- cause non coups senne --> + <row> + <cell anchor='west'> + <JLabel id='reasonForNoFishingLabel'/> + </cell> + <cell anchor='east'> + <BeanComboBox id='reasonForNoFishing' genericType='ReferentialReference<ReasonForNoFishingDto>' _entityClass='ReasonForNoFishingDto.class' constructorParams='this'/> + </cell> + </row> + <row> + <cell columns="2" weighty="1"> + <JLabel/> + </cell> + </row> + </Table> + </tab> + + </JTabbedPane> + </cell> + </row> + + <!-- comment --> + <row> + <cell columns='2' weighty="1"> + <JScrollPane id='comment' + onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2' + onKeyReleased='getBean().setComment(comment2.getText())'/> + </JScrollPane> + </cell> + </row> + </Table> + </JPanel> + + <!-- surcharge des actions (pour appliquer la css specifique --> + <JButton id='delete'/> + <JButton id='reopen'/> + <JButton id='close'/> + <JButton id='closeAndCreate'/> + <JButton id='actionDown'/> + + <Table id='extraActions' fill="both" weightx="1" insets='2' + visible='{model.isUpdatingMode()}'> + <row> + <cell weightx="0.5" fill="both"> + <JButton id='addSet' + onActionPerformed='getHandler().addChild(SetSeineDto.class)'/> + </cell> + <cell weightx="0.5" fill="both"> + <JButton id='addDCP' + onActionPerformed='getHandler().addChild(FloatingObjectDto.class)'/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.open.ContentOpenableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/ActivitySeineUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/ActivitySeineUI.jcss new file mode 100644 index 0000000..8e587b2 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/ActivitySeineUI.jcss @@ -0,0 +1,226 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#model { + editable:true; + modified:{validator.isChanged()}; + valid:{validator.isValid()}; +} + +#time { + propertyTime:{ActivitySeineDto.PROPERTY_TIME}; + bean:{bean}; + label:{t("observe.common.heureobservation")}; + time:{bean.getTime()}; + _validatorLabel:{t("observe.common.heureobservation")}; +} + +#coordinatesLabel { + text:"observe.storage.activityLongline.coordinate"; + labelFor:{coordinatesEditor}; +} + +#coordinatesEditor { + propertyLatitude:{ActivitySeineDto.PROPERTY_LATITUDE}; + propertyLongitude:{ActivitySeineDto.PROPERTY_LONGITUDE}; + propertyQuadrant:{ActivitySeineDto.PROPERTY_QUADRANT}; +} + +#generalTab { + title:{t("observe.storage.activitySeine.tab.general")}; + icon:{getHandler().getErrorIconIfFalse(model.isGeneralTabValid())}; +} + +#measurementsTab { + title:{t("observe.storage.activitySeine.tab.measurements")}; + icon:{getHandler().getErrorIconIfFalse(model.isMeasurementsTabValid())}; +} + +#vesselActivityInformation { + font-size:11; + actionIcon:"information"; +} + +#vesselActivitySeineLabel { + text:"observe.common.vesselActivitySeine"; + labelFor:{vesselActivitySeine}; +} + +#vesselActivitySeine { + property:{ActivitySeineDto.PROPERTY_VESSEL_ACTIVITY_SEINE}; + selectedItem:{bean.getVesselActivitySeine()}; + enabled:{!model.isUpdatingMode()}; +} + +#surroundingActivityLabel { + text:"observe.common.surroundingActivity"; + labelFor:{surroundingActivity}; +} + +#surroundingActivity { + property:{ActivitySeineDto.PROPERTY_SURROUNDING_ACTIVITY}; + selectedItem:{bean.getSurroundingActivity()}; +} + +#previousFpaZoneLabel { + text:"observe.common.previousFpaZone"; + labelFor:{previousFpaZone}; +} + +#previousFpaZone { + property:{ActivitySeineDto.PROPERTY_PREVIOUS_FPA_ZONE}; + selectedItem:{bean.getPreviousFpaZone()}; + enabled:{model.isChangedZoneOperation()}; +} + +#currentFpaZoneLabel { + text:"observe.common.currentFpaZone"; + labelFor:{currentFpaZone}; +} + +#currentFpaZone { + property:{ActivitySeineDto.PROPERTY_CURRENT_FPA_ZONE}; + selectedItem:{bean.getCurrentFpaZone()}; + enabled:{!model.isChangedZoneOperation()}; +} + +#nextFpaZoneLabel { + text:"observe.common.nextFpaZone"; + labelFor:{nextFpaZone}; +} + +#nextFpaZone { + property:{ActivitySeineDto.PROPERTY_NEXT_FPA_ZONE}; + selectedItem:{bean.getNextFpaZone()}; + enabled:{model.isChangedZoneOperation()}; +} + +#vesselSpeedLabel { + text:"observe.common.vesselSpeed"; + labelFor:{vesselSpeed}; +} + +#vesselSpeed { + property:{ActivitySeineDto.PROPERTY_VESSEL_SPEED}; + model:{bean.getVesselSpeed()}; + useFloat:true; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL2_PATTERN}; +} + +#ersIdLabel{ + text:"observe.common.ersId"; + labelFor:{ersId}; +} + +#resetErsId{ + toolTipText:"observe.content.action.reset.ersId.tip"; + _resetPropertyName:{ActivitySeineDto.PROPERTY_ERS_ID}; +} + +#ersId { + _propertyName:{ActivitySeineDto.PROPERTY_ERS_ID}; + text:{getStringValue(bean.getErsId())}; +} + +#seaSurfaceTemperatureLabel { + text:"observe.common.seaSurfaceTemperature"; + labelFor:{seaSurfaceTemperature}; +} + +#seaSurfaceTemperature { + property:{ActivitySeineDto.PROPERTY_SEA_SURFACE_TEMPERATURE}; + model:{bean.getSeaSurfaceTemperature()}; + useFloat:true; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL2_PATTERN}; +} + +#windLabel { + text:"observe.common.wind"; + labelFor:{wind}; +} + +#wind { + property:{ActivitySeineDto.PROPERTY_WIND}; + selectedItem:{bean.getWind()}; +} + +#detectionModeLabel { + text:"observe.common.detectionMode"; + labelFor:{detectionMode}; +} + +#detectionMode { + property:{ActivitySeineDto.PROPERTY_DETECTION_MODE}; + selectedItem:{bean.getDetectionMode()}; +} + +#reasonForNoFishingLabel { + text:"observe.common.nonCoupSenne"; + labelFor:{reasonForNoFishing}; +} + +#reasonForNoFishing { + property:{ActivitySeineDto.PROPERTY_REASON_FOR_NO_FISHING}; + selectedItem:{bean.getReasonForNoFishing()}; +} + +#comment { + columnHeaderView:{new JLabel(t("observe.common.comment"))}; + minimumSize:{new Dimension(10,50)}; +} + +#comment2 { + text:{getStringValue(bean.getComment())}; +} + +#reopen { + _toolTipText:{t("observe.content.action.reopen.activity.tip")}; +} + +#close { + enabled:{!model.isModified() && (model.isHistoricalData() || model.isValid())}; + _toolTipText:{t("observe.action.close.activity.tip")}; +} + +#closeAndCreate { + enabled:{!model.isModified() && (model.isHistoricalData() || model.isValid())}; + _text:{t("observe.content.action.closeAndCreate.activity")}; + _toolTipText:{t("observe.content.action.closeAndCreate.activity.tip")}; +} + +#delete { + _toolTipText:{t("observe.action.delete.activity.tip")}; +} + +#addSet { + enabled:{!model.isModified() && model.isValid() && model.isSetOperation() && bean.getSetSeine() == null}; + text:"observe.action.add.set"; + toolTipText:"observe.action.add.set.tip"; + actionIcon:"add"; +} + +#addDCP { + enabled:{!model.isModified() && model.isValid()}; + text:"observe.action.add.floatingObject"; + toolTipText:"observe.action.add.floatingObject.tip"; + actionIcon:"add"; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/ActivitySeineUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/ActivitySeineUIHandler.java new file mode 100644 index 0000000..2fb46aa --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/ActivitySeineUIHandler.java @@ -0,0 +1,378 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.open.impl.seine; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.seine.VesselActivitySeineDto; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.services.dto.seine.ActivitySeineDtos; +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.services.service.seine.ActivitySeineService; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; +import fr.ird.observe.application.swing.ui.content.open.ContentOpenableUIHandler; +import jaxx.runtime.validator.swing.SwingValidatorMessage; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.event.TableModelListener; +import java.util.HashSet; +import java.util.Set; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class ActivitySeineUIHandler extends ContentOpenableUIHandler<ActivitySeineDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(ActivitySeineUIHandler.class); + + // Compute valid state of tab from the error table + protected final TableModelListener computeTabValidStateListener; + +// static ImmutableSet<String> COORDINATES_PROPERTIES = ImmutableSet.of(ActivitySeine.PROPERTY_QUADRANT, +// ActivitySeine.PROPERTY_LATITUDE, +// ActivitySeine.PROPERTY_LONGITUDE); + +// private LogPropertyChanges logCoordinatesChanges; + + + public ActivitySeineUIHandler(ActivitySeineUI ui) { + super(ui, + DataContextType.Route, + DataContextType.ActivitySeine, + n("observe.storage.activitySeine.message.not.open")); +// this.logCoordinatesChanges = new LogPropertyChanges(COORDINATES_PROPERTIES); + computeTabValidStateListener = e -> { + + SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); + computeTabValidState(source); + + }; + } + + @Override + public ActivitySeineUI getUi() { + return (ActivitySeineUI) super.getUi(); + } + + @Override + protected boolean doOpenData() { + boolean result = getOpenDataManager().canOpenActivitySeine(getSelectedParentId()); + if (result) { + getOpenDataManager().openActivitySeine(getSelectedParentId(), getSelectedId()); + } + return result; + } + + @Override + public boolean doCloseData() { + boolean result = getOpenDataManager().isOpenActivitySeine(getSelectedId()); + if (result) { + getOpenDataManager().closeActivitySeine(getSelectedId()); + } + return result; + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + String activityId = getSelectedId(); + + if (activityId == null) { + + // mode creation + return ContentMode.CREATE; + } + + // l'activity existe en base + if (getOpenDataManager().isOpenActivitySeine(getSelectedId())) { + + // l'activity est ouverte, donc modifiable + return ContentMode.UPDATE; + } + + ActivitySeineUI ui = getUi(); + + // l'activity n'est pas ouverte, donc pas éditable + if (!getOpenDataManager().isOpenRoute(getSelectedParentId())) { + + // la route n'est pas ouverte + addMessage(ui, + NuitonValidatorScope.INFO, + getEntityLabel(RouteDto.class), + t("observe.content.route.message.not.open")); + + } else if (!getOpenDataManager().isOpenTripSeine(dataContext.getSelectedTripSeineId())) { + + // la marée n'est past ouverte + addMessage(ui, + NuitonValidatorScope.INFO, + getEntityLabel(TripSeineDto.class), + t("observe.content.tripSeine.message.not.open")); + + if (getModel().isHistoricalData()) { + + addInfoMessage(t("observe.message.historical.data")); + } + + } else { + + // seule l'activity n'est pas ouverte + addInfoMessage(t(closeMessage)); + } + + return ContentMode.READ; + } + + @Override + public void initUI() { + + super.initUI(); + + // To be sure always remove listener (could prevent some leaks) + getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); + // listen messages to see if required to add + getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); + +// getBean().removePropertyChangeListener(logCoordinatesChanges); +// getBean().addPropertyChangeListener(logCoordinatesChanges); + } + + @Override + public void openUI() { + super.openUI(); + + getUi().getCoordinatesEditor().resetModel(); + + String routeId = getSelectedParentId(); + String activityId = getSelectedId(); + + if (log.isInfoEnabled()) { + log.info(prefix + "routeId = " + routeId); + log.info(prefix + "activityId = " + activityId); + } + + ContentMode mode = computeContentMode(); + if (log.isInfoEnabled()) { + log.info(prefix + "content mode " + mode); + } + ActivitySeineDto bean = getBean(); + + boolean create = activityId == null; + + Form<ActivitySeineDto> form; + if (create) { + + // create mode + form = getActivitySeineService().preCreate(routeId); + + } else { + + // update mode + form = getActivitySeineService().loadForm(activityId); + + } + + setContentMode(mode); + + loadReferentialReferenceSetsInModel(form); + + getModel().setForm(form); + ActivitySeineDtos.copyActivitySeineDto(form.getObject(), bean); + + if (log.isDebugEnabled()) { + log.debug(prefix + "long - lat = " + bean.getLongitude() + " - " + bean.getLatitude()); + } + + SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); + computeTabValidState(errorTableModel); + + finalizeOpenUI(mode, create); + + // Mise à jour du composant de coordonnées + // 1. Mise à jour latitude/longitude: + getUi().getCoordinatesEditor().setLatitudeAndLongitude(bean.getLatitude(), bean.getLongitude()); + + // 2. Mise à jour du quadrant : + // Si le bean de données contient un quadrant, on met simplement à jour le composant de coordonnées pour sélectionner le quadrant voulu + // sinon, on réinitialise les quadrants du composant afin qu'aucun d'eux ne soit sélectionné (par exemple dans le cas de la création de la première activité d'une route) + if (bean.getQuadrant() != null) { + getUi().getCoordinatesEditor().setQuadrant(bean.getQuadrant()); + } else { + resetQuadrant(getUi().getCoordinatesEditor()); + } + + // on annule la modification engendree par ce binding + getModel().setModified(create); + } + + @Override + public void startEditUI(String... binding) { + ActivitySeineUI ui = getUi(); + + ContentUIModel<ActivitySeineDto> model = getModel(); + + boolean create = model.getMode() == ContentMode.CREATE; + String contextName = getValidatorContextName(model.getMode()); + ui.getValidator().setContext(contextName); + if (create) { + addMessage(ui, + NuitonValidatorScope.INFO, + getEntityLabel(ActivitySeineDto.class), + t("observe.storage.activitySeine.message.creating")); + } else { + addMessage(ui, + NuitonValidatorScope.INFO, + getEntityLabel(ActivitySeineDto.class), + t("observe.storage.activitySeine.message.updating")); + } + + super.startEditUI(ActivitySeineUI.BINDING_TIME_TIME, + ActivitySeineUI.BINDING_VESSEL_SPEED_MODEL, + ActivitySeineUI.BINDING_SEA_SURFACE_TEMPERATURE_MODEL, + ActivitySeineUI.BINDING_COMMENT2_TEXT, + ActivitySeineUI.BINDING_VESSEL_ACTIVITY_SEINE_SELECTED_ITEM, + ActivitySeineUI.BINDING_PREVIOUS_FPA_ZONE_SELECTED_ITEM, + ActivitySeineUI.BINDING_CURRENT_FPA_ZONE_SELECTED_ITEM, + ActivitySeineUI.BINDING_NEXT_FPA_ZONE_SELECTED_ITEM, + ActivitySeineUI.BINDING_SURROUNDING_ACTIVITY_SELECTED_ITEM, + ActivitySeineUI.BINDING_CLOSE_ENABLED, + ActivitySeineUI.BINDING_ADD_SET_ENABLED, + ActivitySeineUI.BINDING_CLOSE_AND_CREATE_ENABLED); + model.setModified(create); + } + + @Override + protected boolean doSave(ActivitySeineDto bean) throws Exception { + + boolean notPersisted = bean.isNotPersisted(); + + if (log.isDebugEnabled()) { + log.debug(" long - lat = " + bean.getLongitude() + " - " + bean.getLatitude()); + } + + String routeId = getSelectedParentId(); + + bean.setOpen(true); + + SaveResultDto saveResult = getActivitySeineService().save(routeId, getModel().getBean()); + saveResult.toDto(bean); + + obtainChildPosition(bean); + + // ouverture de l'activité après création + if (notPersisted) { + getOpenDataManager().openActivitySeine(getSelectedParentId(), bean.getId()); + } + + return true; + } + + + @Override + protected int getOpenablePosition(String parentId, ActivitySeineDto bean) { + int position = getActivitySeineService().getActivitySeinePositionInRoute(parentId, bean.getId()); + return position; + } + + @Override + protected boolean doDelete(ActivitySeineDto bean) { + + if (askToDelete(bean)) { + return false; + } + if (log.isInfoEnabled()) { + log.info("Will delete Activity " + bean.getId()); + } + + String routeId = getSelectedParentId(); + getActivitySeineService().delete(routeId, bean.getId()); + getOpenDataManager().closeActivitySeine(bean.getId()); + + if (log.isInfoEnabled()) { + log.info("Delete done for Activity " + bean.getId()); + } + return true; + } + + @Override + protected boolean obtainCanReopen(boolean create) { + + boolean canReopen = !create && getOpenDataManager().canOpenActivitySeine(getSelectedParentId()); + + return canReopen; + } + + public String getActivity6Label() { + + Set<ReferentialReference<VesselActivitySeineDto>> activities = getDataSource().getReferentialReferences(VesselActivitySeineDto.class); + + for (ReferentialReference<VesselActivitySeineDto> vesselActivity : activities) { + if (ActivitySeineDto.ACTIVITY_FIN_DE_PECHE.equals(vesselActivity.getPropertyValue(VesselActivitySeineDto.PROPERTY_CODE))) { + String label = getDecoratorService().getReferentialReferenceDecorator(VesselActivitySeineDto.class).toString(vesselActivity); +// String label = getDecoratorService().decorate(VesselActivitySeineDto.class.getSimpleName(), +// vesselActivity); + return label; + } + } + throw new IllegalStateException(t("observe.error.no.activity.6")); + } + + protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { + + Set<String> errorProperties = new HashSet<>(); + int rowCount = errorTableModel.getRowCount(); + for (int i = 0; i < rowCount; i++) { + + SwingValidatorMessage row = errorTableModel.getRow(i); + if (NuitonValidatorScope.ERROR.equals(row.getScope())) { + errorProperties.add(row.getField()); + } + } + + boolean generalTabValid = !errorProperties.removeAll(ActivitySeineUIModel.GENERAL_TAB_PROPERTIES); + boolean measurementsTabValid = !errorProperties.removeAll(ActivitySeineUIModel.MEASUREMENTS_TAB_PROPERTIES); + + ActivitySeineUIModel model = (ActivitySeineUIModel) getModel(); + model.setGeneralTabValid(generalTabValid); + model.setMeasurementsTabValid(measurementsTabValid); + + } + + protected ActivitySeineService getActivitySeineService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivitySeineService(); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/ActivitySeineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/ActivitySeineUIModel.java new file mode 100644 index 0000000..c71918f --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/ActivitySeineUIModel.java @@ -0,0 +1,121 @@ +package fr.ird.observe.application.swing.ui.content.open.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.ImmutableSet; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.seine.VesselActivitySeineDto; +import fr.ird.observe.services.dto.referential.seine.VesselActivitySeineDtos; +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.application.swing.ui.content.open.ContentOpenableUIModel; + +import java.util.Set; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ActivitySeineUIModel extends ContentOpenableUIModel<ActivitySeineDto> { + + public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; + + public static final String PROPERTY_MEASUREMENTS_TAB_VALID = "measurementsTabValid"; + + public static final String PROPERTY_SET_OPERATION = "setOperation"; + + public static final String PROPERTY_CHANGED_ZONE_OPERATION = "changedZoneOperation"; + + public static final Set<String> GENERAL_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(ActivitySeineDto.PROPERTY_TIME, + ActivitySeineDto.PROPERTY_LATITUDE, + ActivitySeineDto.PROPERTY_LONGITUDE, + ActivitySeineDto.PROPERTY_VESSEL_ACTIVITY_SEINE, + ActivitySeineDto.PROPERTY_SURROUNDING_ACTIVITY, + ActivitySeineDto.PROPERTY_PREVIOUS_FPA_ZONE, + ActivitySeineDto.PROPERTY_CURRENT_FPA_ZONE, + ActivitySeineDto.PROPERTY_NEXT_FPA_ZONE, + ActivitySeineDto.PROPERTY_ERS_ID).build(); + + public static final Set<String> MEASUREMENTS_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(ActivitySeineDto.PROPERTY_VESSEL_SPEED, + ActivitySeineDto.PROPERTY_SEA_SURFACE_TEMPERATURE, + ActivitySeineDto.PROPERTY_WIND, + ActivitySeineDto.PROPERTY_DETECTION_MODE, + ActivitySeineDto.PROPERTY_REASON_FOR_NO_FISHING).build(); + + private static final long serialVersionUID = 1L; + + protected boolean generalTabValid; + + protected boolean measurementsTabValid; + + public ActivitySeineUIModel() { + super(ActivitySeineDto.class); + getBean().addPropertyChangeListener(ActivitySeineDto.PROPERTY_VESSEL_ACTIVITY_SEINE, evt -> { + ReferentialReference<VesselActivitySeineDto> oldActivitySeine = (ReferentialReference<VesselActivitySeineDto>) evt.getOldValue(); + ReferentialReference<VesselActivitySeineDto> newActivitySeine = (ReferentialReference<VesselActivitySeineDto>) evt.getNewValue(); + { + boolean oldValue = VesselActivitySeineDtos.isSetOperation(oldActivitySeine); + boolean newValue = VesselActivitySeineDtos.isSetOperation(newActivitySeine); + firePropertyChange(PROPERTY_SET_OPERATION, oldValue, newValue); + } + { + boolean oldValue = VesselActivitySeineDtos.isChangedZoneOperation(oldActivitySeine); + boolean newValue = VesselActivitySeineDtos.isChangedZoneOperation(newActivitySeine); + firePropertyChange(PROPERTY_CHANGED_ZONE_OPERATION, oldValue, newValue); + } + }); + + } + + public boolean isMeasurementsTabValid() { + return measurementsTabValid; + } + + public void setMeasurementsTabValid(boolean measurementsTabValid) { + Object oldValue = isMeasurementsTabValid(); + this.measurementsTabValid = measurementsTabValid; + firePropertyChange(PROPERTY_MEASUREMENTS_TAB_VALID, oldValue, measurementsTabValid); + } + + public boolean isGeneralTabValid() { + return generalTabValid; + } + + public void setGeneralTabValid(boolean generalTabValid) { + Object oldValue = isGeneralTabValid(); + this.generalTabValid = generalTabValid; + firePropertyChange(PROPERTY_GENERAL_TAB_VALID, oldValue, generalTabValid); + } + + public boolean isSetOperation() { + return VesselActivitySeineDtos.isSetOperation(bean.getVesselActivitySeine()); + } + + public boolean isChangedZoneOperation() { + return VesselActivitySeineDtos.isChangedZoneOperation(bean.getVesselActivitySeine()); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/RouteUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/RouteUI.jaxx new file mode 100644 index 0000000..847c37f --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/RouteUI.jaxx @@ -0,0 +1,102 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.open.ContentOpenableUI superGenericType='RouteDto' contentTitle='{n("observe.content.route.title")}'> + + <import> + fr.ird.observe.services.dto.seine.RouteDto + + org.jdesktop.swingx.JXDatePicker + + jaxx.runtime.swing.editor.NumberEditor + + java.awt.Dimension + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <RouteUIHandler id='handler' constructorParams='this'/> + + <!-- model --> + <RouteUIModel id='model'/> + + <!-- edit bean --> + <RouteDto id='bean'/> + + <!-- validator --> + <BeanValidator id='validator' + autoField='true' + beanClass='fr.ird.observe.services.dto.seine.RouteDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update'> + <field name='activitySeine' component='{actionDown}'/> + </BeanValidator> + + <!-- formulaire --> + <JPanel id="body" layout='{new BorderLayout()}'> + <Table fill='both' constraints='BorderLayout.CENTER'> + <row> + <cell anchor='west'> + <JLabel id='dateLabel'/> + </cell> + <cell anchor='east' weightx="1"> + <JXDatePicker id='date'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='startLogValueLabel'/> + </cell> + <cell anchor='east' weightx="1"> + <NumberEditor id='startLogValue' constructorParams='this'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id='endLogValueLabel'/> + </cell> + <cell anchor='east' weightx="1"> + <NumberEditor id='endLogValue' constructorParams='this'/> + </cell> + </row> + <row> + <cell columns='2' fill="both" weightx="1" weighty="1"> + <JScrollPane id='comment' + onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2' + onKeyReleased='getBean().setComment(comment2.getText())'/> + </JScrollPane> + </cell> + </row> + </Table> + </JPanel> + + <!-- surcharge des actions (pour appliquer la css specifique) --> + <JButton id='delete'/> + <JButton id='reopen'/> + <JButton id='close'/> + <JButton id='closeAndCreate'/> + <JButton id='actionDown'/> + +</fr.ird.observe.application.swing.ui.content.open.ContentOpenableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/RouteUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/RouteUI.jcss new file mode 100644 index 0000000..115a3db --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/RouteUI.jcss @@ -0,0 +1,92 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +NumberEditor { + bean:{bean}; + useFloat:true; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL2_PATTERN}; +} + +#model { + editable:true; + modified:{validator.isChanged()}; + valid:{validator.isValid()}; +} + +#dateLabel { + text:"observe.common.date"; + labelFor:{date}; +} + +#date { + date:{bean.getDate()}; + _propertyName:{RouteDto.PROPERTY_DATE}; +} + +#startLogValueLabel { + text:"observe.common.startLogValue"; + labelFor:{startLogValue}; +} + +#startLogValue { + property:{RouteDto.PROPERTY_START_LOG_VALUE}; + model:{bean.getStartLogValue()}; +} + +#endLogValueLabel { + text:"observe.common.endLogValue"; + labelFor:{endLogValue}; +} + +#endLogValue { + property:{RouteDto.PROPERTY_END_LOG_VALUE}; + model:{bean.getEndLogValue()}; + enabled:{!model.isCreatingMode()}; +} + +#comment { + columnHeaderView:{new JLabel(t("observe.common.comment"))}; + minimumSize:{new Dimension(10,50)}; +} + +#comment2 { + text:{getStringValue(bean.getComment())}; +} + +#reopen { + _toolTipText:{t("observe.content.action.reopen.route.tip")}; +} + +#close { + enabled:{!model.isModified() && (model.isHistoricalData() || model.isValid()) && !dataContext.isOpenActivity()}; + _toolTipText:{t("observe.action.close.route.tip")}; +} + +#closeAndCreate { + enabled:{!model.isModified() && (model.isHistoricalData() || model.isValid()) && !dataContext.isOpenActivity()}; + _text:{t("observe.content.action.closeAndCreate.route")}; + _toolTipText:{t("observe.content.action.closeAndCreate.route.tip")}; +} + +#delete { + _toolTipText:{t("observe.action.delete.route.tip")}; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/RouteUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/RouteUIHandler.java new file mode 100644 index 0000000..c168d17 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/RouteUIHandler.java @@ -0,0 +1,466 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.open.impl.seine; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.seine.VesselActivitySeineDto; +import fr.ird.observe.services.dto.result.TripChildSaveResultDto; +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.services.dto.seine.RouteDtos; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.services.service.seine.RouteService; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.open.ContentOpenableUIHandler; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.util.DateUtil; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.JOptionPane; +import java.util.Date; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class RouteUIHandler extends ContentOpenableUIHandler<RouteDto> { + + public static final String UPDATE_MAREE_NODE = "updateTripNode"; + + /** Logger */ + private static final Log log = LogFactory.getLog(RouteUIHandler.class); + + public RouteUIHandler(RouteUI ui) { + super(ui, + DataContextType.TripSeine, + DataContextType.Route, + n("observe.content.route.message.not.open")); + } + + @Override + public RouteUI getUi() { + return (RouteUI) super.getUi(); + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + String routeId = getSelectedId(); + + if (routeId == null) { + + // mode creation + return ContentMode.CREATE; + } + + // route deja existante + if (getOpenDataManager().isOpenRoute(routeId)) { + + // la route est ouverte + return ContentMode.UPDATE; + } + + RouteUI ui = getUi(); + + // route non ouverte + if (!dataContext.isSelectedOpen(TripSeineDto.class)) { + + addMessage(ui, NuitonValidatorScope.INFO, + getEntityLabel(TripSeineDto.class), + t("observe.content.tripSeine.message.not.open")); + + } else { + + // la maree courante est ouverte + addMessage(ui, NuitonValidatorScope.INFO, + getEntityLabel(RouteDto.class), + t(closeMessage)); + } + return ContentMode.READ; + } + + @Override + public void openUI() { + + super.openUI(); + + String tripId = getSelectedParentId(); + String routeId = getSelectedId(); + + if (log.isInfoEnabled()) { + log.info(prefix + "tripId = " + tripId); + log.info(prefix + "routeId = " + routeId); + } + + ContentMode mode = computeContentMode(); + + if (log.isInfoEnabled()) { + log.info(prefix + "content mode = " + mode); + } + + RouteDto editBean = getBean(); + + boolean create = routeId == null; + + Form<RouteDto> form; + if (create) { + + // create mode + form = getRouteService().preCreate(tripId); + + } else { + + // update mode + form = getRouteService().loadForm(routeId); + + } + + setContentMode(mode); + + loadReferentialReferenceSetsInModel(form); + + getModel().setForm(form); + RouteDtos.copyRouteDto(form.getObject(), editBean); + + finalizeOpenUI(mode, create); + } + + @Override + public void startEditUI(String... binding) { + + boolean create = getModel().getMode() == ContentMode.CREATE; + String contextName = getValidatorContextName(getModel().getMode()); + + RouteUI ui = getUi(); + + ui.getValidator().setContext(contextName); + + if (create) { + addMessage(ui, + NuitonValidatorScope.INFO, + getEntityLabel(RouteDto.class), + t("observe.content.route.message.creating")); + } else { + addMessage(ui, + NuitonValidatorScope.INFO, + getEntityLabel(RouteDto.class), + t("observe.content.route.message.updating")); + + if (getModel().isHistoricalData()) { + + addInfoMessage(t("observe.message.historical.data")); + } + } + + super.startEditUI(RouteUI.BINDING_DATE_DATE, + RouteUI.BINDING_START_LOG_VALUE_MODEL, + RouteUI.BINDING_END_LOG_VALUE_ENABLED, + RouteUI.BINDING_COMMENT2_TEXT, + RouteUI.BINDING_CLOSE_ENABLED, + RouteUI.BINDING_CLOSE_AND_CREATE_ENABLED); + + // le formulaire est en état modifié uniquement si on est en création + getModel().setModified(create); + } + + @Override + protected boolean doSave(RouteDto bean) throws Exception { + + boolean notPersisted = bean.isNotPersisted(); + + String tripId = getSelectedParentId(); + + if (log.isInfoEnabled()) { + log.info("will save route " + bean.getId()); + } + + // on sauvegarde toujours en debut de jour + Date date = DateUtil.getDay(bean.getDate()); + bean.setDate(date); + bean.setOpen(true); + + TripChildSaveResultDto saveResult = getRouteService().save(tripId, bean); + saveResult.toDto(bean); + + setUpdateMareeNodeTag(saveResult.isTripEndDateUpdated()); + + obtainChildPosition(bean); + + // ouverture de la route + if (notPersisted) { + getOpenDataManager().openRoute(getSelectedParentId(), bean.getId()); + } + + return true; + } + + @Override + protected int getOpenablePosition(String parentId, RouteDto bean) { + int position = getRouteService().getRoutePositionInTripSeine(parentId, bean.getId()); + return position; + } + + @Override + protected void afterSave(boolean refresh) { + super.afterSave(refresh); + repaintTripNode(); + } + + @Override + protected void afterDelete() { + super.afterDelete(); + repaintTripNode(); + } + + @Override + protected boolean doDelete(RouteDto bean) { + + if (askToDelete(bean)) { + return false; + } + if (log.isInfoEnabled()) { + log.info("Will delete Route " + bean.getId()); + } + + String tripId = getSelectedParentId(); + boolean wasEndDateUpdated = getRouteService ().delete(tripId, bean.getId()); + getOpenDataManager().closeRoute(getSelectedId()); + + if (log.isInfoEnabled()) { + log.info("Delete done for Route " + bean.getId()); + } + + setUpdateMareeNodeTag(wasEndDateUpdated); + + return true; + } + + @Override + protected boolean doOpenData() { + boolean result = getOpenDataManager().canOpenRoute(getSelectedParentId()); + if (result) { + getOpenDataManager().openRoute(getSelectedParentId(), getSelectedId()); + } + return result; + } + + @Override + public boolean doCloseData() { + + RouteDto route = getBean(); + + // on doit vérifier qu'il existe une activité de fin + // de veille (type activity vessel == 16) + + boolean mustAddFinVeille = !route.isActivityFindDeVeilleFound(); + + boolean createActivityFinDeVeille = false; + boolean closeActivityFinDeVeille = false; + boolean gotoActivityFinDeVeille = false; + + ObserveTreeHelper treeHelper = getTreeHelper(getUi()); + ObserveNode routeNode = treeHelper.getSelectedNode(); + + if (mustAddFinVeille) { + + // on indique à l'observer qu'il doit créer une activité de type + // 16 + + int reponse = UIHelper.askUser( + getUi(), + t("observe.title.need.confirm"), + t("observe.message.need.fin.veille.activity"), + JOptionPane.WARNING_MESSAGE, + new Object[]{ + t("observe.choice.not.create.fin.veille.activity.and.continue"), + t("observe.choice.create.fin.veille.activity.and.continue"), + t("observe.choice.create.fin.veille.activity"), + t("observe.choice.cancel")}, + 0); + if (log.isDebugEnabled()) { + log.debug("response : " + reponse); + } + + + switch (reponse) { + case JOptionPane.CLOSED_OPTION: + case 3: + + // abandon objectOperation + return false; + case 0: + + // rien a faire + // on veut juste cloturer la route + break; + case 1: + + // creation de l'activity de fin de veille + // fermeture de l'activity de fin de veille + // fermeture de la route + createActivityFinDeVeille = true; + closeActivityFinDeVeille = true; + + break; + case 2: + + // creation de l'activity de fin de veille + // selection de cette activity de fin de veille + createActivityFinDeVeille = true; + gotoActivityFinDeVeille = true; + break; + } + } + + if (createActivityFinDeVeille) { + + // stop l'édition de la route + stopEditUI(); + + // creation de l'action de fin de veille + addActivityFinDeVeille(closeActivityFinDeVeille); + + if (gotoActivityFinDeVeille) { + + // on selection l'activity de fin de veille et on y reste + // donc on ne continue pas la fermeture de la route + return false; + } + + // on retourne sur la route + // que l'on va refermer + treeHelper.selectNode(routeNode); + } + + // fermeture de la route + getOpenDataManager().closeRoute(getSelectedId()); + return true; + } + + protected ActivitySeineUI addActivityFinDeVeille(boolean close) { + + ObserveTreeHelper treeHelper = getTreeHelper(getUi()); + + // on créee l'activity de fin de veille + ObserveNode parentNode = treeHelper.getSelectedNode(); + parentNode = treeHelper.findNode( + parentNode, + n("observe.tree.activitySeine") + ); + if (log.isDebugEnabled()) { + log.debug("PARENT NODE = " + parentNode); + } + treeHelper.addUnsavedNode(parentNode, ActivitySeineDto.class); + + // on recupère l'écran d'édition + ActivitySeineUI selectedUI = (ActivitySeineUI) ObserveSwingApplicationContext.get().getContentUIManager().getSelectedContentUI(); + + // on recupère l'activity de fin de veille + ReferentialReference<VesselActivitySeineDto> vesselActivitySeine = null; + + for (ReferentialReference<VesselActivitySeineDto> refVesselActivity : selectedUI.getVesselActivitySeine().getData()) { + + if (ActivitySeineDto.ACTIVITY_FIN_DE_VEILLE.equals(refVesselActivity.getPropertyValue(VesselActivitySeineDto.PROPERTY_CODE))) { + vesselActivitySeine = refVesselActivity; + break; + } + } + + // on la positionne sur le bean d'édition + selectedUI.getBean().setVesselActivitySeine(vesselActivitySeine); + + // on initialise la fin de veille a la dernière minute du jour + selectedUI.getBean().setTime(DateUtil.getEndOfDay(DateUtil.createDate(0, 0, 0))); + + if (close) { + + // on sauvegarde l'activity + selectedUI.save(false); + + // on ferme l'activity + selectedUI.closeData(); + + // on ferme l'écean + selectedUI.stopEdit(); + } + return selectedUI; + } + + @Override + protected boolean obtainCanReopen(boolean create) { + + // on peut reouvrir une route si : + // - pas de route ouverte + // - la maree courante est ouverte + boolean canReopen = !create && getOpenDataManager().canOpenRoute(getSelectedParentId()); + return canReopen; + } + + protected void repaintTripNode() { + Boolean updateTripNode = getUi().getContextValue(Boolean.class, UPDATE_MAREE_NODE); + + getUi().removeContextValue(Boolean.class, UPDATE_MAREE_NODE); + + if (updateTripNode == null || !updateTripNode) { + return; + } + + + ObserveTreeHelper treeHelper = getTreeHelper(getUi()); + ObserveNode tripNode = treeHelper.getSelectedNode().getParent().getParent(); + if (log.isInfoEnabled()) { + log.info("Refresh trip node : " + tripNode); + } + treeHelper.reloadNode(tripNode, false); +// treeHelper.refreshNode(tripNode, false); + } + + protected void setUpdateMareeNodeTag(boolean wasUpdated) { + + if (wasUpdated) { + + // la date de fin a ete modifiee, il faut : redessiner le noeud de la maree le repositionner + getUi().setContextValue(Boolean.TRUE, UPDATE_MAREE_NODE); + + } else { + + getUi().removeContextValue(Boolean.class, UPDATE_MAREE_NODE); + + } + + } + + protected RouteService getRouteService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newRouteService(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/RouteUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/RouteUIModel.java new file mode 100644 index 0000000..c509f76 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/RouteUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.open.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.application.swing.ui.content.open.ContentOpenableUIModel; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class RouteUIModel extends ContentOpenableUIModel<RouteDto> { + + private static final long serialVersionUID = 1L; + + public RouteUIModel() { + super(RouteDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/TripSeineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/TripSeineUI.jaxx new file mode 100644 index 0000000..0372626 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/TripSeineUI.jaxx @@ -0,0 +1,256 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.open.ContentOpenableUI superGenericType='TripSeineDto' + contentTitle='{n("observe.content.tripSeine.title")}'> + + <import> + fr.ird.observe.services.dto.seine.TripSeineDto + fr.ird.observe.services.dto.seine.RouteDto + fr.ird.observe.services.dto.seine.RouteStubDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.HarbourDto + fr.ird.observe.services.dto.referential.PersonDtos + fr.ird.observe.services.dto.referential.VesselDto + fr.ird.observe.services.dto.referential.VesselDtos + fr.ird.observe.services.dto.referential.PersonDto + fr.ird.observe.services.dto.referential.OceanDto + fr.ird.observe.application.swing.ui.util.tripMap.TripMapUI + + org.jdesktop.swingx.JXDatePicker + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + java.awt.Dimension + java.beans.PropertyChangeEvent + java.beans.PropertyChangeListener + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.apache.commons.lang3.StringUtils.isEmpty + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <TripSeineUIHandler id='handler' constructorParams='this'/> + + <!-- model --> + <TripSeineUIModel id='model'/> + + <!-- edit bean --> + <TripSeineDto id='bean'/> + + <!-- validator --> + <BeanValidator id='validator' + beanClass='fr.ird.observe.services.dto.seine.TripSeineDto' + errorTableModel='{getErrorTableModel()}' + autoField='true' + context='ui-update'> + + <field name='route' component='{actionDown}'/> + </BeanValidator> + + <script><![CDATA[ + +protected boolean canEditOcean(java.util.LinkedHashSet<RouteStubDto> routes) { + return routes == null || routes.isEmpty(); +} + +]]> + </script> + + <!-- formulaire --> + <JPanel id="body" layout='{new BorderLayout()}'> + <JTabbedPane id='tripSeineTabPane' constraints='BorderLayout.CENTER'> + <tab id='generalTab'> + <Table insets="0" fill="both"> + + <!-- captain --> + <row> + <cell anchor='west'> + <JLabel id='captainLabel'/> + </cell> + <cell anchor='east'> + <BeanComboBox id='captain' constructorParams='this' genericType='ReferentialReference<PersonDto>' _entityClass='PersonDto.class'/> + </cell> + </row> + + <!-- observer --> + <row> + <cell anchor='west'> + <JLabel id='observerLabel'/> + </cell> + <cell anchor='east'> + <BeanComboBox id='observer' constructorParams='this' genericType='ReferentialReference<PersonDto>' _entityClass='PersonDto.class'/> + </cell> + </row> + + <!-- dataEntryOperator --> + <row> + <cell anchor='west'> + <JLabel id='dataEntryOperatorLabel'/> + </cell> + <cell anchor='east'> + <BeanComboBox id='dataEntryOperator' constructorParams='this' genericType='ReferentialReference<PersonDto>' _entityClass='PersonDto.class'/> + </cell> + </row> + + <!-- vessel --> + <row> + <cell anchor='west'> + <JLabel id='vesselLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='vessel' constructorParams='this' genericType='ReferentialReference<VesselDto>' _entityClass='VesselDto.class'/> + </cell> + </row> + + <!-- ocean (editable uniquement si pas de route saisie) --> + <row> + <cell anchor='west'> + <JLabel id='oceanLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='ocean' genericType='ReferentialReference<OceanDto>' _entityClass='OceanDto.class' constructorParams='this'/> + </cell> + </row> + + <!-- departureHarbour --> + <row> + <cell anchor='west'> + <JLabel id='departureHarbourLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='departureHarbour' genericType='ReferentialReference<HarbourDto>' _entityClass='HarbourDto.class' constructorParams='this'/> + </cell> + </row> + + <!-- landingHarbour --> + <row> + <cell anchor='west'> + <JLabel id='landingHarbourLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='landingHarbour' genericType='ReferentialReference<HarbourDto>' _entityClass='HarbourDto.class' constructorParams='this'/> + </cell> + </row> + + <!-- id ers --> + <row> + + <cell anchor='west'> + <JLabel id='ersIdLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel layout='{new BorderLayout()}'> + <JToolBar id='ersIdToolbar' constraints='BorderLayout.WEST'> + <JButton id='resetErsId' constraints='BorderLayout.WEST' styleClass='resetButton'/> + </JToolBar> + <JTextField id='ersId' constraints='BorderLayout.CENTER'/> + </JPanel> + </cell> + </row> + + <!-- startDate --> + <row> + <cell anchor='west'> + <JLabel id='startDateLabel'/> + </cell> + <cell anchor='west' weightx="0.5"> + <JXDatePicker id='startDate'/> + </cell> + </row> + + <!-- endDate --> + <row> + <cell anchor='west'> + <JLabel id='endDateLabel'/> + </cell> + <cell anchor='west' weightx="0.5"> + <JXDatePicker id='endDate'/> + </cell> + </row> + + <!-- formsUrl --> + <row> + <cell anchor="west"> + <JLabel id='formsUrlLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel layout='{new BorderLayout()}'> + <JToolBar id='formsUrlToolbar' constraints='BorderLayout.WEST'> + <JButton id='resetFormsUrl' constraints='BorderLayout.WEST' styleClass='resetButton'/> + </JToolBar> + <JTextField id='formsUrl' constraints='BorderLayout.CENTER'/> + <JToolBar id='formsUrlToolbar2' constraints='BorderLayout.EAST'> + <JButton id='openLinkFormulairesUrl' + onActionPerformed='getHandler().openLink(getModel().getBean().getFormsUrl())'/> + </JToolBar> + + </JPanel> + </cell> + </row> + + <!-- reportsUrl --> + <row> + <cell anchor="west"> + <JLabel id='reportsUrlLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel layout='{new BorderLayout()}'> + <JToolBar id='reportsUrlToolbar' constraints='BorderLayout.WEST'> + <JButton id='resetReportsUrl' constraints='BorderLayout.WEST' styleClass='resetButton'/> + </JToolBar> + <JTextField id='reportsUrl' constraints='BorderLayout.CENTER'/> + + <JToolBar id='reportsUrlToolbar2' constraints='BorderLayout.EAST'> + <JButton id='openLinkRapportsUrl' constraints='BorderLayout.EAST' + onActionPerformed='getHandler().openLink(getModel().getBean().getReportsUrl())'/> + </JToolBar> + </JPanel> + </cell> + </row> + + <!-- comment --> + <row> + <cell fill='both' weighty="1" columns="2"> + <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2' onKeyReleased='getModel().getBean().setComment(comment2.getText())'/> + </JScrollPane> + </cell> + </row> + </Table> + </tab> + <tab id="mapTab"> + <TripMapUI id="tripMap"/> + </tab> + </JTabbedPane> + </JPanel> + + <!-- surcharge des actions (pour appliquer la css specifique) --> + <JButton id='delete'/> + <JButton id='reopen'/> + <JButton id='close'/> + <JButton id='closeAndCreate'/> + <JButton id='actionDown'/> + +</fr.ird.observe.application.swing.ui.content.open.ContentOpenableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/TripSeineUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/TripSeineUI.jcss new file mode 100644 index 0000000..9f33b17 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/TripSeineUI.jcss @@ -0,0 +1,225 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +BeanComboBox { + bean:{bean}; +} + +NumberEditor { + bean:{bean}; + useFloat:false; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; +} + +#generalTab { + title: {t("observe.content.tripSeine.tab.general")}; +} + +#mapTab { + title: {t("observe.content.tripSeine.tab.map")}; +} + +#model { + editable:true; + modified:{validator.isChanged()}; + valid:{validator.isValid()}; +} + +#observerLabel { + text:"observe.common.observer"; + labelFor:{observer}; +} + +#observer { + property:{TripSeineDto.PROPERTY_OBSERVER}; + selectedItem:{bean.getObserver()}; +} + +#captainLabel { + text:"observe.common.captain"; + labelFor:{captain}; +} + +#captain { + property:{TripSeineDto.PROPERTY_CAPTAIN}; + selectedItem:{bean.getCaptain()}; +} + +#dataEntryOperatorLabel { + text:"observe.common.dataEntryOperator"; + labelFor:{dataEntryOperator}; +} + +#dataEntryOperator { + property:{TripSeineDto.PROPERTY_DATA_ENTRY_OPERATOR}; + selectedItem:{bean.getDataEntryOperator()}; +} + +#vesselLabel { + text:"observe.common.vessel"; + labelFor:{vessel}; +} + +#vessel { + property:{TripSeineDto.PROPERTY_VESSEL}; + selectedItem:{bean.getVessel()}; +} + +#oceanLabel { + text:"observe.common.ocean"; + labelFor:{ocean}; +} + +#ocean { + property:{TripSeineDto.PROPERTY_OCEAN}; + selectedItem:{bean.getOcean()}; + enabled:{canEditOcean(bean.getRoute())}; +} + +#departureHarbourLabel { + text:"observe.common.departureHarbour"; + labelFor:{departureHarbour}; +} + +#departureHarbour { + property:{TripSeineDto.PROPERTY_DEPARTURE_HARBOUR}; + selectedItem:{bean.getDepartureHarbour()}; +} + +#landingHarbourLabel { + text:"observe.common.landingHarbour"; + labelFor:{landingHarbour}; +} + +#landingHarbour { + property:{TripSeineDto.PROPERTY_LANDING_HARBOUR}; + selectedItem:{bean.getLandingHarbour()}; +} + +#ersIdLabel{ + text:"observe.common.ersId"; + labelFor:{ersId}; +} + +#resetErsId{ + toolTipText:"observe.content.action.reset.ersId.tip"; + _resetPropertyName:{TripSeineDto.PROPERTY_ERS_ID}; +} + +#ersId { + _propertyName:{TripSeineDto.PROPERTY_ERS_ID}; + text:{getStringValue(bean.getErsId())}; +} + +#startDateLabel { + text:"observe.common.startDate"; + labelFor:{startDate}; +} + +#startDate { + _propertyName:{TripSeineDto.PROPERTY_START_DATE}; + date:{bean.getStartDate()}; +} + +#endDateLabel { + text:"observe.common.endDate"; + labelFor:{endDate}; +} + +#endDate { + _propertyName:{TripSeineDto.PROPERTY_END_DATE}; + date:{bean.getEndDate()}; +} + +#formsUrlLabel { + text:"observe.common.formsUrl"; + labelFor:{formsUrl}; +} + +#resetFormsUrl { + _resetPropertyName:{TripSeineDto.PROPERTY_FORMS_URL}; + toolTipText:"observe.content.action.reset.formsUrl.tip"; +} + +#formsUrl { + _propertyName:{TripSeineDto.PROPERTY_FORMS_URL}; + text:{getStringValue(bean.getFormsUrl())}; +} + +#openLinkFormulairesUrl { + actionIcon:"openLink"; + opaque:false; + enabled:{!isEmpty(bean.getFormsUrl())}; + toolTipText:"observe.content.action.openLink.formsUrl.tip"; + _notBlocking:true; +} + +#reportsUrlLabel { + text:"observe.common.reportsUrl"; + labelFor:{reportsUrl}; +} + +#resetReportsUrl { + _resetPropertyName:{TripSeineDto.PROPERTY_REPORTS_URL}; + toolTipText:"observe.content.action.reset.reportsUrl.tip"; +} + +#reportsUrl { + _propertyName:{TripSeineDto.PROPERTY_REPORTS_URL}; + text:{getStringValue(bean.getReportsUrl())}; +} + +#openLinkRapportsUrl { + actionIcon:"openLink"; + opaque:false; + enabled:{!isEmpty(bean.getReportsUrl())}; + toolTipText:"observe.content.action.openLink.reportsUrl.tip"; + _notBlocking:true; +} + +#comment { + columnHeaderView:{new JLabel(t("observe.common.comment"))}; + minimumSize:{new Dimension(10,50)}; +} + +#comment2 { + text:{getStringValue(bean.getComment())}; +} + +#reopen { + _toolTipText:{t("observe.content.action.reopen.maree.tip")}; +} + +#close { + enabled:{!model.isModified() && (model.isHistoricalData() || model.isValid()) && !dataContext.isOpenRoute()}; + _toolTipText:{t("observe.action.close.maree.tip")}; +} + +#closeAndCreate { + enabled:{!model.isModified() && (model.isHistoricalData() || model.isValid()) && !dataContext.isOpenRoute()}; + _text:{t("observe.content.action.closeAndCreate.maree")}; + _toolTipText:{t("observe.content.action.closeAndCreate.maree.tip")}; +} + +#delete { + _toolTipText:{t("observe.action.delete.maree.tip")}; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/TripSeineUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/TripSeineUIHandler.java new file mode 100644 index 0000000..3c30aac --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/TripSeineUIHandler.java @@ -0,0 +1,370 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.open.impl.seine; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.TripMapDto; +import fr.ird.observe.services.dto.referential.PersonDtos; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.VesselDtos; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.services.dto.seine.TripSeineDtos; +import fr.ird.observe.services.service.seine.TripSeineService; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.open.ContentOpenableUIHandler; +import fr.ird.observe.application.swing.ui.content.open.ContentOpenableUIModel; +import fr.ird.observe.application.swing.ui.util.tripMap.TripMapUI; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.util.DateUtil; + +import javax.swing.JTabbedPane; +import javax.swing.SwingUtilities; +import java.util.Collection; +import java.util.Date; +import java.util.LinkedList; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class TripSeineUIHandler extends ContentOpenableUIHandler<TripSeineDto> { + + /** Logger */ + static private final Log log = LogFactory.getLog(TripSeineUIHandler.class); + + protected boolean buildTripMap = true; + + public TripSeineUIHandler(TripSeineUI ui) { + super(ui, + DataContextType.Program, + DataContextType.TripSeine, + n("observe.content.tripSeine.message.not.open")); + } + + + @Override + public TripSeineUI getUi() { + return (TripSeineUI) super.getUi(); + } + + @Override + public boolean doCloseData() { + boolean result = getOpenDataManager().isOpenTripSeine(getSelectedId()); + if (result) { + getOpenDataManager().closeTripSeine(getSelectedId()); + } + return result; + } + + @Override + public void initUI() { + super.initUI(); + + TripSeineUI ui = getUi(); + TripMapUI tripMap = ui.getTripMap(); + ObserveSwingApplicationConfig config = ObserveSwingApplicationContext.get().getConfig(); + + tripMap.getHandler().setConfig(config); + + getUi().getTripSeineTabPane().addChangeListener(e -> { + JTabbedPane tripSeineTabPane = (JTabbedPane) e.getSource(); + TripSeineUI ui1 = getUi(); + TripMapUI tripMap1 = ui1.getTripMap(); + if (tripSeineTabPane.getSelectedComponent().equals(tripMap1)) { + ui1.getActions().setVisible(false); + + if (buildTripMap) { + SwingUtilities.invokeLater(() -> { + + TripSeineUI ui11 = getUi(); + TripMapUI tripMap11 = ui11.getTripMap(); + TripMapDto tripSeineMap = getTripSeineService().getTripSeineMap(getSelectedId()); + + + tripMap11.getHandler().doOpenMap(tripSeineMap); + }); + buildTripMap = false; + } + + } else { + ui1.getActions().setVisible(true); + } + }); + + } + + @Override + public void openUI() { + super.openUI(); + + ContentMode mode = computeContentMode(); + + String programId = getSelectedParentId(); + final String tripId = getSelectedId(); + + if (log.isInfoEnabled()) { + log.info(prefix + "programId = " + programId); + log.info(prefix + "tripId = " + tripId); + log.info(prefix + "mode = " + mode); + } + + TripSeineDto bean = getBean(); + + boolean create = tripId == null; + + Form<TripSeineDto> form; + if (create) { + + // create mode + if (log.isInfoEnabled()) { + log.info(prefix + "create a new trip"); + } + form = getTripSeineService().preCreate(programId); + + } else { + + // update mode + if (log.isInfoEnabled()) { + log.info(prefix + "load existing trip " + tripId); + } + form = getTripSeineService().loadForm(tripId); + + } + + setContentMode(mode); + + loadReferentialReferenceSetsInModel(form); + + getModel().setForm(form); + TripSeineDtos.copyTripSeineDto(form.getObject(), bean); + + getUi().getTripSeineTabPane().setSelectedIndex(0); + getUi().getTripMap().getHandler().doCloseMap(); + buildTripMap = true; + + finalizeOpenUI(mode, create); + } + + @Override + public void startEditUI(String... binding) { + + TripSeineUI ui = getUi(); + + ContentOpenableUIModel<TripSeineDto> model = getModel(); + + ContentMode mode = model.getMode(); + + boolean create = mode == ContentMode.CREATE; + + String contextName = getValidatorContextName(mode); + ui.getValidator().setContext(contextName); + + if (create) { + + addInfoMessage(t("observe.content.tripSeine.message.creating")); + } else { + addInfoMessage(t("observe.content.tripSeine.message.updating")); + if (model.isHistoricalData()) { + + addInfoMessage(t("observe.message.historical.data")); + } + } + + // date is current day + if (model.getMode() == ContentMode.UPDATE) { + if (getBean().getEndDate() == null) { + Date date = DateUtil.getEndOfDay(new Date()); + getBean().setEndDate(date); + if (log.isDebugEnabled()) { + log.debug("end date : " + date); + } + } + } + + super.startEditUI(TripSeineUI.BINDING_VESSEL_SELECTED_ITEM, + TripSeineUI.BINDING_OBSERVER_SELECTED_ITEM, + TripSeineUI.BINDING_CAPTAIN_SELECTED_ITEM, + TripSeineUI.BINDING_DATA_ENTRY_OPERATOR_SELECTED_ITEM, + TripSeineUI.BINDING_OCEAN_SELECTED_ITEM, + TripSeineUI.BINDING_START_DATE_DATE, + TripSeineUI.BINDING_END_DATE_DATE, + TripSeineUI.BINDING_COMMENT2_TEXT, + TripSeineUI.BINDING_ERS_ID_TEXT, + TripSeineUI.BINDING_CLOSE_ENABLED, + TripSeineUI.BINDING_CLOSE_AND_CREATE_ENABLED); + model.setModified(create); + } + + @Override + protected boolean doOpenData() { + boolean result = getOpenDataManager().canOpenTripSeine(); + if (result) { + getOpenDataManager().openTripSeine(getSelectedParentId(), getSelectedId()); + } + return result; + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + String tripSeineId = getSelectedId(); + + if (tripSeineId == null) { + + // maree en cours de creation + return ContentMode.CREATE; + } + + if (getOpenDataManager().isOpenTripSeine(tripSeineId)) { + + // maree ouverte + return ContentMode.UPDATE; + } + + addInfoMessage(t(closeMessage)); + return ContentMode.READ; + + } + + @Override + protected boolean doSave(TripSeineDto bean) throws Exception { + + boolean notPersisted = bean.isNotPersisted(); + + // on force toujours la date a etre sans heure, minute,... + Date startDate = DateUtil.getDay(bean.getStartDate()); + if (log.isDebugEnabled()) { + log.debug("startDate = " + startDate); + } + bean.setStartDate(startDate); + + Date endDate = bean.getEndDate(); + if (log.isDebugEnabled()) { + log.debug("endDate = " + endDate); + } + + SaveResultDto saveResult = getTripSeineService().save(bean); + saveResult.toDto(bean); + + // recuperation de la position de la maree dans le program + obtainChildPosition(bean); + + // ouverture de la marée + if (notPersisted) { + getOpenDataManager().openTripSeine(getSelectedParentId(), bean.getId()); + } + + return true; + } + + protected int getOpenablePosition(String parentId, TripSeineDto bean) { + + int position = getTripSeineService().getTripSeinePositionInProgram(parentId, bean.getId()); + + return position; + } + + @Override + protected boolean doDelete(TripSeineDto bean) { + + if (askToDelete(bean)) { + return false; + } + if (log.isInfoEnabled()) { + log.info("Will delete Trip " + bean.getId()); + } + + getTripSeineService().delete(bean.getId()); + getOpenDataManager().closeTripSeine(bean.getId()); + + if (log.isInfoEnabled()) { + log.info("Delete done for Trip " + bean.getId()); + } + return true; + } + + @Override + protected boolean obtainCanReopen(boolean create) { + return !create && getOpenDataManager().canOpenTripSeine(); + } + + @Override + protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { + + Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); + + switch (propertyName) { + + case TripSeineDto.PROPERTY_CAPTAIN: { + result = (List) PersonDtos.filterCaptainReferences((List) result); + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + } + break; + + case TripSeineDto.PROPERTY_OBSERVER: { + result = (List) PersonDtos.filterObserverReferences((List) result); + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + } + break; + + case TripSeineDto.PROPERTY_DATA_ENTRY_OPERATOR: { + result = (List) PersonDtos.filterDataEntryOperatorReferences((List) result); + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + } + break; + + case TripSeineDto.PROPERTY_VESSEL: { + ObserveSwingApplicationConfig config = ObserveSwingApplicationContext.get().getConfig(); + result = (List) VesselDtos.filterVesselReferencesByVesselTypeIds((List) result, config.getSeineVesselTypeIds()); + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + } + break; + + } + + return result; + } + + protected TripSeineService getTripSeineService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripSeineService(); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/TripSeineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/TripSeineUIModel.java new file mode 100644 index 0000000..67c289c --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/open/impl/seine/TripSeineUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.open.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.application.swing.ui.content.open.ContentOpenableUIModel; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class TripSeineUIModel extends ContentOpenableUIModel<TripSeineDto> { + + private static final long serialVersionUID = 1L; + + public TripSeineUIModel() { + super(TripSeineDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/package.html b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/package.html similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/package.html rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/package.html diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ContentReferenceUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ContentReferenceUI.jaxx new file mode 100644 index 0000000..26f4b89 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ContentReferenceUI.jaxx @@ -0,0 +1,201 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ContentUI abstract='true' + superGenericType='E' + genericType='E extends ReferentialDto'> + + <import> + fr.ird.observe.services.dto.referential.ReferentialDto + fr.ird.observe.services.dto.referential.ReferentialReference + + fr.ird.observe.application.swing.ui.UIHelper + fr.ird.observe.application.swing.ui.actions.shared.DeleteReferenceUIAction + fr.ird.observe.application.swing.ui.actions.shared.ResetEditUIAction + fr.ird.observe.application.swing.ui.actions.shared.SaveEditUIAction + + jaxx.runtime.swing.editor.bean.BeanListHeader + jaxx.runtime.validator.swing.SwingValidator + + javax.swing.DefaultListModel + javax.swing.ListSelectionModel + javax.swing.JTable + javax.swing.UIManager + javax.swing.table.TableCellRenderer + </import> + + <java.lang.String id='listText' javaBean='""'/> + <java.lang.String id='createToolTip' javaBean='""'/> + <java.lang.String id='detailToolTip' javaBean='""'/> + <java.lang.String id='modifyToolTip' javaBean='""'/> + <java.lang.String id='deleteToolTip' javaBean='""'/> + <java.lang.String id='saveToolTip' javaBean='""'/> + + <ContentReferenceUIModel id='model' genericType='E'/> + + <ContentReferenceUIHandler id='handler' genericType='E' constructorParams='this'/> + + <BlockingLayerUI id='editKeyTableLayerUI'/> + + <CardLayout2Ext id='viewLayout' constructorParams='this, "body"'/> + + <script><![CDATA[ + +public static final String LIST_VIEW = "listView"; + +public static final String DETAIL_VIEW = "detailView"; + +public abstract SwingValidator<E> getValidator(); + +public void decorateUniqueKeyTable(JTable table, + TableCellRenderer renderer, + JScrollPane pane) { + table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); + UIHelper.fixTableColumnWidth(table, 1, 70); +} + +body.setLayout(viewLayout); +viewLayout.addLayoutComponent(listView, LIST_VIEW); +viewLayout.addLayoutComponent(editView, DETAIL_VIEW); + +]]></script> + + <JPanel id="body"> + + <JPanel id="listView" constraints="LIST_VIEW"> + <JScrollPane id='listPane' constraints='BorderLayout.CENTER' columnHeaderView='{referentialListHeader}'> + <JList id='list' + onValueChanged='if (!event.getValueIsAdjusting()) { getHandler().selectBean((ReferentialReference<E>)getSelectedBean(list)); }' + onMouseClicked='if (event.getClickCount() == 2) { getHandler().modifyUI(); }'/> + + <BeanListHeader id='referentialListHeader' genericType='ReferentialReference<E>' _entityClass="getModel().getBeanType()"/> + </JScrollPane> + </JPanel> + + <Table id="editView" insets="0" weightx="1" fill="both" + constraints="DETAIL_VIEW"> + <row> + <cell anchor='north'> + <!-- pour les autres propriétés du référentiel à editer --> + <Table id='editTable' fill='both' insets="1"/> + </cell> + </row> + <row> + <cell anchor='north'> + <!-- pour les autres propriétés du référentiel à editer --> + <Table id='editExtraTable' fill='both' insets="1"/> + </cell> + </row> + <row> + <cell anchor='north'> + <!-- pour les propriétés i18n du référentiel à editer --> + <Table id='editI18nTable' fill='both' insets="1"/> + </cell> + </row> + <row> + <cell anchor='north' weighty="1"> + <!-- pour les autres propriétés (à mettre après i18n) à editer --> + <Table id='editMoreExtraTable' fill='both' insets="1"> + <row> + <cell> + <javax.swing.Box.Filler id='filler' + constructorParams='UIHelper.newMinDimension(), UIHelper.newMinDimension(), UIHelper.newMaxXDimension()'/> + </cell> + </row> + </Table> + </cell> + </row> + <!--row> + <cell weighty="1" anchor='north'> + <javax.swing.Box.Filler id='filler' + constructorParams='UIHelper.newMinDimension(), UIHelper.newMinDimension(), UIHelper.newMaxXDimension()'/> + </cell> + </row--> + </Table> + + </JPanel> + + <Table id='actions' fill='both' weightx='1' insets='0'> + <row> + <cell> + <Table id="listActions" fill="both" weightx="1" insets="1" visible='{!model.isEditing()}'> + <row> + <cell> + <JButton id='create' onActionPerformed='getHandler().createUI()'/> + </cell> + <cell> + <JButton id='modify' onActionPerformed='getHandler().modifyUI()'/> + </cell> + <cell> + <JButton id='detail' onActionPerformed='getHandler().modifyUI()'/> + </cell> + <cell> + <JButton id='deleteFromList' styleClass='delete'/> + </cell> + </row> + </Table> + </cell> + </row> + <row> + <cell> + <Table id="detailActions" fill='both' insets="1,4,1,1" + visible='{model.isEditing()}'> + <row> + <cell fill="both" weightx="1"> + <Table fill="both" weightx="1" insets="1" visible='{!model.isReadingMode()}'> + <row> + <cell> + <JButton id='reset'/> + </cell> + <cell> + <JButton id='save'/> + </cell> + <cell> + <JButton id='deleteFromDetail' styleClass='delete'/> + </cell> + </row> + </Table> + </cell> + </row> + <row> + <cell fill="both" weightx="1"> + <JButton id='backToList' onActionPerformed='getHandler().backToList()'/> + <!--onActionPerformed='getHandelr().backToList();if (!model.isModified() || fr.ird.observe.application.swing.ui.content.ContentUIHandler.checkEdit(this)) { stopEdit(); }'/--> + </cell> + </row> + </Table> + </cell> + </row> + </Table> + + <JPanel id="invisible"> + + <JButton id="showUsages" onActionPerformed='getHandler().showUsages()'/> + + <JButton id='showUniqueKeys' onActionPerformed='getHandler().showUniqueKeys((JButton) event.getSource());'/> + + <JButton id='showTechnicalInformations' + onActionPerformed='getHandler().showTechnicalInformations((JButton) event.getSource());'/> + + </JPanel> + +</fr.ird.observe.application.swing.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ContentReferenceUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ContentReferenceUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ContentReferenceUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ContentReferenceUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ContentReferenceUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ContentReferenceUIHandler.java new file mode 100644 index 0000000..66f342c --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ContentReferenceUIHandler.java @@ -0,0 +1,828 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.ref; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.services.dto.ReferenceMap; +import fr.ird.observe.services.dto.constants.ReferenceStatus; +import fr.ird.observe.services.dto.constants.ReferentialLocale; +import fr.ird.observe.services.dto.reference.request.ReferenceSetRequestDefinitions; +import fr.ird.observe.services.dto.referential.I18nReferentialDto; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.VesselSizeCategoryDto; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.service.DataNotFoundException; +import fr.ird.observe.services.service.ReferentialService; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.ContentUIHandler; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import fr.ird.observe.application.swing.ui.usage.UsagesUI; +import fr.ird.observe.application.swing.ui.util.SpringUtilities; +import fr.ird.observe.application.swing.validation.ValidationContext; +import jaxx.runtime.JAXXContext; +import jaxx.runtime.swing.CardLayout2Ext; +import jaxx.runtime.swing.editor.bean.BeanListHeader; +import jaxx.runtime.validator.swing.SwingValidatorUtil; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.time.FastDateFormat; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.decorator.Decorator; +import org.nuiton.util.beans.Binder; +import org.nuiton.util.beans.BinderFactory; + +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JPopupMenu; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.JToolBar; +import javax.swing.RowSorter; +import javax.swing.SortOrder; +import javax.swing.SpringLayout; +import javax.swing.SwingUtilities; +import javax.swing.border.TitledBorder; +import javax.swing.table.DefaultTableCellRenderer; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.Font; +import java.beans.Introspector; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Locale; +import java.util.Set; + +import static org.nuiton.i18n.I18n.t; + +/** + * Controleur d'un écran d'édition du référentiel. + * + * @param <E>le type d'entité + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ContentReferenceUIHandler<E extends ReferentialDto> extends ContentUIHandler<E> { + + /** Logger */ + private static final Log log = + LogFactory.getLog(ContentReferenceUIHandler.class); + + private final Runnable revalidate; + + private final ReferentialContentUIInitializer<E, ContentReferenceUI<E>> uiInitializer; + + private final FastDateFormat dateFormat; + + public ContentReferenceUIHandler(ContentReferenceUI<E> ui) { + super(ui, null, null); + uiInitializer = new ReferentialContentUIInitializer<>(ui); + Locale locale = ui.getConfig().getLocale(); + if (Locale.ENGLISH.equals(locale)) { + dateFormat = FastDateFormat.getInstance("yyyy-MM-ddZZ"); + } else { + dateFormat = FastDateFormat.getInstance("dd/MM/yyyy"); + } + + revalidate = () -> { + + // revalidate ui layout + ContentReferenceUI<E> ui1 = getUi(); + Container parent = ui1.getParent(); + if (parent == null) { + + // plus de parent donc rien a faire + return; + } + if (log.isDebugEnabled()) { + log.debug("Will revalidate " + parent.getName()); + } + ui1.revalidate(); + }; + } + + public static <E extends IdDto> void showUsagesForDelete(JAXXContext tx, + E entity, + ReferenceMap usages) { + + DecoratorService service = ObserveSwingApplicationContext.get().getDecoratorService(); + Decorator<?> decorator = service.getDecoratorByType(entity.getClass()); + String type = DecoratorService.getEntityLabel(entity.getClass()); + type = t(type); + String message = t("observe.message.show.usage.for.delete", type, decorator.toString(entity)); + String message2 = t("observe.message.show.usage.for.delete2"); + + UsagesUI usagesUI = new UsagesUI(tx); + usagesUI.init(message, message2, null, usages); + + UIHelper.askUser(null, + t("observe.title.can.not.delete.referentiel"), + usagesUI, + JOptionPane.WARNING_MESSAGE, + new Object[]{ + t("observe.choice.cancel")}, + 0); + } + + public static <E extends IdDto> boolean showUsagesForDesactivated(JAXXContext tx, + E entity, + ReferenceMap usages) { + + DecoratorService service = ObserveSwingApplicationContext.get().getDecoratorService(); + Decorator<?> decorator = service.getDecoratorByType(entity.getClass()); + String type = DecoratorService.getEntityLabel(entity.getClass()); + type = t(type); + String message = t("observe.message.show.usage.for.desactivated", type, decorator.toString(entity)); + String message2 = t("observe.message.show.usage.for.desactivated2"); + String message3 = t("observe.message.show.usage.for.desactivated3"); + + UsagesUI usagesUI = new UsagesUI(tx); + usagesUI.init(message, message2, message3, usages); + + int reponse = UIHelper.askUser(null, + t("observe.title.need.confirm.to.desactivate.referentiel"), + usagesUI, + JOptionPane.WARNING_MESSAGE, + new Object[]{ + t("observe.choice.save"), + t("observe.choice.cancel")}, + 0); + if (log.isDebugEnabled()) { + log.debug("response : " + reponse); + } + + switch (reponse) { + case 0: + // will save ui + return true; + + } + // any other case : do not save + return false; + } + + public void selectBean(ReferentialReference<E> selectedReference) { + + if (selectedReference != null) { + + Form<E> form = getReferentialService().loadForm(getBeanType(), selectedReference.getId()); + getModel().setForm(form); + + E selectedBean = form.getObject(); + + getModel().setSelectedBean(selectedBean); + + // copy right now the selected bean to the model bean to respect contract + // of parent handler (for delation or save object...) + + Binder<E, E> binder = BinderFactory.newBinder(getBeanType()); + binder.copy(selectedBean, getBean()); + + //TODO update data cache + } + + } + + @Override + public ContentReferenceUI<E> getUi() { + return (ContentReferenceUI<E>) super.getUi(); + } + + @Override + public ContentReferenceUIModel<E> getModel() { + return getUi().getModel(); + } + + @Override + protected boolean computeCanWrite(ObserveSwingDataSource source) { + return source.canWriteReferential(); + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + addInfoMessage(t("observe.message.referentiel.editable")); + + return ContentMode.UPDATE; + } + + /** + * Pour afficher une popup avec l'ensemble des clefs metiers utilisées. + * + * @param button le boutton qui a declanche l'action + */ + public void showUniqueKeys(JButton button) { + Class<E> beanType = getBeanType(); + + Set<ReferentialReference<E>> entities = getDataSource().getReferentialReferences(beanType); + List<Object[]> datas = new ArrayList<>(entities.size()); + + String[] naturalIds = getModel().getNaturalIds(); + int nbColumns = naturalIds.length + 1; + + String[] columns = new String[nbColumns]; + System.arraycopy(naturalIds, 0, columns, 1, naturalIds.length); + columns[0] = StringUtils.removeEnd(Introspector.decapitalize(beanType.getSimpleName()), "Dto"); + + DecoratorService dService = getDecoratorService(); + ReferentialReferenceDecorator<E> decorator = dService.getReferentialReferenceDecorator(beanType); + + for (ReferentialReference<E> e : entities) { + + Object[] data = new Object[nbColumns]; + int index = 0; + data[0] = decorator.toString(e); + + for (String property : naturalIds) { + Object o = null; + if (e.getPropertyNames().contains(property)) { + o = e.getPropertyValue(property); + } + if (ContentReferenceUIModel.DEFAULT_PROPERTIES[0].equals(property) && o == null) { + // cas special du code à 0, le loador ne retourne pas + // de valeur car c'est la valeur par defaut d'un type + // primitif, on force donc l'utilisation du zero. + o = 0; + } + if ("code".equals(property) && o == null) { + // cas special du code à 0, le loador ne retourne pas + // de valeur car c'est la valeur par defaut d'un type + // primitif, on force donc l'utilisation du zero. + o = 0; + } + if ("gender".equals(property) && o == null) { + // cas special du code à 0, le loador ne retourne pas + // de valeur car c'est la valeur par defaut d'un type + // primitif, on force donc l'utilisation du zero. + o = 0; + } + Object value; + if (o instanceof ReferentialDto) { + // on doit decorer la valeur + Decorator<?> d = dService.getDecoratorByType(o.getClass()); + value = d.toString(o); + } else { + value = o; + } + data[++index] = value; + } + datas.add(data); + } + + JTable table = new JTable(new UniqueKeyTableModel(columns, datas)); + + table.setAutoCreateRowSorter(true); + table.getRowSorter().setSortKeys(Collections.singletonList(new RowSorter.SortKey(0, SortOrder.ASCENDING))); + table.setFillsViewportHeight(true); + JScrollPane pane = new JScrollPane(); + + getUi().decorateUniqueKeyTable(table, new DefaultTableCellRenderer(), pane); + + pane.setViewportView(table); + pane.setVerticalScrollBarPolicy( + JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); + + String title = t("observe.title.unique.key", + t(DecoratorService.getEntityLabel(beanType))); + + pane.setBorder(new TitledBorder(title)); + + JPopupMenu popup = new JPopupMenu(); + popup.setBorder(null); + popup.add(pane); + popup.pack(); + Dimension dim = popup.getPreferredSize(); + int x = (int) (button.getPreferredSize().getWidth() - dim.getWidth()); + int y = button.getHeight(); + popup.show(button, x, y); + } + + public void showUsages() { + + E bean; + + if (getModel().isEditing()) { + bean = getModel().getBean(); + } else { + bean = getModel().getSelectedBean(); + } + + // recherche des utilisation du bean dans la base + ReferenceMap usages; + try { + usages = getReferentialService().findAllUsages(bean); + + } catch (DataNotFoundException e) { + UIHelper.handlingError(e); + return; + } + + DecoratorService dService = getDecoratorService(); + Decorator<?> decorator = dService.getDecoratorByType(bean.getClass()); + String type = DecoratorService.getEntityLabel(bean.getClass()); + type = t(type); + String message = t("observe.message.show.usages", type, decorator.toString(bean)); + + ContentReferenceUI<E> ui = getUi(); + + UsagesUI usagesUI = new UsagesUI(ui); + usagesUI.init(message, null, null, usages); + + UIHelper.askUser(ui, + t("observe.title.show.usage"), + usagesUI, + JOptionPane.INFORMATION_MESSAGE, + new Object[]{t("observe.choice.quit")}, + 0); + } + + /** + * Pour afficher une popup avec l'ensemble des informations techniques. + * + * @param button le boutton qui a declanche l'action + */ + public void showTechnicalInformations(JButton button) { + + ReferentialDto bean = getModel().isEditing() ? getBean() : getModel().getSelectedBean(); + + JPanel content = new JPanel(new SpringLayout()); + + content.add(new JLabel(t("observe.common.topiaId"))); + content.add(new JLabel(bean.getId())); + + content.add(new JLabel(t("observe.common.topiaCreateDate"))); + + content.add(new JLabel(dateFormat.format(bean.getCreateDate()))); + + content.add(new JLabel(t("observe.common.lastUpdateDate"))); + + content.add(new JLabel(dateFormat.format(bean.getLastUpdateDate()))); + + content.add(new JLabel(t("observe.common.topiaVersion"))); + content.add(new JLabel(String.valueOf(bean.getVersion()))); + + SpringUtilities.makeCompactGrid(content, 4, 2, 5, 5, 5, 5); + + Decorator<E> decorator = getDecoratorService().getDecoratorByType(getBeanType()); + + String title = t("observe.title.technical.informations", + "\n" + decorator.toString(bean)); + + content.setBorder(new TitledBorder(title)); + + JPopupMenu popup = new JPopupMenu(); + popup.setBorderPainted(true); + popup.add(content); + popup.pack(); + Dimension dim = popup.getPreferredSize(); + int x = (int) (button.getPreferredSize().getWidth() - dim.getWidth()); + int y = button.getHeight(); + popup.show(button, x, y); + } + + @Override + public void initUI() { + + uiInitializer.initUI(); + + ContentReferenceUI<E> ui = getUi(); + + ui.getViewLayout().addPropertyChangeListener(CardLayout2Ext.SELECTED_PROPERTY_NAME, + evt -> SwingUtilities.invokeLater(revalidate)); + +// UIHelper.getLayer(ui.getEditKeyTable()).setUI(ui.getEditKeyTableLayerUI()); + } + + @Override + public void openUI() { + super.openUI(); + + ContentReferenceUIModel<E> model = getModel(); + + ReferenceSetRequestDefinitions requestDefinition = ReferenceSetRequestDefinitions.get(getBeanType()); + loadReferentialReferenceSetsInModel(requestDefinition.name()); + + // Chargement des données + updateUiWithReferenceSetsFromModel(); + + ContentReferenceUI<E> ui = getUi(); + + if (I18nReferentialDto.class.isAssignableFrom(model.getBeanType())) { + // on met en gras le libelle selectionne en base + + ReferentialLocale localeEnum; + localeEnum = ReferentialLocale.valueOf( + ui.getConfig().getDbLocale()); + String libelleName = localeEnum.getLibelle() + "Label"; + for (int i = 1; i <= 8; i++) { + String lib = "label" + i + "Label"; + JLabel label = (JLabel) ui.getObjectById(lib); + if (label == null) { + // not in ui actually + continue; + } + Font font = label.getFont(); + Font normalFont = font.deriveFont(Font.PLAIN); + Font boldFont = font.deriveFont(Font.BOLD); + + if (libelleName.equals(lib)) { + // on met en gras le label + font = boldFont; + } else { + // on met en normal le label + font = normalFont; + } + label.setFont(font); + ((JComponent) ui.getObjectById("label" + i)).setFont(font); + } + } + ContentMode mode = computeContentMode(); + model.setMode(mode); + if (mode != ContentMode.READ) { + //FIXME le binding ne marche pas en init + ui.processDataBinding(ContentReferenceUI.BINDING_DELETE_FROM_LIST_ENABLED); + } + } + + @Override + protected void updateToolbarActions() { + + // nettoyage de la toolbar + super.updateToolbarActions(); + + // on ajoute les deux actions showUsages et showUniqueKeys + ContentReferenceUI<E> ui = getUi(); + JToolBar toolBar = ui.getTitleRightToolBar(); + toolBar.add(ui.getShowUniqueKeys(), 2); + toolBar.add(ui.getShowTechnicalInformations(), 2); + toolBar.add(ui.getShowUsages(), 2); + } + + @Override + public void startEditUI(String... binding) { + + ContentReferenceUI<E> ui = getUi(); + + ContentReferenceUIModel<E> model = getModel(); + + E bean = model.getBean(); + ContentMode mode = model.getMode(); + boolean canEdit = mode != ContentMode.READ; + if (canEdit) { + removeAllMessages(ui); + String contextName = getValidatorContextName(mode); + if (log.isDebugEnabled()) { + log.debug("contextName = " + contextName); + } + ui.getValidator().setContext(contextName); + + if (mode == ContentMode.CREATE) { + addInfoMessage(t("observe.message.creating.referentiel")); + + // creation mode + Form<E> form = getReferentialService().preCreate(getBeanType()); + + loadReferentialReferenceSetsInModel(form); + + getModel().setForm(form); + + copyIntoBean(form.getObject(), bean); + + } else { + addInfoMessage(t("observe.message.updating.referentiel")); + } + + // do edit + super.startEditUI(model.getDataBinding()); + + if (mode == ContentMode.UPDATE) { + + // nothing has changed just after starting editing + ui.getValidator().setChanged(false); + } + } else { + + // reset all validators + SwingValidatorUtil.setValidatorBean(ui, null); + + // load bean + UIHelper.processDataBinding(ui, model.getDataBinding()); + + // pass in editing mode (without any modification possible) + model.setEditing(true); + + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ValidationContext validationContext = applicationContext.getValidationContext(); + validationContext.cleanCache(); + } + } + + protected void reloadReferentialReferenceSetsInModel(Form<E> form) { + + loadReferentialReferenceSetsInModel(form); + + updateReferentialBeanListHeader(getModel().getBeanType(), getUi().getReferentialListHeader()); + + } + + @Override + protected void prepareValidationContext() { + super.prepareValidationContext(); + BeanListHeader<ReferentialReference<E>> jList = getUi().getReferentialListHeader(); + List<ReferentialReference<E>> data = jList.getData(); + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ValidationContext validationContext = applicationContext.getValidationContext(); + if (log.isDebugEnabled()) { + log.debug("Set referentiel list [" + getBeanType().getSimpleName() + "] in validation context : " + data.size()); + } + validationContext.setEditingReferentielList(data); + } + +// @Override +// public boolean closeUI() throws Exception { +// return super.closeUI(); +// } + + public final void createUI() { + + ContentReferenceUI<E> ui = getUi(); + + // force le mode creation + getModel().setMode(ContentMode.CREATE); + + if (log.isDebugEnabled()) { + log.debug("Will create new entity [" + getModel().getBeanType() + "]"); + } + + copyIntoBean(null, getBean()); + + // on demarre l'edition + ui.startEdit(null); + } + + public void modifyUI() { + + ContentReferenceUIModel<E> model = getModel(); + if (model.getMode() != ContentMode.READ) { + + // force le mode mise a jour + model.setMode(ContentMode.UPDATE); + } + + copyIntoBean(model.getSelectedBean(), getBean()); + + getUi().startEdit(null); + } + + @Override + public void stopEditUI() { + super.stopEditUI(); + + ContentReferenceUI<E> ui = getUi(); + ContentReferenceUIModel<E> model = getModel(); + + if (model.getMode() != ContentMode.READ) { + + // on retourne en mode mise a jour sur la liste + model.setMode(ContentMode.UPDATE); + removeAllMessages(ui); + addInfoMessage(t("observe.message.referentiel.editable")); + } + + updateUiWithReferenceSetsFromModel(); + + } + + @Override + public final void resetEditUI() { + + ContentMode mode = getModel().getMode(); + super.resetEditUI(); + if (mode == ContentMode.CREATE) { + createUI(); + } else { + modifyUI(); + } + } + + public void backToList() { + ContentReferenceUIModel<E> model = getModel(); + if (!model.isModified() || checkEdit(getUi())) { + getUi().stopEdit(); + + // then resynch the selected bean to edit bean (used for example to delete)... + // repush selected bean to bean + + copyIntoBean(model.getSelectedBean(), getBean()); + } + } + + @Override + protected boolean doSave(E bean) throws Exception { + + ContentReferenceUIModel<E> model = getModel(); + + if (bean.getId() == null) { + + if (log.isInfoEnabled()) { + log.info("Create referentiel " + bean); + } + + SaveResultDto saveResult = getReferentialService().save(bean); + + saveResult.toDto(bean); + + if (bean instanceof ProgramDto) { + + // add the program in tree + ObserveTreeHelper treeHelper = getTreeHelper(getUi()); + ReferentialReference<ProgramDto> reference = ObserveSwingApplicationContext.get().getReferenceBinderEngine().transformReferentialDtoToReference(getDecoratorService().getReferentialLocale(), (ProgramDto) bean); + treeHelper.addProgram(reference); + + } + + // on met a jour le referentiel dans le cache et le model + ReferenceSetRequestDefinitions requestDefinition = ReferenceSetRequestDefinitions.get(getBeanType()); + loadReferentialReferenceSetsInModel(requestDefinition.name()); + + return true; + } + + if (log.isInfoEnabled()) { + log.info("Will update exisintg entity : " + bean.getId()); + } + // le bean original + E oldBean = model.getSelectedBean(); + + if (oldBean != null && + oldBean.getStatus() == ReferenceStatus.enabled && + bean.getStatus() == ReferenceStatus.disabled) { + + // l'entite a ete desactive + // on recherche les objets utilisant cette entitee + // on indique a l'utilisateur ce changement + if (log.isDebugEnabled()) { + log.debug("entity status was desactivated, looking " + + "for usage"); + } + + ReferenceMap usages = getReferentialService().findAllUsages(bean); + + if (usages.isEmpty()) { + if (log.isInfoEnabled()) { + log.info("No usage found, no warning to display"); + } + } else { + // some usages were found + boolean willsave = showUsagesForDesactivated(getUi(), bean, + usages); + if (!willsave) { + if (log.isDebugEnabled()) { + log.debug("User refuses to continue, skip " + + "saving..."); + } + return false; + } + } + } + + + // sauvegarde du bean d'edition dans le bean de la base + SaveResultDto saveResult = getReferentialService().save(bean); + saveResult.toDto(bean); + + if (bean instanceof ProgramDto) { + + // update the program in tree + ObserveTreeHelper treeHelper = getTreeHelper(getUi()); + treeHelper.updateProgram((ProgramDto) bean); + } + + // on met a jour le referentiel dans le cache et le model + ReferenceSetRequestDefinitions requestDefinition = ReferenceSetRequestDefinitions.get(getBeanType()); + loadReferentialReferenceSetsInModel(requestDefinition.name()); + + return true; + } + + @Override + protected boolean doDelete(E bean) { + + ContentReferenceUI<E> ui = getUi(); + ContentReferenceUIModel<E> model = getModel(); + + if (log.isInfoEnabled()) { + log.info("entity to be deleted, looking for usage"); + } + + // recherche des utilisation du bean dans la base + ReferenceMap usages = getReferentialService().findAllUsages(bean); + + if (MapUtils.isEmpty(usages)) { + if (log.isDebugEnabled()) { + log.debug("No usage found, no warning to display"); + } + } else { + + // some usages were found + if (log.isDebugEnabled()) { + log.debug("can not delete referentiel entity (found usages)"); + } + showUsagesForDelete(ui, bean, usages); + return false; + } + + if (!UIHelper.confirmForEntityDelete(ui, model.getBeanType(), bean)) { + return false; + } + + String beanId = bean.getId(); + getReferentialService().delete(getBeanType(), beanId); + + return true; + } + + @Override + protected void afterDelete() { + E bean = getBean(); + if (bean instanceof ProgramDto) { + + // remove the program in tree + ObserveTreeHelper treeHelper = getTreeHelper(getUi()); + treeHelper.removeProgram(bean.getId()); + } + + // on met a jour le referentiel dans le cache et le model + ReferenceSetRequestDefinitions requestDefinition = ReferenceSetRequestDefinitions.get(getBeanType()); + loadReferentialReferenceSetsInModel(requestDefinition.name()); + + //getModel().setSelectedBean(null); + super.afterDelete(); + } + + protected void afterSave(boolean refresh) { + super.afterSave(refresh); + getUi().stopEdit(); + } + + @Override + protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { + // No filter for referantial screen + return incomingReferences; + } + + public boolean canSeeI18nTable(E bean) { + return bean instanceof I18nReferentialDto || bean instanceof VesselSizeCategoryDto; + } + + public String updateView(boolean editing) { + if (log.isDebugEnabled()) { + log.debug("Editing has changed : " + editing); + } + return editing ? ContentReferenceUI.DETAIL_VIEW : ContentReferenceUI.LIST_VIEW; + } + + protected void copyIntoBean(E source, E target) { + Binder<E, E> binder = BinderFactory.newBinder(getBeanType()); + binder.copy(source, target); + } + + protected ReferentialService getReferentialService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newReferentialService(); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ContentReferenceUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ContentReferenceUIModel.java new file mode 100644 index 0000000..fdc9f23 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ContentReferenceUIModel.java @@ -0,0 +1,259 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.ref; + +import fr.ird.observe.services.dto.referential.I18nReferentialDto; +import fr.ird.observe.services.dto.referential.LengthWeightParameterDto; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Le modèle pour un écran d'édition du référentiel. + * + * @author Tony Chemit - chemit@codelutin.com + * @since .14 + */ +public abstract class ContentReferenceUIModel<E extends ReferentialDto> extends ContentUIModel<E> { + + public static final String PROPERTY_EMPTY = "empty"; + + public static final String PROPERTY_SELECTED_BEAN = "selectedBean"; + + public static final String SUFFIX_TEXT = ".text"; + + public static final String SUFFIX_MODEL = ".model"; + + public static final String SUFFIX_SELECTED_INDEX = ".selectedIndex"; + + public static final String SUFFIX_SELECTED_ITEM = ".selectedItem"; + + public static final String SUFFIX_SELECTED = ".selected"; + + public static final String SUFFIX_DATE = ".date"; + + /** liste des bindings present sur tous les ecrans du referentiel */ + protected final static String[] DEFAULT_DATABINDING = { + ReferentialDto.PROPERTY_CODE + SUFFIX_TEXT, + ReferentialDto.PROPERTY_URI + SUFFIX_TEXT, + ReferentialDto.PROPERTY_STATUS + SUFFIX_SELECTED_INDEX, + ReferentialDto.PROPERTY_NEED_COMMENT + SUFFIX_SELECTED + }; + + /** liste des proprietes presents sur les entites parametrageLengthWeightAble */ + protected final static String[] DEFAULT_LENGTH_WEIGHT_PARAMETER_ABLE_DATABINDING = { + LengthWeightParameterDto.PROPERTY_START_DATE + SUFFIX_DATE, + LengthWeightParameterDto.PROPERTY_END_DATE + SUFFIX_DATE, + LengthWeightParameterDto.PROPERTY_SPECIES + SUFFIX_SELECTED_ITEM, + LengthWeightParameterDto.PROPERTY_OCEAN + SUFFIX_SELECTED_ITEM, + LengthWeightParameterDto.PROPERTY_SEX + SUFFIX_SELECTED_INDEX, + LengthWeightParameterDto.PROPERTY_LENGTH_WEIGHT_FORMULA + SUFFIX_TEXT, + LengthWeightParameterDto.PROPERTY_WEIGHT_LENGTH_FORMULA + SUFFIX_TEXT, + LengthWeightParameterDto.PROPERTY_COEFFICIENTS + SUFFIX_TEXT, + LengthWeightParameterDto.PROPERTY_MEAN_LENGTH + SUFFIX_MODEL, + LengthWeightParameterDto.PROPERTY_MEAN_WEIGHT + SUFFIX_MODEL + }; + + /** liste des bindings presents sur les entites i18n */ + protected final static String[] DEFAULT_I18N_DATABINDING = { + I18nReferentialDto.PROPERTY_LABEL1 + SUFFIX_TEXT, + I18nReferentialDto.PROPERTY_LABEL2 + SUFFIX_TEXT, + I18nReferentialDto.PROPERTY_LABEL3 + SUFFIX_TEXT, + I18nReferentialDto.PROPERTY_LABEL4 + SUFFIX_TEXT, + I18nReferentialDto.PROPERTY_LABEL5 + SUFFIX_TEXT, + I18nReferentialDto.PROPERTY_LABEL6 + SUFFIX_TEXT, + I18nReferentialDto.PROPERTY_LABEL7 + SUFFIX_TEXT, + I18nReferentialDto.PROPERTY_LABEL8 + SUFFIX_TEXT + }; + + /** liste des proprietes present sur tous les ecrans du referentiel */ + protected final static String[] DEFAULT_PROPERTIES = { + ReferentialDto.PROPERTY_CODE, + ReferentialDto.PROPERTY_URI, + ReferentialDto.PROPERTY_STATUS, + ReferentialDto.PROPERTY_NEED_COMMENT + }; + + /** liste des proprietes presents sur les entites taillePoidsAble */ + protected final static String[] DEFAULT_PARAMETRAGE_TAILLE_POIDS_ABLE_PROPERTIES = { + LengthWeightParameterDto.PROPERTY_START_DATE, + LengthWeightParameterDto.PROPERTY_END_DATE, + LengthWeightParameterDto.PROPERTY_OCEAN, + LengthWeightParameterDto.PROPERTY_SPECIES, + LengthWeightParameterDto.PROPERTY_SEX, + LengthWeightParameterDto.PROPERTY_LENGTH_WEIGHT_FORMULA, + LengthWeightParameterDto.PROPERTY_WEIGHT_LENGTH_FORMULA, + LengthWeightParameterDto.PROPERTY_COEFFICIENTS, + LengthWeightParameterDto.PROPERTY_MEAN_LENGTH, + LengthWeightParameterDto.PROPERTY_MEAN_WEIGHT + }; + + /** liste des proprietes presents sur les entites i18n */ + protected final static String[] DEFAULT_I18N_PROPERTIES = { + I18nReferentialDto.PROPERTY_LABEL1, + I18nReferentialDto.PROPERTY_LABEL2, + I18nReferentialDto.PROPERTY_LABEL3, + I18nReferentialDto.PROPERTY_LABEL4, + I18nReferentialDto.PROPERTY_LABEL5, + I18nReferentialDto.PROPERTY_LABEL6, + I18nReferentialDto.PROPERTY_LABEL7, + I18nReferentialDto.PROPERTY_LABEL8 + }; + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(ContentReferenceUIModel.class); + + /** la liste des propriétés du bean a charger */ + protected final String[] properties; + + /** la liste des propriétés faisant partie de la clef metier */ + protected final String[] naturalIds; + + /** la liste des bindings à activer lors de l'ouverture de l'ui */ + protected final String[] dataBinding; + + protected E selectedBean; + + protected ContentReferenceUIModel(Class<E> beanType) { + + this(beanType, null, null, null); + + } + + protected ContentReferenceUIModel(Class<E> beanType, + String[] extraProperties, + String[] extraBindings) { + + this(beanType, extraProperties, null, extraBindings); + + } + + protected ContentReferenceUIModel(Class<E> beanType, + String[] extraProperties, + String[] naturalIds, + String[] extraBindings) { + super(beanType); + + boolean useDefault = naturalIds == null; + + // la clef naturelle par defaut est la premiere des properties + this.naturalIds = useDefault ? new String[]{DEFAULT_PROPERTIES[0]} : naturalIds; + + List<String> properties = buildProperties(useDefault, extraProperties); + this.properties = properties.toArray(new String[properties.size()]); + + List<String> bindings = buildDataBindings(useDefault, extraBindings); + this.dataBinding = bindings.toArray(new String[bindings.size()]); + + + } + + public String[] getNaturalIds() { + return naturalIds; + } + + public String[] getDataBinding() { + return dataBinding; + } + + public E getSelectedBean() { + return selectedBean; + } + + public void setSelectedBean(E selectedBean) { + Object oldvalue = this.selectedBean; + this.selectedBean = selectedBean; + firePropertyChange(PROPERTY_SELECTED_BEAN, oldvalue, selectedBean); + } + + /** + * construction de la liste des propriétés a binder pour une entite. + * + * @param usedefault un drapeau pour savoir si on doit conserver la premiere valeur par defaut + * @param properties les propriétés supplémentaires a ajouter en plus de + * celles communes + * @return la liste des toutes les proprietes utilises sur l'entite edite dans l'ui + */ + protected final List<String> buildProperties(boolean usedefault, String[] properties) { + + List<String> result = new ArrayList<>(); + result.addAll(Arrays.asList(DEFAULT_PROPERTIES)); + if (properties != null) { + result.addAll(Arrays.asList(properties)); + } + Class<E> beanType = getBeanType(); + + if (I18nReferentialDto.class.isAssignableFrom(beanType)) { + result.addAll(Arrays.asList(DEFAULT_I18N_PROPERTIES)); + } + if (LengthWeightParameterDto.class.isAssignableFrom(beanType)) { + result.addAll(Arrays.asList(DEFAULT_PARAMETRAGE_TAILLE_POIDS_ABLE_PROPERTIES)); + } + if (!usedefault) { + + // on supprime le premiere valeur + result.remove(DEFAULT_PROPERTIES[0]); + } + return result; + + } + + /** + * construction de la liste des databindings utiliser pour une entite. + * + * @param usedefault un drapeau pour savoir si on doit conserver la premiere valeur par defaut + * @param dataBinding les bindings supplémentaires a utiliser en plus de + * ceux communs + * @return la liste de tous les databindings utilises sur l'entite edite dans l'ui + */ + protected final List<String> buildDataBindings(boolean usedefault, String[] dataBinding) { + + List<String> result = new ArrayList<>(); + result.addAll(Arrays.asList(DEFAULT_DATABINDING)); + if (dataBinding != null) { + result.addAll(Arrays.asList(dataBinding)); + } + Class<E> beanType = getBeanType(); + + if (I18nReferentialDto.class.isAssignableFrom(beanType)) { + result.addAll(Arrays.asList(DEFAULT_I18N_DATABINDING)); + } + if (LengthWeightParameterDto.class.isAssignableFrom(beanType)) { + result.addAll(Arrays.asList(DEFAULT_LENGTH_WEIGHT_PARAMETER_ABLE_DATABINDING)); + } + if (!usedefault) { + + // on supprime le premier binding + result.remove(DEFAULT_DATABINDING[0]); + } + return result; + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ReferenceHomeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ReferenceHomeUI.jaxx new file mode 100644 index 0000000..9aef95a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ReferenceHomeUI.jaxx @@ -0,0 +1,46 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ContentUI + superGenericType='ProgramDto' + + > + + <import> + fr.ird.observe.services.dto.referential.ProgramDto + fr.ird.observe.application.swing.ui.content.ContentMode + </import> + + <ReferenceHomeUIModel id='model'/> + + <ReferenceHomeUIHandler id='handler' constructorParams='this'/> + + + <Table id='body' fill='both' weighty="1"> + <row weighty="1" weightx="1"> + <cell> + <JLabel id='homeLabel'/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ReferenceHomeUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ReferenceHomeUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ReferenceHomeUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ReferenceHomeUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ReferenceHomeUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ReferenceHomeUIHandler.java new file mode 100644 index 0000000..165d539 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ReferenceHomeUIHandler.java @@ -0,0 +1,53 @@ +package fr.ird.observe.application.swing.ui.content.ref; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.ContentUIHandler; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ReferenceHomeUIHandler extends ContentUIHandler<ProgramDto> { + + public ReferenceHomeUIHandler(ReferenceHomeUI ui) { + super(ui, null, null); + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + return null; + } + + @Override + protected boolean computeCanWrite(ObserveSwingDataSource source) { + return source.canWriteReferential(); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ReferenceHomeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ReferenceHomeUIModel.java new file mode 100644 index 0000000..0628e17 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ReferenceHomeUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ReferenceHomeUIModel extends ContentUIModel<ProgramDto> { + + private static final long serialVersionUID = 1L; + + public ReferenceHomeUIModel() { + super(ProgramDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ReferentialContentUIInitializer.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ReferentialContentUIInitializer.java new file mode 100644 index 0000000..fefc437 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/ReferentialContentUIInitializer.java @@ -0,0 +1,57 @@ +package fr.ird.observe.application.swing.ui.content.ref; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.application.swing.ui.content.ContentUIInitializer; + +/** + * Created on 11/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.9 + */ +public class ReferentialContentUIInitializer<E extends ReferentialDto, UI extends ContentReferenceUI<E>> extends ContentUIInitializer<E, UI> { + +// /** Logger. */ +// private static final Log log = LogFactory.getLog(ReferentialContentUIInitializer.class); + + public ReferentialContentUIInitializer(UI ui) { + super(ui); + } + + @Override + protected void initBlockLayerUI(String... doNotBlockComponentIds) { + + super.initBlockLayerUI(doNotBlockComponentIds); + + //tchemit-2014-12-29 We should use a spearate list for this, but there is no collision possible... + ui.getEditKeyTableLayerUI().setAcceptedComponentNames(doNotBlockComponentIds); + + } + +// protected Decorator<ReferenceDto> getDecorator(Class<? extends ReferentialDto> dtoClass) { +// return ObserveSwingApplicationContext.get().getDecorator(ReferenceDto.class, dtoClass.getSimpleName()); +// } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/UniqueKeyTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/UniqueKeyTableModel.java new file mode 100644 index 0000000..ac50797 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/UniqueKeyTableModel.java @@ -0,0 +1,87 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.ref; + +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; + +import javax.swing.table.AbstractTableModel; +import java.util.List; + +import static org.nuiton.i18n.I18n.t; + +/** + * Un modèle de tableau pour afficher les clef metier des objets du + * référentiel. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.2 + */ +public class UniqueKeyTableModel extends AbstractTableModel { + + private static final long serialVersionUID = 1L; + + protected final String[] columns; + + protected final List<Object[]> datas; + + protected transient DecoratorService decoratorService; + + public UniqueKeyTableModel(String[] columns, List<Object[]> datas) { + this.columns = columns; + this.datas = datas; + } + + public DecoratorService getDecoratorService() { + if (decoratorService == null) { + decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); + } + return decoratorService; + } + + @Override + public int getRowCount() { + return datas.size(); + } + + @Override + public int getColumnCount() { + return columns.length; + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + return datas.get(rowIndex)[columnIndex]; + } + + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + // tableau non editable + return false; + } + + @Override + public String getColumnName(int column) { + String property = columns[column]; + return t(DecoratorService.getPropertyLabel(property)); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/CountryUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/CountryUI.jaxx new file mode 100644 index 0000000..abe8713 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/CountryUI.jaxx @@ -0,0 +1,185 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='CountryDto' + contentTitle='{n("observe.content.title.country")}' + listText='{n("observe.content.list.country")}' + createToolTip='{n("observe.content.action.country.create.tip")}' + detailToolTip='{n("observe.content.action.country.detail.tip")}' + modifyToolTip='{n("observe.content.action.country.modify.tip")}' + deleteToolTip='{n("observe.content.action.country.delete.tip")}' + saveToolTip='{n("observe.content.action.country.save.tip")}' + + > + + <style source="ReferenceEntity.jcss"/> + <style source="I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.CountryDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.CountryDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <CountryUIModel id='model'/> + + <!-- edit bean --> + <CountryDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- iso2Code --> + <row> + <cell anchor="west"> + <JLabel id='iso2CodeLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='iso2Code' + onKeyReleased='getBean().setIso2Code(iso2Code.getText())'/> + </cell> + </row> + + <!-- iso3Code --> + <row> + <cell anchor="west"> + <JLabel id='iso3CodeLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='iso3Code' + onKeyReleased='getBean().setIso3Code(iso3Code.getText())'/> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/CountryUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/CountryUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/CountryUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/CountryUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/CountryUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/CountryUIModel.java new file mode 100644 index 0000000..037ec0b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/CountryUIModel.java @@ -0,0 +1,45 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.CountryDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/27/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class CountryUIModel extends ContentReferenceUIModel<CountryDto> { + + private static final long serialVersionUID = 1L; + + public CountryUIModel() { + super(CountryDto.class, + new String[]{CountryDto.PROPERTY_ISO2_CODE, CountryDto.PROPERTY_ISO3_CODE}, + new String[]{CountryUI.BINDING_ISO2_CODE_TEXT, CountryUI.BINDING_ISO3_CODE_TEXT} + ); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/FpaZoneUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/FpaZoneUI.jaxx new file mode 100644 index 0000000..c58392c --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/FpaZoneUI.jaxx @@ -0,0 +1,181 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='FpaZoneDto' + contentTitle='{n("observe.content.title.fpaZones")}' + listText='{n("observe.content.list.fpaZone")}' + createToolTip='{n("observe.content.action.fpaZone.create.tip")}' + detailToolTip='{n("observe.content.action.fpaZone.detail.tip")}' + modifyToolTip='{n("observe.content.action.fpaZone.modify.tip")}' + deleteToolTip='{n("observe.content.action.fpaZone.delete.tip")}' + saveToolTip='{n("observe.content.action.fpaZone.save.tip")}' + + > + + <style source="ReferenceEntity.jcss"/> + <style source="I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.FpaZoneDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + org.jdesktop.swingx.JXDatePicker + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.FpaZoneDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <FpaZoneUIModel id='model'/> + + <!-- edit bean --> + <FpaZoneDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id="uriLabel"/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + + <!-- date debut - fin de validite --> + <row> + <cell anchor='west'> + <JLabel id='startDateFinValiditeLabel'/> + </cell> + <cell anchor='west' weightx="1" fill="both"> + <JPanel layout='{new GridLayout()}'> + <JXDatePicker id='startDate' + onActionPerformed='getBean().setStartDate(startDate.getDate())'/> + <JXDatePicker id='endDate' + onActionPerformed='getBean().setEndDate(endDate.getDate())'/> + </JPanel> + </cell> + </row> + </Table> + + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/FpaZoneUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/FpaZoneUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/FpaZoneUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/FpaZoneUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/FpaZoneUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/FpaZoneUIModel.java new file mode 100644 index 0000000..b0a70d0 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/FpaZoneUIModel.java @@ -0,0 +1,45 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.FpaZoneDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/27/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class FpaZoneUIModel extends ContentReferenceUIModel<FpaZoneDto> { + + private static final long serialVersionUID = 1L; + + public FpaZoneUIModel() { + super(FpaZoneDto.class, + new String[]{FpaZoneDto.PROPERTY_START_DATE, FpaZoneDto.PROPERTY_END_DATE}, + new String[]{FpaZoneUI.BINDING_START_DATE_DATE, FpaZoneUI.BINDING_END_DATE_DATE} + ); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearCaracteristicTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearCaracteristicTypeUI.jaxx new file mode 100644 index 0000000..74db9f0 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearCaracteristicTypeUI.jaxx @@ -0,0 +1,162 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='GearCaracteristicTypeDto' + contentTitle='{n("observe.content.title.gearCaracteristicTypes")}' + listText='{n("observe.content.list.gearCaracteristicType")}' + createToolTip='{n("observe.content.action.gearCaracteristicType.create.tip")}' + detailToolTip='{n("observe.content.action.gearCaracteristicType.detail.tip")}' + modifyToolTip='{n("observe.content.action.gearCaracteristicType.modify.tip")}' + deleteToolTip='{n("observe.content.action.gearCaracteristicType.delete.tip")}' + saveToolTip='{n("observe.content.action.gearCaracteristicType.save.tip")}'> + + <style source="ReferenceEntity.jcss"/> + <style source="I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.GearCaracteristicTypeDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.GearCaracteristicTypeDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <GearCaracteristicTypeUIModel id='model'/> + + <!-- edit bean --> + <GearCaracteristicTypeDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id="uriLabel"/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearCaracteristicTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearCaracteristicTypeUIModel.java new file mode 100644 index 0000000..1d6a69a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearCaracteristicTypeUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.GearCaracteristicTypeDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 3/23/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.16 + */ +public class GearCaracteristicTypeUIModel extends ContentReferenceUIModel<GearCaracteristicTypeDto> { + + private static final long serialVersionUID = 1L; + + public GearCaracteristicTypeUIModel() { + super(GearCaracteristicTypeDto.class); + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearCaracteristicUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearCaracteristicUI.jaxx new file mode 100644 index 0000000..54ecb86 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearCaracteristicUI.jaxx @@ -0,0 +1,187 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='GearCaracteristicDto' + contentTitle='{n("observe.content.title.gearCaracteristics")}' + listText='{n("observe.content.list.gearCaracteristic")}' + createToolTip='{n("observe.content.action.gearCaracteristic.create.tip")}' + detailToolTip='{n("observe.content.action.gearCaracteristic.detail.tip")}' + modifyToolTip='{n("observe.content.action.gearCaracteristic.modify.tip")}' + deleteToolTip='{n("observe.content.action.gearCaracteristic.delete.tip")}' + saveToolTip='{n("observe.content.action.gearCaracteristic.save.tip")}'> + + <style source="ReferenceEntity.jcss"/> + <style source="I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.GearCaracteristicDto + fr.ird.observe.services.dto.referential.GearCaracteristicTypeDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + jaxx.runtime.swing.editor.bean.BeanComboBox + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.GearCaracteristicDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <GearCaracteristicUIModel id='model'/> + + <!-- edit bean --> + <GearCaracteristicDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id="uriLabel"/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + + <!-- gearCaracteristicType --> + <row> + <cell anchor='west'> + <JLabel id='gearCaracteristicTypeLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='gearCaracteristicType' constructorParams='this' genericType='ReferentialReference<GearCaracteristicTypeDto>' _entityClass='GearCaracteristicTypeDto.class'/> + </cell> + </row> + + <!-- unit --> + <row> + <cell anchor='west'> + <JLabel id='unitLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='unit' onKeyReleased='getBean().setUnit(unit.getText())'/> + </cell> + </row> + + </Table> + + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearCaracteristicUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearCaracteristicUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearCaracteristicUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearCaracteristicUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearCaracteristicUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearCaracteristicUIModel.java new file mode 100644 index 0000000..219494d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearCaracteristicUIModel.java @@ -0,0 +1,49 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.GearCaracteristicDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 3/23/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.16 + */ +public class GearCaracteristicUIModel extends ContentReferenceUIModel<GearCaracteristicDto> { + + private static final long serialVersionUID = 1L; + + public GearCaracteristicUIModel() { + super(GearCaracteristicDto.class, + new String[]{ + GearCaracteristicDto.PROPERTY_GEAR_CARACTERISTIC_TYPE, + GearCaracteristicDto.PROPERTY_UNIT, + }, + new String[]{GearCaracteristicDto.PROPERTY_GEAR_CARACTERISTIC_TYPE + SUFFIX_SELECTED_ITEM, + GearCaracteristicDto.PROPERTY_UNIT + SUFFIX_TEXT} + ); + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearUI.jaxx new file mode 100644 index 0000000..1c7122b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearUI.jaxx @@ -0,0 +1,200 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='GearDto' + contentTitle='{n("observe.content.title.gears")}' + listText='{n("observe.content.list.gear")}' + createToolTip='{n("observe.content.action.gear.create.tip")}' + detailToolTip='{n("observe.content.action.gear.detail.tip")}' + modifyToolTip='{n("observe.content.action.gear.modify.tip")}' + deleteToolTip='{n("observe.content.action.gear.delete.tip")}' + saveToolTip='{n("observe.content.action.gear.save.tip")}'> + + <style source="ReferenceEntity.jcss"/> + <style source="I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.GearDto + fr.ird.observe.services.dto.referential.GearCaracteristicDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + org.nuiton.jaxx.widgets.select.FilterableDoubleList + + java.util.Collection + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.GearDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <GearUIModel id='model'/> + + <!-- edit bean --> + <GearDto id='bean'/> + + <!-- handler --> + <GearUIHandler id='handler' constructorParams="this"/> + + <Table id="editView" insets="0" fill="both"> + <row> + <cell anchor="north" weightx="1"> + <JTabbedPane id='tabPane'> + <tab id='generalTab'> + <Table fill="both"> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + + <row> + <cell columns="2"> + <Table id='editI18nTable2'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> + </cell> + </row> + <row> + <cell columns="2" weighty="1"> + <JLabel/> + </cell> + </row> + </Table> + </tab> + + <tab id='gearCaracteristicTab'> + <Table fill="both" weightx="1"> + <!-- gearCaracteristic --> + <row> + <cell weightx="1" weighty="1"> + <JScrollPane id='gearCaracteristicPane' layout='{new GridLayout(1,1)}'> + <FilterableDoubleList id='gearCaracteristic' + genericType='ReferentialReference<GearCaracteristicDto>' + _entityClass='GearCaracteristicDto.class'/> + </JScrollPane> + </cell> + </row> + </Table> + </tab> + </JTabbedPane> + </cell> + </row> + <row> + <cell columns="2" weighty="1"> + <JLabel/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearUIHandler.java new file mode 100644 index 0000000..bcd18f7 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearUIHandler.java @@ -0,0 +1,102 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.GearDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIHandler; +import jaxx.runtime.validator.swing.SwingValidatorMessage; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.event.TableModelListener; +import java.util.HashSet; +import java.util.Set; + +/** + * Created on 3/23/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.16 + */ +public class GearUIHandler extends ContentReferenceUIHandler<GearDto> { + + // Compute valid state of tab from the error table + protected final TableModelListener computeTabValidStateListener; + + public GearUIHandler(ContentReferenceUI<GearDto> ui) { + super(ui); + computeTabValidStateListener = e -> { + + SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); + computeTabValidState(source); + + }; + } + + @Override + public void initUI() { + + super.initUI(); + + // To be sure always remove listener (could prevent some leaks) + getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); + // listen messages to see if required to add + getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); + + } + + @Override + public void selectBean(ReferentialReference<GearDto> selectedBean) { + + super.selectBean(selectedBean); + + SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); + computeTabValidState(errorTableModel); + + ((GearUI) getUi()).getTabPane().setSelectedIndex(0); + + } + + protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { + + Set<String> errorProperties = new HashSet<>(); + int rowCount = errorTableModel.getRowCount(); + for (int i = 0; i < rowCount; i++) { + + SwingValidatorMessage row = errorTableModel.getRow(i); + if (NuitonValidatorScope.ERROR.equals(row.getScope())) { + errorProperties.add(row.getField()); + } + } + + boolean generalTabValid = !errorProperties.removeAll(GearUIModel.GENERAL_TAB_PROPERTIES); + boolean gearCaracteristicTabValid = !errorProperties.removeAll(GearUIModel.GEAR_CARACTERISTIC_TAB_PROPERTIES); + + GearUIModel model = (GearUIModel) getModel(); + model.setGeneralTabValid(generalTabValid); + model.setGearCaracteristicTabValid(gearCaracteristicTabValid); + + } +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearUIModel.java new file mode 100644 index 0000000..96612df --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/GearUIModel.java @@ -0,0 +1,92 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.ImmutableSet; +import fr.ird.observe.services.dto.referential.GearDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +import java.util.Set; + +/** + * Created on 3/23/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.16 + */ +public class GearUIModel extends ContentReferenceUIModel<GearDto> { + + private static final long serialVersionUID = 1L; + + public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; + + public static final String PROPERTY_GEAR_CARACTERISTIC_TAB_VALID = "gearCaracteristicTabValid"; + + public static final Set<String> GENERAL_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(GearDto.PROPERTY_URI, + GearDto.PROPERTY_CODE, + GearDto.PROPERTY_STATUS, + GearDto.PROPERTY_NEED_COMMENT, + GearDto.PROPERTY_LABEL1, + GearDto.PROPERTY_LABEL2, + GearDto.PROPERTY_LABEL3, + GearDto.PROPERTY_LABEL4, + GearDto.PROPERTY_LABEL5, + GearDto.PROPERTY_LABEL6, + GearDto.PROPERTY_LABEL7, + GearDto.PROPERTY_LABEL8).build(); + + public static final Set<String> GEAR_CARACTERISTIC_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(GearDto.PROPERTY_GEAR_CARACTERISTIC).build(); + + protected boolean generalTabValid; + + protected boolean gearCaracteristicTabValid; + + public GearUIModel() { + super(GearDto.class, + new String[]{GearDto.PROPERTY_GEAR_CARACTERISTIC}, + new String[]{GearDto.PROPERTY_GEAR_CARACTERISTIC + SUFFIX_SELECTED}); + } + + public boolean isGearCaracteristicTabValid() { + return gearCaracteristicTabValid; + } + + public void setGearCaracteristicTabValid(boolean gearCaracteristicTabValid) { + Object oldValue = isGearCaracteristicTabValid(); + this.gearCaracteristicTabValid = gearCaracteristicTabValid; + firePropertyChange(PROPERTY_GEAR_CARACTERISTIC_TAB_VALID, oldValue, gearCaracteristicTabValid); + } + + public boolean isGeneralTabValid() { + return generalTabValid; + } + + public void setGeneralTabValid(boolean generalTabValid) { + Object oldValue = isGeneralTabValid(); + this.generalTabValid = generalTabValid; + firePropertyChange(PROPERTY_GENERAL_TAB_VALID, oldValue, generalTabValid); + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/HarbourUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/HarbourUI.jaxx new file mode 100644 index 0000000..4c960bc --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/HarbourUI.jaxx @@ -0,0 +1,149 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='HarbourDto' + contentTitle='{n("observe.content.title.harbours")}' + listText='{n("observe.content.list.harbour")}' + createToolTip='{n("observe.content.action.harbour.create.tip")}' + detailToolTip='{n("observe.content.action.harbour.detail.tip")}' + modifyToolTip='{n("observe.content.action.harbour.modify.tip")}' + deleteToolTip='{n("observe.content.action.harbour.delete.tip")}' + saveToolTip='{n("observe.content.action.harbour.save.tip")}' + + > + + <style source="ReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.HarbourDto + fr.ird.observe.services.dto.referential.CountryDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + jaxx.runtime.swing.editor.bean.BeanComboBox + + org.nuiton.jaxx.widgets.gis.absolute.CoordinatesEditor + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' context='ui-create' + beanClass='fr.ird.observe.services.dto.referential.HarbourDto' + errorTableModel='{getErrorTableModel()}'> + + <field name='longitude' component='coordinates'/> + <field name='latitude' component='coordinates'/> + <field name='quadrant' component='coordinates'/> + <field name='name' component='harbourName'/> + + </BeanValidator> + + <!-- model --> + <HarbourUIModel id='model'/> + + <!-- edit bean --> + <HarbourDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- locode --> + <row> + <cell anchor='west'> + <JLabel id='locodeLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='locode' onKeyReleased='getBean().setLocode(locode.getText())'/> + </cell> + </row> + + <!-- name --> + <row> + <cell anchor='west'> + <JLabel id='harbourNameLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='harbourName' onKeyReleased='getBean().setName(harbourName.getText())'/> + </cell> + </row> + + <!-- country --> + <row> + <cell anchor='west'> + <JLabel id='countryLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='country' constructorParams='this' genericType='ReferentialReference<CountryDto>' _entityClass='CountryDto.class'/> + </cell> + </row> + + <!-- coordinates --> + <row> + <cell anchor='west'> + <JLabel id='coordinatesLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <CoordinatesEditor id='coordinates' constructorParams='this'/> + </cell> + + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/HarbourUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/HarbourUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/HarbourUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/HarbourUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/HarbourUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/HarbourUIModel.java new file mode 100644 index 0000000..fe751e4 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/HarbourUIModel.java @@ -0,0 +1,55 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.HarbourDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 1/7/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.11 + */ +public class HarbourUIModel extends ContentReferenceUIModel<HarbourDto> { + + private static final long serialVersionUID = 1L; + + public HarbourUIModel() { + super(HarbourDto.class, + new String[]{HarbourDto.PROPERTY_NAME, + HarbourDto.PROPERTY_COUNTRY, + HarbourDto.PROPERTY_LOCODE, + HarbourDto.PROPERTY_LATITUDE, + HarbourDto.PROPERTY_LONGITUDE, + HarbourDto.PROPERTY_QUADRANT}, + new String[]{HarbourUI.BINDING_COUNTRY_SELECTED_ITEM, + HarbourUI.BINDING_HARBOUR_NAME_TEXT, + HarbourUI.BINDING_LOCODE_TEXT, + HarbourUI.BINDING_COORDINATES_LATITUDE, + HarbourUI.BINDING_COORDINATES_LONGITUDE, + HarbourUI.BINDING_COORDINATES_QUADRANT} + ); + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/I18nReferenceEntity.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/I18nReferenceEntity.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/I18nReferenceEntity.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/I18nReferenceEntity.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/LengthWeightParameterUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/LengthWeightParameterUI.jaxx new file mode 100644 index 0000000..6727cd7 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/LengthWeightParameterUI.jaxx @@ -0,0 +1,300 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='LengthWeightParameterDto' + contentTitle='{n("observe.content.title.lengthWeightParameters")}' + listText='{n("observe.content.list.lengthWeightParameter")}' + createToolTip='{n("observe.content.action.lengthWeightParameter.create.tip")}' + detailToolTip='{n("observe.content.action.lengthWeightParameter.detail.tip")}' + modifyToolTip='{n("observe.content.action.lengthWeightParameter.modify.tip")}' + deleteToolTip='{n("observe.content.action.lengthWeightParameter.delete.tip")}' + saveToolTip='{n("observe.content.action.lengthWeightParameter.save.tip")}' + + > + + <style source="ReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.SexDto + fr.ird.observe.services.dto.referential.SpeciesDto + fr.ird.observe.services.dto.referential.OceanDto + fr.ird.observe.services.dto.referential.LengthWeightParameterDto + fr.ird.observe.application.swing.ui.UIHelper + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + org.jdesktop.swingx.JXDatePicker + + javax.swing.JScrollPane + javax.swing.JTable + javax.swing.table.TableCellRenderer + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.LengthWeightParameterDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <LengthWeightParameterUIModel id='model'/> + + <!-- handler --> + <LengthWeightParameterUIHandler id='handler' constructorParams="this"/> + + <!-- edit bean --> + <LengthWeightParameterDto id='bean'/> + + <script><![CDATA[ +@Override +public void decorateUniqueKeyTable(JTable table, + TableCellRenderer renderer, + JScrollPane pane) { + + UIHelper.fixTableColumnWidth(table, 0, 250); + UIHelper.fixTableColumnWidth(table, 1, 100); + UIHelper.fixTableColumnWidth(table, 2, 100); + UIHelper.fixTableColumnWidth(table, 3, 200); + + table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); + + UIHelper.setTableColumnRenderer(table, 1, + UIHelper.newDecorateTableCellRenderer(renderer, SexDto.class)); +} +]]></script> + + <Table id="editView" insets="0" fill="both"> + <row> + <cell anchor="north" weightx="1"> + <JTabbedPane id='tabPane'> + <tab id='generalTab'> + <Table fill="both"> + + <!-- sex --> + <row> + <cell anchor="west"> + <JLabel id='sexLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='sex' constructorParams='this' + genericType='ReferentialReference<SexDto>' _entityClass='SexDto.class'/> + </cell> + </row> + + <!-- species --> + <row> + <cell anchor='west'> + <JLabel id='speciesLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='species' constructorParams='this' + genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class'/> + </cell> + </row> + + <!-- ocean --> + <row> + <cell anchor='west'> + <JLabel id='oceanLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='ocean' constructorParams='this' + genericType='ReferentialReference<OceanDto>' _entityClass='OceanDto.class'/> + </cell> + </row> + + <!-- date debut - fin de validite --> + <row> + <cell anchor='west'> + <JLabel id='startDateFinValiditeLabel'/> + </cell> + <cell anchor='west' weightx="1" fill="both"> + <JPanel layout='{new GridLayout()}'> + <JXDatePicker id='startDate' + onActionPerformed='getBean().setStartDate(startDate.getDate())'/> + <JXDatePicker id='endDate' + onActionPerformed='getBean().setEndDate(endDate.getDate())'/> + </JPanel> + </cell> + </row> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- status --> + <row> + <cell anchor="west"> + <JLabel id='statusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <EnumEditor id='status' constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + + <row> + <cell columns="2" weighty="1"> + <JLabel/> + </cell> + </row> + </Table> + </tab> + + <tab id='otherTab'> + <Table fill="both" insets="0"> + + <row> + <cell weightx="1"> + <Table id="relationTable" fill="both"> + + <!-- coefficients --> + <row> + <cell anchor='west' columns="2"> + <JLabel id='coefficientsInformation'/> + </cell> + </row> + + <row> + <cell anchor='west'> + <JLabel id='coefficientsLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='coefficients' + onKeyReleased='getBean().setCoefficients(coefficients.getText())'/> + </cell> + </row> + + <!-- relation weight --> + <row> + <cell anchor='west' columns="2"> + <JLabel id='lengthWeightFormulaInformation'/> + </cell> + </row> + + <row> + <cell anchor='west'> + <JLabel id='lengthWeightFormulaLabel'/> + </cell> + <cell weightx="1" fill="both"> + <JTextField id='lengthWeightFormula' + onKeyReleased='getBean().setLengthWeightFormula(lengthWeightFormula.getText())'/> + </cell> + </row> + + <!-- relation taille --> + <row> + <cell anchor='west' columns="2"> + <JLabel id='weightLengthFormulaInformation'/> + </cell> + </row> + + <row> + <cell anchor='west'> + <JLabel id='weightLengthFormulaLabel'/> + </cell> + <cell weightx="1" fill="both"> + <JTextField id='weightLengthFormula' + onKeyReleased='getBean().setWeightLengthFormula(weightLengthFormula.getText())'/> + </cell> + </row> + </Table> + </cell> + </row> + + <row> + <cell weightx="1"> + + <Table id='meanValuesTable' fill='both' insets="1"> + + <!-- tailleMoyen --> + <row> + <cell anchor="west"> + <JLabel id='meanLengthLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <NumberEditor id='meanLength' constructorParams='this' styleClass="float2"/> + </cell> + </row> + + <!-- meanWeight --> + <row> + <cell anchor="west"> + <JLabel id='meanWeightLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <NumberEditor id='meanWeight' constructorParams='this' styleClass="float2"/> + </cell> + </row> + <row> + <cell> + <javax.swing.Box.Filler id='filler' + constructorParams='UIHelper.newMinDimension(), UIHelper.newMinDimension(), UIHelper.newMaxXDimension()'/> + </cell> + </row> + </Table> + + </cell> + </row> + + <row> + <cell columns="2" weighty="1"> + <JLabel/> + </cell> + </row> + + </Table> + </tab> + </JTabbedPane> + </cell> + </row> + <row> + <cell columns="2" weighty="1"> + <JLabel/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/LengthWeightParameterUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/LengthWeightParameterUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/LengthWeightParameterUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/LengthWeightParameterUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/LengthWeightParameterUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/LengthWeightParameterUIHandler.java new file mode 100644 index 0000000..cbdcb04 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/LengthWeightParameterUIHandler.java @@ -0,0 +1,102 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.LengthWeightParameterDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIHandler; +import jaxx.runtime.validator.swing.SwingValidatorMessage; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.event.TableModelListener; +import java.util.HashSet; +import java.util.Set; + +/** + * Created on 1/11/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.11 + */ +public class LengthWeightParameterUIHandler extends ContentReferenceUIHandler<LengthWeightParameterDto> { + + // Compute valid state of tab from the error table + protected final TableModelListener computeTabValidStateListener; + + public LengthWeightParameterUIHandler(ContentReferenceUI<LengthWeightParameterDto> ui) { + super(ui); + computeTabValidStateListener = e -> { + + SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); + computeTabValidState(source); + + }; + } + + @Override + public void initUI() { + + super.initUI(); + + // To be sure always remove listener (could prevent some leaks) + getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); + // listen messages to see if required to add + getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); + + } + + @Override + public void selectBean(ReferentialReference<LengthWeightParameterDto> selectedBean) { + + super.selectBean(selectedBean); + + SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); + computeTabValidState(errorTableModel); + + ((LengthWeightParameterUI) getUi()).getTabPane().setSelectedIndex(0); + + } + + protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { + + Set<String> errorProperties = new HashSet<>(); + int rowCount = errorTableModel.getRowCount(); + for (int i = 0; i < rowCount; i++) { + + SwingValidatorMessage row = errorTableModel.getRow(i); + if (NuitonValidatorScope.ERROR.equals(row.getScope())) { + errorProperties.add(row.getField()); + } + } + + boolean generalTabValid = !errorProperties.removeAll(LengthWeightParameterUIModel.GENERAL_TAB_PROPERTIES); + boolean otherTabValid = !errorProperties.removeAll(LengthWeightParameterUIModel.OTHER_TAB_PROPERTIES); + + LengthWeightParameterUIModel model = (LengthWeightParameterUIModel) getModel(); + model.setGeneralTabValid(generalTabValid); + model.setOtherTabValid(otherTabValid); + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/LengthWeightParameterUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/LengthWeightParameterUIModel.java new file mode 100644 index 0000000..148cf37 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/LengthWeightParameterUIModel.java @@ -0,0 +1,102 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.ImmutableSet; +import fr.ird.observe.services.dto.referential.LengthWeightParameterDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +import java.util.Set; + +/** + * Created on 9/27/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class LengthWeightParameterUIModel extends ContentReferenceUIModel<LengthWeightParameterDto> { + + public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; + + public static final String PROPERTY_OTHER_TAB_VALID = "otherTabValid"; + + public static final Set<String> GENERAL_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(LengthWeightParameterDto.PROPERTY_URI, + LengthWeightParameterDto.PROPERTY_CODE, + LengthWeightParameterDto.PROPERTY_STATUS, + LengthWeightParameterDto.PROPERTY_SEX, + LengthWeightParameterDto.PROPERTY_OCEAN, + LengthWeightParameterDto.PROPERTY_SPECIES, + LengthWeightParameterDto.PROPERTY_NEED_COMMENT, + LengthWeightParameterDto.PROPERTY_START_DATE, + LengthWeightParameterDto.PROPERTY_END_DATE).build(); + + public static final Set<String> OTHER_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(LengthWeightParameterDto.PROPERTY_MEAN_LENGTH, + LengthWeightParameterDto.PROPERTY_MEAN_WEIGHT, + LengthWeightParameterDto.PROPERTY_WEIGHT_LENGTH_FORMULA, + LengthWeightParameterDto.PROPERTY_WEIGHT_LENGTH_FORMULA_VALID, + LengthWeightParameterDto.PROPERTY_LENGTH_WEIGHT_FORMULA, + LengthWeightParameterDto.PROPERTY_LENGTH_WEIGHT_FORMULA_VALID, + LengthWeightParameterDto.PROPERTY_COEFFICIENTS).build(); + + private static final long serialVersionUID = 1L; + + protected boolean generalTabValid; + + protected boolean otherTabValid; + + public LengthWeightParameterUIModel() { + super(LengthWeightParameterDto.class, + null, + new String[]{ + LengthWeightParameterDto.PROPERTY_SEX, + LengthWeightParameterDto.PROPERTY_OCEAN, + LengthWeightParameterDto.PROPERTY_SPECIES, + LengthWeightParameterDto.PROPERTY_START_DATE, + }, + null + ); + } + + public boolean isOtherTabValid() { + return otherTabValid; + } + + public void setOtherTabValid(boolean otherTabValid) { + Object oldValue = isOtherTabValid(); + this.otherTabValid = otherTabValid; + firePropertyChange(PROPERTY_OTHER_TAB_VALID, oldValue, otherTabValid); + } + + public boolean isGeneralTabValid() { + return generalTabValid; + } + + public void setGeneralTabValid(boolean generalTabValid) { + Object oldValue = isGeneralTabValid(); + this.generalTabValid = generalTabValid; + firePropertyChange(PROPERTY_GENERAL_TAB_VALID, oldValue, generalTabValid); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/NeedCommentReferenceEntity.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/NeedCommentReferenceEntity.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/NeedCommentReferenceEntity.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/NeedCommentReferenceEntity.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/OceanUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/OceanUI.jaxx new file mode 100644 index 0000000..ab4f259 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/OceanUI.jaxx @@ -0,0 +1,164 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='OceanDto' + contentTitle='{n("observe.content.title.oceans")}' + listText='{n("observe.content.list.ocean")}' + createToolTip='{n("observe.content.action.ocean.create.tip")}' + detailToolTip='{n("observe.content.action.ocean.detail.tip")}' + modifyToolTip='{n("observe.content.action.ocean.modify.tip")}' + deleteToolTip='{n("observe.content.action.ocean.delete.tip")}' + saveToolTip='{n("observe.content.action.ocean.save.tip")}' + + > + + <style source="ReferenceEntity.jcss"/> + <style source="I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.OceanDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.OceanDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <OceanUIModel id='model'/> + + <!-- edit bean --> + <OceanDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' + onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/OceanUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/OceanUIModel.java new file mode 100644 index 0000000..69bfec8 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/OceanUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.OceanDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/27/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class OceanUIModel extends ContentReferenceUIModel<OceanDto> { + + private static final long serialVersionUID = 1L; + + public OceanUIModel() { + super(OceanDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/OrganismUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/OrganismUI.jaxx new file mode 100644 index 0000000..9868346 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/OrganismUI.jaxx @@ -0,0 +1,189 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='OrganismDto' + contentTitle='{n("observe.content.title.organisms")}' + listText='{n("observe.content.list.organism")}' + createToolTip='{n("observe.content.action.organism.create.tip")}' + detailToolTip='{n("observe.content.action.organism.detail.tip")}' + modifyToolTip='{n("observe.content.action.organism.modify.tip")}' + deleteToolTip='{n("observe.content.action.organism.delete.tip")}' + saveToolTip='{n("observe.content.action.organism.save.tip")}' + + > + + <style source="ReferenceEntity.jcss"/> + <style source="I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.OrganismDto + fr.ird.observe.services.dto.referential.CountryDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + jaxx.runtime.swing.editor.bean.BeanComboBox + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.OrganismDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <OrganismUIModel id='model'/> + + <!-- edit bean --> + <OrganismDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' + onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- country --> + <row> + <cell anchor='west'> + <JLabel id='countryLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='country' constructorParams='this' genericType='ReferentialReference<CountryDto>' _entityClass='CountryDto.class'/> + </cell> + </row> + + <!-- description --> + <row> + <cell anchor='west'> + <JLabel id='descriptionLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='description' + onKeyReleased='getBean().setDescription(description.getText())'/> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/OrganismUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/OrganismUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/OrganismUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/OrganismUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/OrganismUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/OrganismUIModel.java new file mode 100644 index 0000000..60cbfcc --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/OrganismUIModel.java @@ -0,0 +1,45 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.OrganismDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/27/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class OrganismUIModel extends ContentReferenceUIModel<OrganismDto> { + + private static final long serialVersionUID = 1L; + + public OrganismUIModel() { + super(OrganismDto.class, + new String[]{OrganismDto.PROPERTY_COUNTRY, OrganismDto.PROPERTY_DESCRIPTION}, + new String[]{OrganismUI.BINDING_COUNTRY_SELECTED_ITEM, OrganismUI.BINDING_DESCRIPTION_TEXT} + ); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/PersonUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/PersonUI.jaxx new file mode 100644 index 0000000..a4e9a5f --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/PersonUI.jaxx @@ -0,0 +1,169 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='PersonDto' + contentTitle='{n("observe.content.title.persons")}' + listText='{n("observe.content.list.person")}' + createToolTip='{n("observe.content.action.person.create.tip")}' + detailToolTip='{n("observe.content.action.person.detail.tip")}' + modifyToolTip='{n("observe.content.action.person.modify.tip")}' + deleteToolTip='{n("observe.content.action.person.delete.tip")}' + saveToolTip='{n("observe.content.action.person.save.tip")}' + + > + + <style source="ReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.PersonDto + fr.ird.observe.services.dto.referential.CountryDto + fr.ird.observe.application.swing.ui.UIHelper + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + javax.swing.JTable + javax.swing.JScrollPane + javax.swing.table.TableCellRenderer + + jaxx.runtime.swing.editor.bean.BeanComboBox + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.PersonDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <PersonUIModel id='model'/> + + <!-- edit bean --> + <PersonDto id='bean'/> + + <script><![CDATA[ +@Override +public void decorateUniqueKeyTable(JTable table, + TableCellRenderer renderer, + JScrollPane pane) { + UIHelper.fixTableColumnWidth(table, 1, 120); +} +]]></script> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- lastName --> + <row> + <cell anchor="west"> + <JLabel id='lastNameLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='lastName' + onKeyReleased='getBean().setLastName(lastName.getText())'/> + </cell> + </row> + + <!-- firstName --> + <row> + <cell anchor="west"> + <JLabel id='firstNameLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='firstName' + onKeyReleased='getBean().setFirstName(firstName.getText())'/> + </cell> + </row> + + <!-- country --> + <row> + <cell anchor='west'> + <JLabel id='countryLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='country' constructorParams='this' genericType='ReferentialReference<CountryDto>' _entityClass='CountryDto.class'/> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + + <!-- is observer --> + <row> + <cell columns="2"> + <JCheckBox id='observer' + onStateChanged='getBean().setObserver(observer.isSelected())'/> + </cell> + </row> + + <!-- is captain --> + <row> + <cell columns="2"> + <JCheckBox id='captain' + onStateChanged='getBean().setCaptain(captain.isSelected())'/> + </cell> + </row> + + <!-- is dataEntryOperator --> + <row> + <cell columns="2"> + <JCheckBox id='dataEntryOperator' + onStateChanged='getBean().setDataEntryOperator(dataEntryOperator.isSelected())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/PersonUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/PersonUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/PersonUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/PersonUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/PersonUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/PersonUIModel.java new file mode 100644 index 0000000..2ed1a9e --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/PersonUIModel.java @@ -0,0 +1,61 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.PersonDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/27/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class PersonUIModel extends ContentReferenceUIModel<PersonDto> { + + private static final long serialVersionUID = 1L; + + public PersonUIModel() { + super(PersonDto.class, + new String[]{ + PersonDto.PROPERTY_CODE, + PersonDto.PROPERTY_LAST_NAME, + PersonDto.PROPERTY_FIRST_NAME, + PersonDto.PROPERTY_CAPTAIN, + PersonDto.PROPERTY_OBSERVER, + PersonDto.PROPERTY_DATA_ENTRY_OPERATOR, + PersonDto.PROPERTY_COUNTRY + }, + new String[]{PersonDto.PROPERTY_CODE}, + new String[]{PersonUI.BINDING_CODE_TEXT, + PersonUI.BINDING_FIRST_NAME_TEXT, + PersonUI.BINDING_LAST_NAME_TEXT, + PersonUI.BINDING_CAPTAIN_SELECTED, + PersonUI.BINDING_OBSERVER_SELECTED, + PersonUI.BINDING_DATA_ENTRY_OPERATOR_SELECTED, + PersonUI.BINDING_COUNTRY_SELECTED_ITEM, + } + ); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/ProgramObservationEnum.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/ProgramObservationEnum.java new file mode 100644 index 0000000..3eaaa4d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/ProgramObservationEnum.java @@ -0,0 +1,60 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +import static org.nuiton.i18n.I18n.n; + +/** + * Une énumeration pour définir les différents niveaux d'observations effectués + * sur un program. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.2 + */ +public enum ProgramObservationEnum { + + value0, + value1, + value2, + value3, + value4, + value5, + value6, + value7, + value8, + value9; + + static { + + n("observe.programObservationEnum.value0"); + n("observe.programObservationEnum.value1"); + n("observe.programObservationEnum.value2"); + n("observe.programObservationEnum.value3"); + n("observe.programObservationEnum.value4"); + n("observe.programObservationEnum.value5"); + n("observe.programObservationEnum.value6"); + n("observe.programObservationEnum.value7"); + n("observe.programObservationEnum.value8"); + n("observe.programObservationEnum.value9"); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/ProgramUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/ProgramUI.jaxx new file mode 100644 index 0000000..dd036e9 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/ProgramUI.jaxx @@ -0,0 +1,339 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='ProgramDto' + contentTitle='{n("observe.content.title.programs")}' + listText='{n("observe.content.list.program")}' + createToolTip='{n("observe.content.action.program.create.tip")}' + detailToolTip='{n("observe.content.action.program.detail.tip")}' + modifyToolTip='{n("observe.content.action.program.modify.tip")}' + deleteToolTip='{n("observe.content.action.program.delete.tip")}' + saveToolTip='{n("observe.content.action.program.save.tip")}' + + > + + <style source="ReferenceEntity.jcss"/> + <style source="I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.constants.GearType + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.ProgramDto + fr.ird.observe.services.dto.referential.OrganismDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + fr.ird.observe.application.swing.ui.content.ref.impl.ProgramObservationEnum + + jaxx.runtime.swing.editor.bean.BeanComboBox + + org.jdesktop.swingx.JXDatePicker + + java.awt.Dimension + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' context='ui-create' + beanClass='fr.ird.observe.services.dto.referential.ProgramDto' errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <ProgramUIModel id='model'/> + + <!-- handler --> + <ProgramUIHandler id='handler' constructorParams="this"/> + + <!-- edit bean --> + <ProgramDto id='bean'/> + + <Table id="editView" insets="0" fill="both"> + <row> + <cell anchor="north" weightx="1"> + <JTabbedPane id='tabPane'> + <tab id='generalTab'> + <Table fill="both"> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- organism --> + <row> + <cell anchor='west'> + <JLabel id='organismLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='organism' constructorParams='this' + genericType='ReferentialReference<OrganismDto>' _entityClass='OrganismDto.class'/> + </cell> + </row> + + <row> + <!-- gearType --> + <cell anchor='west'> + <JLabel id='gearTypeLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <EnumEditor id='gearType' + constructorParams='GearType.class' + genericType='GearType' + onItemStateChanged='getBean().setGearType((GearType) gearType.getSelectedItem())'/> + </cell> + </row> + + <!-- date debut - fin de validite --> + <row> + <cell anchor='west'> + <JLabel id='startDateFinProgramLabel'/> + </cell> + <cell anchor='west'> + <JPanel layout='{new GridLayout()}'> + <JXDatePicker id='startDate' onActionPerformed='getBean().setStartDate(startDate.getDate())'/> + <JXDatePicker id='endDate' onActionPerformed='getBean().setEndDate(endDate.getDate())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + + <row> + <cell columns="2"> + <Table id='editI18nTable2'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> + </cell> + </row> + </Table> + </tab> + + <tab id='observationsTab'> + <Table fill="both"> + + <row> + + <!-- nonTargetObservation --> + <cell anchor='west'> + <JLabel id='nonTargetObservationLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <EnumEditor id='nonTargetObservation' + constructorParams='ProgramObservationEnum.class, getConfig().getNonTargetObservation()' + genericType='ProgramObservationEnum' + onItemStateChanged='getBean().setNonTargetObservation(nonTargetObservation.getSelectedIndex())'/> + </cell> + + </row> + <row> + <!-- targetDiscardsObservation --> + <cell anchor='west'> + <JLabel id='targetDiscardsObservationLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <EnumEditor id='targetDiscardsObservation' + constructorParams='ProgramObservationEnum.class, getConfig().getTargetDiscardsObservation()' + genericType='ProgramObservationEnum' + onItemStateChanged='getBean().setTargetDiscardsObservation(targetDiscardsObservation.getSelectedIndex())'/> + </cell> + </row> + <row> + + <!-- samplesObservation --> + <cell anchor='west'> + <JLabel id='samplesObservationLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <EnumEditor id='samplesObservation' + constructorParams='ProgramObservationEnum.class, getConfig().getSamplesObservation()' + genericType='ProgramObservationEnum' + onItemStateChanged='getBean().setSamplesObservation(samplesObservation.getSelectedIndex())'/> + </cell> + </row> + <row> + <!-- objectsObservation --> + <cell anchor='west'> + <JLabel id='objectsObservationLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <EnumEditor id='objectsObservation' + constructorParams='ProgramObservationEnum.class, getConfig().getObjectsObservation()' + genericType='ProgramObservationEnum' + onItemStateChanged='getBean().setObjectsObservation(objectsObservation.getSelectedIndex())'/> + </cell> + </row> + <row> + + <!-- detailledActivitiesObservation --> + <cell anchor='west'> + <JLabel id='detailledActivitiesObservationLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <EnumEditor id='detailledActivitiesObservation' + constructorParams='ProgramObservationEnum.class, getConfig().getDetailledActivitiesObservation()' + genericType='ProgramObservationEnum' + onItemStateChanged='getBean().setDetailledActivitiesObservation(detailledActivitiesObservation.getSelectedIndex())'/> + </cell> + </row> + <row> + <!-- mammalsObservation --> + <cell anchor='west'> + <JLabel id='mammalsObservationLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <EnumEditor id='mammalsObservation' + constructorParams='ProgramObservationEnum.class, getConfig().getMammalsObservation()' + genericType='ProgramObservationEnum' + onItemStateChanged='getBean().setMammalsObservation(mammalsObservation.getSelectedIndex())'/> + </cell> + </row> + <row> + + <!-- birdsObservation --> + <cell anchor='west'> + <JLabel id='birdsObservationLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <EnumEditor id='birdsObservation' + constructorParams='ProgramObservationEnum.class, getConfig().getBirdsObservation()' + genericType='ProgramObservationEnum' + onItemStateChanged='getBean().setBirdsObservation(birdsObservation.getSelectedIndex())'/> + </cell> + </row> + <row> + <!-- baitObservation --> + <cell anchor='west'> + <JLabel id='baitObservationLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <EnumEditor id='baitObservation' + constructorParams='ProgramObservationEnum.class, getConfig().getBaitObservation()' + genericType='ProgramObservationEnum' + onItemStateChanged='getBean().setBaitObservation(baitObservation.getSelectedIndex())'/> + </cell> + </row> + + <row> + <cell columns="2" weighty="1"> + <JLabel/> + </cell> + </row> + </Table> + </tab> + </JTabbedPane> + </cell> + </row> + + <!-- Comment --> + <row> + <cell weightx="1" weighty="1" fill="both"> + <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2' onKeyReleased='getBean().setComment(comment2.getText())'/> + </JScrollPane> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/ProgramUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/ProgramUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/ProgramUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/ProgramUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/ProgramUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/ProgramUIHandler.java new file mode 100644 index 0000000..426daa4 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/ProgramUIHandler.java @@ -0,0 +1,102 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIHandler; +import jaxx.runtime.validator.swing.SwingValidatorMessage; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.event.TableModelListener; +import java.util.HashSet; +import java.util.Set; + +/** + * Created on 1/11/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.11 + */ +public class ProgramUIHandler extends ContentReferenceUIHandler<ProgramDto> { + + // Compute valid state of tab from the error table + protected final TableModelListener computeTabValidStateListener; + + public ProgramUIHandler(ContentReferenceUI<ProgramDto> ui) { + super(ui); + computeTabValidStateListener = e -> { + + SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); + computeTabValidState(source); + + }; + } + + @Override + public void initUI() { + + super.initUI(); + + // To be sure always remove listener (could prevent some leaks) + getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); + // listen messages to see if required to add + getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); + + } + + @Override + public void selectBean(ReferentialReference<ProgramDto> selectedBean) { + + super.selectBean(selectedBean); + + SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); + computeTabValidState(errorTableModel); + + ((ProgramUI) getUi()).getTabPane().setSelectedIndex(0); + + } + + protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { + + Set<String> errorProperties = new HashSet<>(); + int rowCount = errorTableModel.getRowCount(); + for (int i = 0; i < rowCount; i++) { + + SwingValidatorMessage row = errorTableModel.getRow(i); + if (NuitonValidatorScope.ERROR.equals(row.getScope())) { + errorProperties.add(row.getField()); + } + } + + boolean generalTabValid = !errorProperties.removeAll(ProgramUIModel.GENERAL_TAB_PROPERTIES); + boolean observationsTabValid = !errorProperties.removeAll(ProgramUIModel.OBSERVATIONS_TAB_PROPERTIES); + + ProgramUIModel model = (ProgramUIModel) getModel(); + model.setGeneralTabValid(generalTabValid); + model.setObservationsTabValid(observationsTabValid); + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/ProgramUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/ProgramUIModel.java new file mode 100644 index 0000000..8d4e500 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/ProgramUIModel.java @@ -0,0 +1,126 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.ImmutableSet; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +import java.util.Set; + +/** + * Created on 9/27/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ProgramUIModel extends ContentReferenceUIModel<ProgramDto> { + + public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; + + public static final String PROPERTY_OBSERVATIONS_TAB_VALID = "observationsTabValid"; + + public static final Set<String> GENERAL_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(ProgramDto.PROPERTY_URI, + ProgramDto.PROPERTY_CODE, + ProgramDto.PROPERTY_STATUS, + ProgramDto.PROPERTY_NEED_COMMENT, + ProgramDto.PROPERTY_GEAR_TYPE, + ProgramDto.PROPERTY_ORGANISM, + ProgramDto.PROPERTY_LABEL1, + ProgramDto.PROPERTY_LABEL2, + ProgramDto.PROPERTY_LABEL3, + ProgramDto.PROPERTY_LABEL4, + ProgramDto.PROPERTY_LABEL5, + ProgramDto.PROPERTY_LABEL6, + ProgramDto.PROPERTY_LABEL7, + ProgramDto.PROPERTY_LABEL8).build(); + + public static final Set<String> OBSERVATIONS_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(ProgramDto.PROPERTY_DETAILLED_ACTIVITIES_OBSERVATION, + ProgramDto.PROPERTY_NON_TARGET_OBSERVATION, + ProgramDto.PROPERTY_BAIT_OBSERVATION, + ProgramDto.PROPERTY_MAMMALS_OBSERVATION, + ProgramDto.PROPERTY_SAMPLES_OBSERVATION, + ProgramDto.PROPERTY_OBJECTS_OBSERVATION, + ProgramDto.PROPERTY_BIRDS_OBSERVATION, + ProgramDto.PROPERTY_TARGET_DISCARDS_OBSERVATION).build(); + + private static final long serialVersionUID = 1L; + + protected boolean generalTabValid; + + protected boolean observationsTabValid; + + public ProgramUIModel() { + super(ProgramDto.class, + new String[]{ + ProgramDto.PROPERTY_ORGANISM, + ProgramDto.PROPERTY_START_DATE, + ProgramDto.PROPERTY_END_DATE, + ProgramDto.PROPERTY_DETAILLED_ACTIVITIES_OBSERVATION, + ProgramDto.PROPERTY_NON_TARGET_OBSERVATION, + ProgramDto.PROPERTY_BAIT_OBSERVATION, + ProgramDto.PROPERTY_MAMMALS_OBSERVATION, + ProgramDto.PROPERTY_SAMPLES_OBSERVATION, + ProgramDto.PROPERTY_OBJECTS_OBSERVATION, + ProgramDto.PROPERTY_BIRDS_OBSERVATION, + ProgramDto.PROPERTY_TARGET_DISCARDS_OBSERVATION, + ProgramDto.PROPERTY_GEAR_TYPE}, + new String[]{ + ProgramUI.BINDING_ORGANISM_SELECTED_ITEM, + ProgramUI.BINDING_START_DATE_DATE, + ProgramUI.BINDING_END_DATE_DATE, + ProgramUI.BINDING_DETAILLED_ACTIVITIES_OBSERVATION_SELECTED_INDEX, + ProgramUI.BINDING_NON_TARGET_OBSERVATION_SELECTED_INDEX, + ProgramUI.BINDING_BAIT_OBSERVATION_SELECTED_INDEX, + ProgramUI.BINDING_MAMMALS_OBSERVATION_SELECTED_INDEX, + ProgramUI.BINDING_SAMPLES_OBSERVATION_SELECTED_INDEX, + ProgramUI.BINDING_OBJECTS_OBSERVATION_SELECTED_INDEX, + ProgramUI.BINDING_BIRDS_OBSERVATION_SELECTED_INDEX, + ProgramUI.BINDING_TARGET_DISCARDS_OBSERVATION_SELECTED_INDEX, + ProgramUI.BINDING_GEAR_TYPE_SELECTED_ITEM} + ); + } + + public boolean isObservationsTabValid() { + return observationsTabValid; + } + + public void setObservationsTabValid(boolean observationsTabValid) { + Object oldValue = isObservationsTabValid(); + this.observationsTabValid = observationsTabValid; + firePropertyChange(PROPERTY_OBSERVATIONS_TAB_VALID, oldValue, observationsTabValid); + } + + public boolean isGeneralTabValid() { + return generalTabValid; + } + + public void setGeneralTabValid(boolean generalTabValid) { + Object oldValue = isGeneralTabValid(); + this.generalTabValid = generalTabValid; + firePropertyChange(PROPERTY_GENERAL_TAB_VALID, oldValue, generalTabValid); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/ReferenceEntity.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/ReferenceEntity.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/ReferenceEntity.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/ReferenceEntity.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SexUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SexUI.jaxx new file mode 100644 index 0000000..1531138 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SexUI.jaxx @@ -0,0 +1,164 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='SexDto' + contentTitle='{n("observe.content.title.sexx")}' + listText='{n("observe.content.list.sex")}' + createToolTip='{n("observe.content.action.sex.create.tip")}' + detailToolTip='{n("observe.content.action.sex.detail.tip")}' + modifyToolTip='{n("observe.content.action.sex.modify.tip")}' + deleteToolTip='{n("observe.content.action.sex.delete.tip")}' + saveToolTip='{n("observe.content.action.sex.save.tip")}' + + > + + <style source="ReferenceEntity.jcss"/> + <style source="I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.SexDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.SexDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <SexUIModel id='model'/> + + <!-- edit bean --> + <SexDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id="uriLabel"/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SexUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SexUIModel.java new file mode 100644 index 0000000..72291fd --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SexUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.SexDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/27/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class SexUIModel extends ContentReferenceUIModel<SexDto> { + + private static final long serialVersionUID = 1L; + + public SexUIModel() { + super(SexDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesGroupUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesGroupUI.jaxx new file mode 100644 index 0000000..6bfd929 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesGroupUI.jaxx @@ -0,0 +1,166 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='SpeciesGroupDto' + contentTitle='{n("observe.content.title.speciesGroupSpeciess")}' + listText='{n("observe.content.list.speciesGroupSpecies")}' + createToolTip='{n("observe.content.action.speciesGroupSpecies.create.tip")}' + detailToolTip='{n("observe.content.action.speciesGroupSpecies.detail.tip")}' + modifyToolTip='{n("observe.content.action.speciesGroupSpecies.modify.tip")}' + deleteToolTip='{n("observe.content.action.speciesGroupSpecies.delete.tip")}' + saveToolTip='{n("observe.content.action.speciesGroupSpecies.save.tip")}' + + > + + <style source="ReferenceEntity.jcss"/> + <style source="I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.SpeciesGroupDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + jaxx.runtime.swing.editor.NumberEditor + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.SpeciesGroupDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <SpeciesGroupUIModel id='model'/> + + <!-- edit bean --> + <SpeciesGroupDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesGroupUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesGroupUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesGroupUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesGroupUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesGroupUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesGroupUIModel.java new file mode 100644 index 0000000..137b09b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesGroupUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.SpeciesGroupDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/27/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class SpeciesGroupUIModel extends ContentReferenceUIModel<SpeciesGroupDto> { + + private static final long serialVersionUID = 1L; + + public SpeciesGroupUIModel() { + super(SpeciesGroupDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesListUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesListUI.jaxx new file mode 100644 index 0000000..b3c88a6 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesListUI.jaxx @@ -0,0 +1,206 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='SpeciesListDto' + contentTitle='{n("observe.content.title.speciesLists")}' + listText='{n("observe.content.list.speciesList")}' + createToolTip='{n("observe.content.action.speciesList.create.tip")}' + detailToolTip='{n("observe.content.action.speciesList.detail.tip")}' + modifyToolTip='{n("observe.content.action.speciesList.modify.tip")}' + deleteToolTip='{n("observe.content.action.speciesList.delete.tip")}' + saveToolTip='{n("observe.content.action.species.save.tip")}' + + > + + <style source="ReferenceEntity.jcss"/> + <style source="I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.SpeciesListDto + fr.ird.observe.services.dto.referential.SpeciesDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + jaxx.runtime.swing.editor.bean.BeanComboBox + org.nuiton.jaxx.widgets.select.FilterableDoubleList + + javax.swing.DefaultListModel + javax.swing.ListSelectionModel + + java.util.Collection + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.SpeciesListDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <SpeciesListUIModel id='model'/> + + <!-- edit bean --> + <SpeciesListDto id='bean'/> + + <!-- handler --> + <SpeciesListUIHandler id='handler' constructorParams="this"/> + + <Table id="editView" insets="0" fill="both"> + <row> + <cell anchor="north" weightx="1"> + <JTabbedPane id='tabPane'> + <tab id='generalTab'> + <Table fill="both"> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + + <row> + <cell columns="2"> + <Table id='editI18nTable2'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> + </cell> + </row> + <row> + <cell columns="2" weighty="1"> + <JLabel/> + </cell> + </row> + </Table> + </tab> + + <tab id='speciesTab'> + <Table fill="both" weightx="1"> + <!-- species --> + <row> + <cell weightx="1" weighty="1"> + <JScrollPane id='speciesPane' layout='{new GridLayout(1,1)}'> + <FilterableDoubleList id='species' + genericType='ReferentialReference<SpeciesDto>' + _entityClass='SpeciesDto.class'/> + </JScrollPane> + </cell> + </row> + </Table> + </tab> + </JTabbedPane> + </cell> + </row> + <row> + <cell columns="2" weighty="1"> + <JLabel/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesListUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesListUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesListUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesListUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesListUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesListUIHandler.java new file mode 100644 index 0000000..f429e7c --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesListUIHandler.java @@ -0,0 +1,102 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.SpeciesListDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIHandler; +import jaxx.runtime.validator.swing.SwingValidatorMessage; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.event.TableModelListener; +import java.util.HashSet; +import java.util.Set; + +/** + * Created on 1/11/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.11 + */ +public class SpeciesListUIHandler extends ContentReferenceUIHandler<SpeciesListDto> { + + // Compute valid state of tab from the error table + protected final TableModelListener computeTabValidStateListener; + + public SpeciesListUIHandler(ContentReferenceUI<SpeciesListDto> ui) { + super(ui); + computeTabValidStateListener = e -> { + + SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); + computeTabValidState(source); + + }; + } + + @Override + public void initUI() { + + super.initUI(); + + // To be sure always remove listener (could prevent some leaks) + getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); + // listen messages to see if required to add + getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); + + } + + @Override + public void selectBean(ReferentialReference<SpeciesListDto> selectedBean) { + + super.selectBean(selectedBean); + + SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); + computeTabValidState(errorTableModel); + + ((SpeciesListUI) getUi()).getTabPane().setSelectedIndex(0); + + } + + protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { + + Set<String> errorProperties = new HashSet<>(); + int rowCount = errorTableModel.getRowCount(); + for (int i = 0; i < rowCount; i++) { + + SwingValidatorMessage row = errorTableModel.getRow(i); + if (NuitonValidatorScope.ERROR.equals(row.getScope())) { + errorProperties.add(row.getField()); + } + } + + boolean generalTabValid = !errorProperties.removeAll(SpeciesListUIModel.GENERAL_TAB_PROPERTIES); + boolean speciesTabValid = !errorProperties.removeAll(SpeciesListUIModel.SPECIES_TAB_PROPERTIES); + + SpeciesListUIModel model = (SpeciesListUIModel) getModel(); + model.setGeneralTabValid(generalTabValid); + model.setSpeciesTabValid(speciesTabValid); + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesListUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesListUIModel.java new file mode 100644 index 0000000..52343cf --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesListUIModel.java @@ -0,0 +1,94 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.ImmutableSet; +import fr.ird.observe.services.dto.referential.SpeciesListDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +import java.util.Set; + +/** + * Created on 9/27/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class SpeciesListUIModel extends ContentReferenceUIModel<SpeciesListDto> { + + public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; + + public static final String PROPERTY_SPECIES_TAB_VALID = "speciesTabValid"; + + public static final Set<String> GENERAL_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(SpeciesListDto.PROPERTY_URI, + SpeciesListDto.PROPERTY_CODE, + SpeciesListDto.PROPERTY_STATUS, + SpeciesListDto.PROPERTY_NEED_COMMENT, + SpeciesListDto.PROPERTY_LABEL1, + SpeciesListDto.PROPERTY_LABEL2, + SpeciesListDto.PROPERTY_LABEL3, + SpeciesListDto.PROPERTY_LABEL4, + SpeciesListDto.PROPERTY_LABEL5, + SpeciesListDto.PROPERTY_LABEL6, + SpeciesListDto.PROPERTY_LABEL7, + SpeciesListDto.PROPERTY_LABEL8).build(); + + public static final Set<String> SPECIES_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(SpeciesListDto.PROPERTY_SPECIES).build(); + + private static final long serialVersionUID = 1L; + + protected boolean generalTabValid; + + protected boolean speciesTabValid; + + public SpeciesListUIModel() { + super(SpeciesListDto.class, + new String[]{SpeciesListDto.PROPERTY_SPECIES}, + new String[]{SpeciesListDto.PROPERTY_SPECIES + SUFFIX_SELECTED}, + null + ); + } + + public boolean isSpeciesTabValid() { + return speciesTabValid; + } + + public void setSpeciesTabValid(boolean speciesTabValid) { + Object oldValue = isSpeciesTabValid(); + this.speciesTabValid = speciesTabValid; + firePropertyChange(PROPERTY_SPECIES_TAB_VALID, oldValue, speciesTabValid); + } + + public boolean isGeneralTabValid() { + return generalTabValid; + } + + public void setGeneralTabValid(boolean generalTabValid) { + Object oldValue = isGeneralTabValid(); + this.generalTabValid = generalTabValid; + firePropertyChange(PROPERTY_GENERAL_TAB_VALID, oldValue, generalTabValid); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesUI.jaxx new file mode 100644 index 0000000..ae30ad1 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesUI.jaxx @@ -0,0 +1,282 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='SpeciesDto' + contentTitle='{n("observe.content.title.speciess")}' + listText='{n("observe.content.list.speciesFaune")}' + createToolTip='{n("observe.content.action.species.create.tip")}' + detailToolTip='{n("observe.content.action.species.detail.tip")}' + modifyToolTip='{n("observe.content.action.species.modify.tip")}' + deleteToolTip='{n("observe.content.action.species.delete.tip")}' + saveToolTip='{n("observe.content.action.species.save.tip")}' + + > + + <style source="ReferenceEntity.jcss"/> + <style source="I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.SpeciesDto + fr.ird.observe.services.dto.referential.SpeciesGroupDto + fr.ird.observe.services.dto.referential.OceanDto + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + org.nuiton.jaxx.widgets.select.FilterableDoubleList + + java.util.Collection + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.SpeciesDto' + context='ui-create' errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <SpeciesUIModel id='model'/> + + <!-- handler --> + <SpeciesUIHandler id='handler' constructorParams="this"/> + + <!-- edit bean --> + <SpeciesDto id='bean'/> + + <Table id="editView" insets="0" fill="both"> + <row> + <cell anchor="north" weightx="1"> + <JTabbedPane id='tabPane'> + <tab id='generalTab'> + <Table fill="both"> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' constructorParams='ReferenceStatus.class' genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- homeId / faoCode / wormsId --> + <row> + <cell anchor="west"> + <JLabel id='homeIdFAOWormsIdLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel layout='{new GridLayout()}'> + <JTextField id='homeId' onKeyReleased='getBean().setHomeId(homeId.getText())'/> + <JTextField id='faoCode' onKeyReleased='getBean().setFaoCode(faoCode.getText())'/> + <JTextField id='wormsId' onKeyReleased='getBean().setWormsId(Long.valueOf(wormsId.getText()))'/> + </JPanel> + </cell> + </row> + + <!-- speciesGroup --> + <row> + <cell anchor='west'> + <JLabel id='speciesGroupLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='speciesGroup' constructorParams='this' genericType='ReferentialReference<SpeciesGroupDto>' _entityClass='SpeciesGroupDto.class'/> + </cell> + </row> + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + + <row> + <cell columns="2"> + <Table id='editI18nTable2'> + <!-- scientificLabel --> + <row> + <cell anchor='west'> + <JLabel id='scientificLabelLabel'/> + </cell> + <cell anchor='east' fill="both" columns="3"> + <JTextField id='scientificLabel' + onKeyReleased='getBean().setScientificLabel(scientificLabel.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> + </cell> + </row> + <row> + <cell columns="2" weighty="1"> + <JLabel/> + </cell> + </row> + </Table> + </tab> + + <tab id='otherTab'> + <Table fill="both"> + <row> + <cell weightx="1"> + <Table id="editTaillePoids" fill='both' insets="1"> + + <!-- lengthMeasureType --> + <row> + <cell anchor="west"> + <JLabel id='lengthMeasureTypeLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='lengthMeasureType' + onKeyReleased='getBean().setLengthMeasureType(lengthMeasureType.getText())'/> + </cell> + </row> + + <!-- minLengthMax --> + <row> + <cell anchor="west"> + <JLabel id='minLengthMaxLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel layout='{new GridLayout()}'> + <NumberEditor id='minLength' constructorParams='this' styleClass="float2"/> + <NumberEditor id='maxLength' constructorParams='this' styleClass="float2"/> + </JPanel> + </cell> + </row> + + <!-- minWeightMax --> + <row> + <cell anchor="west"> + <JLabel id='minWeightMaxLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel layout='{new GridLayout()}'> + <NumberEditor id='minWeight' constructorParams='this' styleClass="float2"/> + <NumberEditor id='maxWeight' constructorParams='this' styleClass="float2"/> + </JPanel> + </cell> + </row> + + </Table> + </cell> + </row> + + <row> + <cell weightx="1"> + <JScrollPane id='oceanPane' layout='{new GridLayout(1,1)}' onFocusGained='ocean.requestFocus()'> + <FilterableDoubleList id='ocean' genericType='ReferentialReference<OceanDto>' _entityClass='OceanDto.class'/> + </JScrollPane> + </cell> + </row> + + <row> + <cell columns="2" weighty="1"> + <JLabel/> + </cell> + </row> + </Table> + </tab> + </JTabbedPane> + </cell> + </row> + <row> + <cell columns="2" weighty="1"> + <JLabel/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesUIHandler.java new file mode 100644 index 0000000..f6f3043 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesUIHandler.java @@ -0,0 +1,102 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.SpeciesDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIHandler; +import jaxx.runtime.validator.swing.SwingValidatorMessage; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.event.TableModelListener; +import java.util.HashSet; +import java.util.Set; + +/** + * Created on 1/11/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.11 + */ +public class SpeciesUIHandler extends ContentReferenceUIHandler<SpeciesDto> { + + // Compute valid state of tab from the error table + protected final TableModelListener computeTabValidStateListener; + + public SpeciesUIHandler(ContentReferenceUI<SpeciesDto> ui) { + super(ui); + computeTabValidStateListener = e -> { + + SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); + computeTabValidState(source); + + }; + } + + @Override + public void initUI() { + + super.initUI(); + + // To be sure always remove listener (could prevent some leaks) + getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); + // listen messages to see if required to add + getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); + + } + + @Override + public void selectBean(ReferentialReference<SpeciesDto> selectedBean) { + + super.selectBean(selectedBean); + + SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); + computeTabValidState(errorTableModel); + + ((SpeciesUI) getUi()).getTabPane().setSelectedIndex(0); + + } + + protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { + + Set<String> errorProperties = new HashSet<>(); + int rowCount = errorTableModel.getRowCount(); + for (int i = 0; i < rowCount; i++) { + + SwingValidatorMessage row = errorTableModel.getRow(i); + if (NuitonValidatorScope.ERROR.equals(row.getScope())) { + errorProperties.add(row.getField()); + } + } + + boolean generalTabValid = !errorProperties.removeAll(SpeciesUIModel.GENERAL_TAB_PROPERTIES); + boolean otherTabValid = !errorProperties.removeAll(SpeciesUIModel.OTHER_TAB_PROPERTIES); + + SpeciesUIModel model = (SpeciesUIModel) getModel(); + model.setGeneralTabValid(generalTabValid); + model.setOtherTabValid(otherTabValid); + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesUIModel.java new file mode 100644 index 0000000..16debc4 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/SpeciesUIModel.java @@ -0,0 +1,124 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.ImmutableSet; +import fr.ird.observe.services.dto.referential.SpeciesDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +import java.util.Set; + +/** + * Created on 9/27/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class SpeciesUIModel extends ContentReferenceUIModel<SpeciesDto> { + + public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; + + public static final String PROPERTY_OTHER_TAB_VALID = "otherTabValid"; + + public static final Set<String> GENERAL_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(SpeciesDto.PROPERTY_URI, + SpeciesDto.PROPERTY_CODE, + SpeciesDto.PROPERTY_STATUS, + SpeciesDto.PROPERTY_FAO_CODE, + SpeciesDto.PROPERTY_HOME_ID, + SpeciesDto.PROPERTY_WORMS_ID, + SpeciesDto.PROPERTY_NEED_COMMENT, + SpeciesDto.PROPERTY_SCIENTIFIC_LABEL, + SpeciesDto.PROPERTY_LABEL1, + SpeciesDto.PROPERTY_LABEL2, + SpeciesDto.PROPERTY_LABEL3, + SpeciesDto.PROPERTY_LABEL4, + SpeciesDto.PROPERTY_LABEL5, + SpeciesDto.PROPERTY_LABEL6, + SpeciesDto.PROPERTY_LABEL7, + SpeciesDto.PROPERTY_LABEL8).build(); + + public static final Set<String> OTHER_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(SpeciesDto.PROPERTY_SPECIES_GROUP, + SpeciesDto.PROPERTY_OCEAN, + SpeciesDto.PROPERTY_MAX_LENGTH, + SpeciesDto.PROPERTY_MIN_LENGTH, + SpeciesDto.PROPERTY_MAX_WEIGHT, + SpeciesDto.PROPERTY_MIN_WEIGHT).build(); + + private static final long serialVersionUID = 1L; + + protected boolean generalTabValid; + + protected boolean otherTabValid; + + + public SpeciesUIModel() { + super(SpeciesDto.class, + new String[]{SpeciesDto.PROPERTY_SPECIES_GROUP, + SpeciesDto.PROPERTY_OCEAN, + SpeciesDto.PROPERTY_LENGTH_MEASURE_TYPE, + SpeciesDto.PROPERTY_MIN_LENGTH, + SpeciesDto.PROPERTY_MAX_LENGTH, + SpeciesDto.PROPERTY_MIN_WEIGHT, + SpeciesDto.PROPERTY_MAX_WEIGHT, + SpeciesDto.PROPERTY_HOME_ID, + SpeciesDto.PROPERTY_FAO_CODE, + SpeciesDto.PROPERTY_WORMS_ID, + SpeciesDto.PROPERTY_SCIENTIFIC_LABEL}, + new String[]{ + SpeciesDto.PROPERTY_SPECIES_GROUP + SUFFIX_SELECTED_ITEM, + SpeciesDto.PROPERTY_LENGTH_MEASURE_TYPE + SUFFIX_TEXT, + SpeciesDto.PROPERTY_MIN_LENGTH + SUFFIX_MODEL, + SpeciesDto.PROPERTY_MAX_LENGTH + SUFFIX_MODEL, + SpeciesDto.PROPERTY_MIN_WEIGHT + SUFFIX_MODEL, + SpeciesDto.PROPERTY_MAX_WEIGHT + SUFFIX_MODEL, + SpeciesDto.PROPERTY_HOME_ID + SUFFIX_TEXT, + SpeciesDto.PROPERTY_FAO_CODE + SUFFIX_TEXT, + SpeciesDto.PROPERTY_WORMS_ID + SUFFIX_TEXT, + SpeciesDto.PROPERTY_SCIENTIFIC_LABEL + SUFFIX_TEXT, + SpeciesDto.PROPERTY_OCEAN + SUFFIX_SELECTED} + ); + } + + public boolean isOtherTabValid() { + return otherTabValid; + } + + public void setOtherTabValid(boolean otherTabValid) { + Object oldValue = isOtherTabValid(); + this.otherTabValid = otherTabValid; + firePropertyChange(PROPERTY_OTHER_TAB_VALID, oldValue, otherTabValid); + } + + public boolean isGeneralTabValid() { + return generalTabValid; + } + + public void setGeneralTabValid(boolean generalTabValid) { + Object oldValue = isGeneralTabValid(); + this.generalTabValid = generalTabValid; + firePropertyChange(PROPERTY_GENERAL_TAB_VALID, oldValue, generalTabValid); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselSizeCategoryUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselSizeCategoryUI.jaxx new file mode 100644 index 0000000..b2a1b5a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselSizeCategoryUI.jaxx @@ -0,0 +1,121 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='VesselSizeCategoryDto' + contentTitle='{n("observe.content.title.vesselSizeCategoryx")}' + listText='{n("observe.content.list.vesselSizeCategory")}' + createToolTip='{n("observe.content.action.vesselSizeCategory.create.tip")}' + detailToolTip='{n("observe.content.action.vesselSizeCategory.detail.tip")}' + modifyToolTip='{n("observe.content.action.vesselSizeCategory.modify.tip")}' + deleteToolTip='{n("observe.content.action.vesselSizeCategory.delete.tip")}' + saveToolTip='{n("observe.content.action.vesselSizeCategory.save.tip")}' + + > + + <style source="ReferenceEntity.jcss"/> + <style source="I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.VesselSizeCategoryDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.VesselSizeCategoryDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <VesselSizeCategoryUIModel id='model'/> + + <!-- edit bean --> + <VesselSizeCategoryDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + + <!-- gaugeLabel --> + <row> + <cell anchor="west"> + <JLabel id='gaugeLabelLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='gaugeLabel' + onKeyReleased='getBean().setGaugeLabel(gaugeLabel.getText())'/> + </cell> + </row> + + <!-- capacityLabel --> + <row> + <cell anchor="west"> + <JLabel id='capacityLabelLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='capacityLabel' + onKeyReleased='getBean().setCapacityLabel(capacityLabel.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselSizeCategoryUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselSizeCategoryUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselSizeCategoryUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselSizeCategoryUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselSizeCategoryUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselSizeCategoryUIModel.java new file mode 100644 index 0000000..ead3119 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselSizeCategoryUIModel.java @@ -0,0 +1,50 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.VesselSizeCategoryDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/27/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class VesselSizeCategoryUIModel extends ContentReferenceUIModel<VesselSizeCategoryDto> { + + private static final long serialVersionUID = 1L; + + public VesselSizeCategoryUIModel() { + super(VesselSizeCategoryDto.class, + new String[]{ + VesselSizeCategoryDto.PROPERTY_GAUGE_LABEL, + VesselSizeCategoryDto.PROPERTY_CAPACITY_LABEL + }, + new String[]{ + VesselSizeCategoryUI.BINDING_CAPACITY_LABEL_TEXT, + VesselSizeCategoryUI.BINDING_GAUGE_LABEL_TEXT} + ); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselTypeUI.jaxx new file mode 100644 index 0000000..4893a16 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselTypeUI.jaxx @@ -0,0 +1,164 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='VesselTypeDto' + contentTitle='{n("observe.content.title.vesselTypex")}' + listText='{n("observe.content.list.vesselType")}' + createToolTip='{n("observe.content.action.vesselType.create.tip")}' + detailToolTip='{n("observe.content.action.vesselType.detail.tip")}' + modifyToolTip='{n("observe.content.action.vesselType.modify.tip")}' + deleteToolTip='{n("observe.content.action.vesselType.delete.tip")}' + saveToolTip='{n("observe.content.action.vesselType.save.tip")}' + + > + + <style source="ReferenceEntity.jcss"/> + <style source="I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.VesselTypeDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.VesselTypeDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <VesselTypeUIModel id='model'/> + + <!-- edit bean --> + <VesselTypeDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id="uriLabel"/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselTypeUIModel.java new file mode 100644 index 0000000..98fc319 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselTypeUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.VesselTypeDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/27/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class VesselTypeUIModel extends ContentReferenceUIModel<VesselTypeDto> { + + private static final long serialVersionUID = 1L; + + public VesselTypeUIModel() { + super(VesselTypeDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselUI.jaxx new file mode 100644 index 0000000..16995a9 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselUI.jaxx @@ -0,0 +1,297 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='VesselDto' + contentTitle='{n("observe.content.title.vesselx")}' + listText='{n("observe.content.list.vessel")}' + createToolTip='{n("observe.content.action.vessel.create.tip")}' + detailToolTip='{n("observe.content.action.vessel.detail.tip")}' + modifyToolTip='{n("observe.content.action.vessel.modify.tip")}' + deleteToolTip='{n("observe.content.action.vessel.delete.tip")}' + saveToolTip='{n("observe.content.action.vessel.save.tip")}' + + > + + <style source="ReferenceEntity.jcss"/> + <style source="I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.VesselDto + fr.ird.observe.services.dto.referential.VesselSizeCategoryDto + fr.ird.observe.services.dto.referential.CountryDto + fr.ird.observe.services.dto.referential.VesselTypeDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + org.jdesktop.swingx.JXDatePicker + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' context='ui-create' + beanClass='fr.ird.observe.services.dto.referential.VesselDto' errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <VesselUIModel id='model'/> + + <!-- handler --> + <VesselUIHandler id='handler' constructorParams="this"/> + + <!-- edit bean --> + <VesselDto id='bean'/> + + <Table id="editView" insets="0" fill="both"> + <row> + <cell anchor="north" weightx="1"> + <JTabbedPane id='tabPane'> + <tab id='generalTab'> + <Table fill="both"> + + <!-- keelCode / fleetCountry --> + <row> + <cell anchor="west"> + <JLabel id='keelCodeFlotteLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel layout='{new GridLayout()}'> + <NumberEditor id='keelCode' constructorParams='this' styleClass="integer"/> + <NumberEditor id='fleetCountry' constructorParams='this' styleClass="integer"/> + </JPanel> + </cell> + </row> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' constructorParams='ReferenceStatus.class' genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- vesselType --> + <row> + <cell anchor='west'> + <JLabel id='vesselTypeLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='vesselType' constructorParams='this' genericType='ReferentialReference<VesselTypeDto>' _entityClass='VesselTypeDto.class'/> + </cell> + </row> + + <!-- vesselSizeCategory --> + <row> + <cell anchor='west'> + <JLabel id='vesselSizeCategoryLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='vesselSizeCategory' constructorParams='this' genericType='ReferentialReference<VesselSizeCategoryDto>' _entityClass='VesselSizeCategoryDto.class'/> + </cell> + </row> + + <!-- flagCountry --> + <row> + <cell anchor='west'> + <JLabel id='flagCountryLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='flagCountry' constructorParams='this' genericType='ReferentialReference<CountryDto>' _entityClass='CountryDto.class'/> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + <row> + <cell columns="2"> + <Table id='editI18nTable2'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> + </cell> + </row> + <row> + <cell columns="2" weighty="1"> + <JLabel/> + </cell> + </row> + </Table> + </tab> + + <tab id='otherTab'> + <Table fill="both"> + <!-- length --> + <row> + <cell anchor="west"> + <JLabel id='lengthLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <NumberEditor id='length' constructorParams='this' styleClass="float2"/> + </cell> + </row> + + <!-- capacity --> + <row> + <cell anchor="west"> + <JLabel id='capacityLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <NumberEditor id='capacity' constructorParams='this' styleClass="float2"/> + </cell> + </row> + + <!-- power --> + <row> + <cell anchor="west"> + <JLabel id='powerLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <NumberEditor id='power' constructorParams='this' styleClass="integer"/> + </cell> + </row> + + <!-- searchMaximum --> + <row> + <cell anchor="west"> + <JLabel id='searchMaximumLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <NumberEditor id='searchMaximum' constructorParams='this' styleClass="float2"/> + </cell> + </row> + + <!-- yearService --> + <row> + <cell anchor="west"> + <JLabel id='yearServiceLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <NumberEditor id='yearService' constructorParams='this' styleClass="integer"/> + </cell> + </row> + + <!-- changeDate --> + <row> + <cell anchor='west'> + <JLabel id='changeDateLabel'/> + </cell> + <cell anchor='west'> + <JXDatePicker id='changeDate' onActionPerformed='getBean().setChangeDate(changeDate.getDate())'/> + </cell> + </row> + <row> + <cell columns="2" weighty="1"> + <JLabel/> + </cell> + </row> + </Table> + </tab> + </JTabbedPane> + </cell> + </row> + <row> + <cell columns="2" weighty="1"> + <JLabel/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselUIHandler.java new file mode 100644 index 0000000..ca813c5 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselUIHandler.java @@ -0,0 +1,102 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.VesselDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIHandler; +import jaxx.runtime.validator.swing.SwingValidatorMessage; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.event.TableModelListener; +import java.util.HashSet; +import java.util.Set; + +/** + * Created on 1/11/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.11 + */ +public class VesselUIHandler extends ContentReferenceUIHandler<VesselDto> { + + // Compute valid state of tab from the error table + protected final TableModelListener computeTabValidStateListener; + + public VesselUIHandler(ContentReferenceUI<VesselDto> ui) { + super(ui); + computeTabValidStateListener = e -> { + + SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); + computeTabValidState(source); + + }; + } + + @Override + public void initUI() { + + super.initUI(); + + // To be sure always remove listener (could prevent some leaks) + getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); + // listen messages to see if required to add + getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); + + } + + @Override + public void selectBean(ReferentialReference<VesselDto> selectedBean) { + + super.selectBean(selectedBean); + + SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); + computeTabValidState(errorTableModel); + + ((VesselUI) getUi()).getTabPane().setSelectedIndex(0); + + } + + protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { + + Set<String> errorProperties = new HashSet<>(); + int rowCount = errorTableModel.getRowCount(); + for (int i = 0; i < rowCount; i++) { + + SwingValidatorMessage row = errorTableModel.getRow(i); + if (NuitonValidatorScope.ERROR.equals(row.getScope())) { + errorProperties.add(row.getField()); + } + } + + boolean generalTabValid = !errorProperties.removeAll(VesselUIModel.GENERAL_TAB_PROPERTIES); + boolean otherTabValid = !errorProperties.removeAll(VesselUIModel.OTHER_TAB_PROPERTIES); + + VesselUIModel model = (VesselUIModel) getModel(); + model.setGeneralTabValid(generalTabValid); + model.setOtherTabValid(otherTabValid); + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselUIModel.java new file mode 100644 index 0000000..17dcebc --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/VesselUIModel.java @@ -0,0 +1,126 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.ImmutableSet; +import fr.ird.observe.services.dto.referential.VesselDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +import java.util.Set; + +/** + * Created on 9/27/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class VesselUIModel extends ContentReferenceUIModel<VesselDto> { + + public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; + + public static final String PROPERTY_OTHER_TAB_VALID = "otherTabValid"; + + public static final Set<String> GENERAL_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(VesselDto.PROPERTY_URI, + VesselDto.PROPERTY_CODE, + VesselDto.PROPERTY_STATUS, + VesselDto.PROPERTY_KEEL_CODE, + VesselDto.PROPERTY_VESSEL_TYPE, + VesselDto.PROPERTY_VESSEL_SIZE_CATEGORY, + VesselDto.PROPERTY_NEED_COMMENT, + VesselDto.PROPERTY_FLAG_COUNTRY, + VesselDto.PROPERTY_FLEET_COUNTRY, + VesselDto.PROPERTY_LABEL1, + VesselDto.PROPERTY_LABEL2, + VesselDto.PROPERTY_LABEL3, + VesselDto.PROPERTY_LABEL4, + VesselDto.PROPERTY_LABEL5, + VesselDto.PROPERTY_LABEL6, + VesselDto.PROPERTY_LABEL7, + VesselDto.PROPERTY_LABEL8).build(); + + public static final Set<String> OTHER_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(VesselDto.PROPERTY_CAPACITY, + VesselDto.PROPERTY_CHANGE_DATE, + VesselDto.PROPERTY_COMMENT, + VesselDto.PROPERTY_LENGTH, + VesselDto.PROPERTY_LENGTH, + VesselDto.PROPERTY_POWER, + VesselDto.PROPERTY_SEARCH_MAXIMUM, + VesselDto.PROPERTY_YEAR_SERVICE).build(); + + private static final long serialVersionUID = 1L; + + protected boolean generalTabValid; + + protected boolean otherTabValid; + + public VesselUIModel() { + super(VesselDto.class, + new String[]{ + VesselDto.PROPERTY_VESSEL_TYPE, + VesselDto.PROPERTY_VESSEL_SIZE_CATEGORY, + VesselDto.PROPERTY_FLAG_COUNTRY, + VesselDto.PROPERTY_KEEL_CODE, + VesselDto.PROPERTY_FLEET_COUNTRY, + VesselDto.PROPERTY_YEAR_SERVICE, + VesselDto.PROPERTY_LENGTH, + VesselDto.PROPERTY_CAPACITY, + VesselDto.PROPERTY_POWER, + VesselDto.PROPERTY_SEARCH_MAXIMUM, + VesselDto.PROPERTY_CHANGE_DATE}, + new String[]{VesselUI.BINDING_VESSEL_TYPE_SELECTED_ITEM, + VesselUI.BINDING_VESSEL_SIZE_CATEGORY_SELECTED_ITEM, + VesselUI.BINDING_FLAG_COUNTRY_SELECTED_ITEM, + VesselUI.BINDING_KEEL_CODE_MODEL, + VesselUI.BINDING_FLEET_COUNTRY_MODEL, + VesselUI.BINDING_YEAR_SERVICE_MODEL, + VesselUI.BINDING_LENGTH_MODEL, + VesselUI.BINDING_CAPACITY_MODEL, + VesselUI.BINDING_POWER_MODEL, + VesselUI.BINDING_SEARCH_MAXIMUM_MODEL, + VesselUI.BINDING_CHANGE_DATE_DATE} + ); + } + + public boolean isOtherTabValid() { + return otherTabValid; + } + + public void setOtherTabValid(boolean otherTabValid) { + Object oldValue = isOtherTabValid(); + this.otherTabValid = otherTabValid; + firePropertyChange(PROPERTY_OTHER_TAB_VALID, oldValue, otherTabValid); + } + + public boolean isGeneralTabValid() { + return generalTabValid; + } + + public void setGeneralTabValid(boolean generalTabValid) { + Object oldValue = isGeneralTabValid(); + this.generalTabValid = generalTabValid; + firePropertyChange(PROPERTY_GENERAL_TAB_VALID, oldValue, generalTabValid); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/BaitHaulingStatusUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/BaitHaulingStatusUI.jaxx new file mode 100644 index 0000000..8f99794 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/BaitHaulingStatusUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='BaitHaulingStatusDto' + contentTitle='{n("observe.content.title.baitHaulingStatuss")}' + listText='{n("observe.content.list.baitHaulingStatus")}' + createToolTip='{n("observe.content.action.baitHaulingStatus.create.tip")}' + detailToolTip='{n("observe.content.action.baitHaulingStatus.detail.tip")}' + modifyToolTip='{n("observe.content.action.baitHaulingStatus.modify.tip")}' + deleteToolTip='{n("observe.content.action.baitHaulingStatus.delete.tip")}' + saveToolTip='{n("observe.content.action.baitHaulingStatus.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.BaitHaulingStatusDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.BaitHaulingStatusDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <BaitHaulingStatusUIModel id='model'/> + + <!-- edit bean --> + <BaitHaulingStatusDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/BaitHaulingStatusUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/BaitHaulingStatusUIModel.java new file mode 100644 index 0000000..856143f --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/BaitHaulingStatusUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.BaitHaulingStatusDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class BaitHaulingStatusUIModel extends ContentReferenceUIModel<BaitHaulingStatusDto> { + + private static final long serialVersionUID = 1L; + + public BaitHaulingStatusUIModel() { + super(BaitHaulingStatusDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/BaitSettingStatusUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/BaitSettingStatusUI.jaxx new file mode 100644 index 0000000..f379d78 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/BaitSettingStatusUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='BaitSettingStatusDto' + contentTitle='{n("observe.content.title.baitSettingStatuss")}' + listText='{n("observe.content.list.baitSettingStatus")}' + createToolTip='{n("observe.content.action.baitSettingStatus.create.tip")}' + detailToolTip='{n("observe.content.action.baitSettingStatus.detail.tip")}' + modifyToolTip='{n("observe.content.action.baitSettingStatus.modify.tip")}' + deleteToolTip='{n("observe.content.action.baitSettingStatus.delete.tip")}' + saveToolTip='{n("observe.content.action.baitSettingStatus.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.BaitSettingStatusDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.BaitSettingStatusDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <BaitSettingStatusUIModel id='model'/> + + <!-- edit bean --> + <BaitSettingStatusDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/BaitSettingStatusUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/BaitSettingStatusUIModel.java new file mode 100644 index 0000000..4b0849d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/BaitSettingStatusUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.BaitSettingStatusDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class BaitSettingStatusUIModel extends ContentReferenceUIModel<BaitSettingStatusDto> { + + private static final long serialVersionUID = 1L; + + public BaitSettingStatusUIModel() { + super(BaitSettingStatusDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/BaitTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/BaitTypeUI.jaxx new file mode 100644 index 0000000..39bc47e --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/BaitTypeUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='BaitTypeDto' + contentTitle='{n("observe.content.title.baitTypes")}' + listText='{n("observe.content.list.baitType")}' + createToolTip='{n("observe.content.action.baitType.create.tip")}' + detailToolTip='{n("observe.content.action.baitType.detail.tip")}' + modifyToolTip='{n("observe.content.action.baitType.modify.tip")}' + deleteToolTip='{n("observe.content.action.baitType.delete.tip")}' + saveToolTip='{n("observe.content.action.baitType.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.BaitTypeDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.BaitTypeDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <BaitTypeUIModel id='model'/> + + <!-- edit bean --> + <BaitTypeDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/BaitTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/BaitTypeUIModel.java new file mode 100644 index 0000000..7011363 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/BaitTypeUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.BaitTypeDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class BaitTypeUIModel extends ContentReferenceUIModel<BaitTypeDto> { + + private static final long serialVersionUID = 1L; + + public BaitTypeUIModel() { + super(BaitTypeDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/CatchFateLonglineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/CatchFateLonglineUI.jaxx new file mode 100644 index 0000000..8677759 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/CatchFateLonglineUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='CatchFateLonglineDto' + contentTitle='{n("observe.content.title.catchFateLonglines")}' + listText='{n("observe.content.list.catchFateLongline")}' + createToolTip='{n("observe.content.action.catchFateLongline.create.tip")}' + detailToolTip='{n("observe.content.action.catchFateLongline.detail.tip")}' + modifyToolTip='{n("observe.content.action.catchFateLongline.modify.tip")}' + deleteToolTip='{n("observe.content.action.catchFateLongline.delete.tip")}' + saveToolTip='{n("observe.content.action.catchFateLongline.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.CatchFateLonglineDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.CatchFateLonglineDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <CatchFateLonglineUIModel id='model'/> + + <!-- edit bean --> + <CatchFateLonglineDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/CatchFateLonglineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/CatchFateLonglineUIModel.java new file mode 100644 index 0000000..47eceb7 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/CatchFateLonglineUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.CatchFateLonglineDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class CatchFateLonglineUIModel extends ContentReferenceUIModel<CatchFateLonglineDto> { + + private static final long serialVersionUID = 1L; + + public CatchFateLonglineUIModel() { + super(CatchFateLonglineDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/EncounterTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/EncounterTypeUI.jaxx new file mode 100644 index 0000000..a43527b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/EncounterTypeUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='EncounterTypeDto' + contentTitle='{n("observe.content.title.encounterTypes")}' + listText='{n("observe.content.list.encounterType")}' + createToolTip='{n("observe.content.action.encounterType.create.tip")}' + detailToolTip='{n("observe.content.action.encounterType.detail.tip")}' + modifyToolTip='{n("observe.content.action.encounterType.modify.tip")}' + deleteToolTip='{n("observe.content.action.encounterType.delete.tip")}' + saveToolTip='{n("observe.content.action.encounterType.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.EncounterTypeDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.EncounterTypeDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <EncounterTypeUIModel id='model'/> + + <!-- edit bean --> + <EncounterTypeDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/EncounterTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/EncounterTypeUIModel.java new file mode 100644 index 0000000..55b034a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/EncounterTypeUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.EncounterTypeDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class EncounterTypeUIModel extends ContentReferenceUIModel<EncounterTypeDto> { + + private static final long serialVersionUID = 1L; + + public EncounterTypeUIModel() { + super(EncounterTypeDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HealthnessUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HealthnessUI.jaxx new file mode 100644 index 0000000..f2c5a29 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HealthnessUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='HealthnessDto' + contentTitle='{n("observe.content.title.healthnesss")}' + listText='{n("observe.content.list.healthness")}' + createToolTip='{n("observe.content.action.healthness.create.tip")}' + detailToolTip='{n("observe.content.action.healthness.detail.tip")}' + modifyToolTip='{n("observe.content.action.healthness.modify.tip")}' + deleteToolTip='{n("observe.content.action.healthness.delete.tip")}' + saveToolTip='{n("observe.content.action.healthness.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.HealthnessDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.HealthnessDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <HealthnessUIModel id='model'/> + + <!-- edit bean --> + <HealthnessDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HealthnessUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HealthnessUIModel.java new file mode 100644 index 0000000..fe7695d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HealthnessUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.HealthnessDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class HealthnessUIModel extends ContentReferenceUIModel<HealthnessDto> { + + private static final long serialVersionUID = 1L; + + public HealthnessUIModel() { + super(HealthnessDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HookPositionUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HookPositionUI.jaxx new file mode 100644 index 0000000..13904bc --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HookPositionUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='HookPositionDto' + contentTitle='{n("observe.content.title.hookPositions")}' + listText='{n("observe.content.list.hookPosition")}' + createToolTip='{n("observe.content.action.hookPosition.create.tip")}' + detailToolTip='{n("observe.content.action.hookPosition.detail.tip")}' + modifyToolTip='{n("observe.content.action.hookPosition.modify.tip")}' + deleteToolTip='{n("observe.content.action.hookPosition.delete.tip")}' + saveToolTip='{n("observe.content.action.hookPosition.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.HookPositionDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.HookPositionDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <HookPositionUIModel id='model'/> + + <!-- edit bean --> + <HookPositionDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HookPositionUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HookPositionUIModel.java new file mode 100644 index 0000000..dac8eca --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HookPositionUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.HookPositionDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class HookPositionUIModel extends ContentReferenceUIModel<HookPositionDto> { + + private static final long serialVersionUID = 1L; + + public HookPositionUIModel() { + super(HookPositionDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HookSizeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HookSizeUI.jaxx new file mode 100644 index 0000000..cd7345d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HookSizeUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='HookSizeDto' + contentTitle='{n("observe.content.title.HookSizes")}' + listText='{n("observe.content.list.HookSize")}' + createToolTip='{n("observe.content.action.hookSize.create.tip")}' + detailToolTip='{n("observe.content.action.hookSize.detail.tip")}' + modifyToolTip='{n("observe.content.action.hookSize.modify.tip")}' + deleteToolTip='{n("observe.content.action.hookSize.delete.tip")}' + saveToolTip='{n("observe.content.action.hookSize.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.HookSizeDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.HookSizeDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <HookSizeUIModel id='model'/> + + <!-- edit bean --> + <HookSizeDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HookSizeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HookSizeUIModel.java new file mode 100644 index 0000000..4b984cc --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HookSizeUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.HookSizeDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class HookSizeUIModel extends ContentReferenceUIModel<HookSizeDto> { + + private static final long serialVersionUID = 1L; + + public HookSizeUIModel() { + super(HookSizeDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HookTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HookTypeUI.jaxx new file mode 100644 index 0000000..bea8f39 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HookTypeUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='HookTypeDto' + contentTitle='{n("observe.content.title.HookTypes")}' + listText='{n("observe.content.list.HookType")}' + createToolTip='{n("observe.content.action.hookType.create.tip")}' + detailToolTip='{n("observe.content.action.hookType.detail.tip")}' + modifyToolTip='{n("observe.content.action.hookType.modify.tip")}' + deleteToolTip='{n("observe.content.action.hookType.delete.tip")}' + saveToolTip='{n("observe.content.action.hookType.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.HookTypeDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.HookTypeDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <HookTypeUIModel id='model'/> + + <!-- edit bean --> + <HookTypeDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HookTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HookTypeUIModel.java new file mode 100644 index 0000000..1d8fa33 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/HookTypeUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.HookTypeDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class HookTypeUIModel extends ContentReferenceUIModel<HookTypeDto> { + + private static final long serialVersionUID = 1L; + + public HookTypeUIModel() { + super(HookTypeDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/ItemHorizontalPositionUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/ItemHorizontalPositionUI.jaxx new file mode 100644 index 0000000..d374d62 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/ItemHorizontalPositionUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='ItemHorizontalPositionDto' + contentTitle='{n("observe.content.title.itemHorizontalPositions")}' + listText='{n("observe.content.list.itemHorizontalPosition")}' + createToolTip='{n("observe.content.action.itemHorizontalPosition.create.tip")}' + detailToolTip='{n("observe.content.action.itemHorizontalPosition.detail.tip")}' + modifyToolTip='{n("observe.content.action.itemHorizontalPosition.modify.tip")}' + deleteToolTip='{n("observe.content.action.itemHorizontalPosition.delete.tip")}' + saveToolTip='{n("observe.content.action.itemHorizontalPosition.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.ItemHorizontalPositionDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.ItemHorizontalPositionDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <ItemHorizontalPositionUIModel id='model'/> + + <!-- edit bean --> + <ItemHorizontalPositionDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/ItemHorizontalPositionUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/ItemHorizontalPositionUIModel.java new file mode 100644 index 0000000..ba9aea4 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/ItemHorizontalPositionUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.ItemHorizontalPositionDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ItemHorizontalPositionUIModel extends ContentReferenceUIModel<ItemHorizontalPositionDto> { + + private static final long serialVersionUID = 1L; + + public ItemHorizontalPositionUIModel() { + super(ItemHorizontalPositionDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/ItemVerticalPositionUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/ItemVerticalPositionUI.jaxx new file mode 100644 index 0000000..56198eb --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/ItemVerticalPositionUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='ItemVerticalPositionDto' + contentTitle='{n("observe.content.title.itemVerticalPositions")}' + listText='{n("observe.content.list.itemVerticalPosition")}' + createToolTip='{n("observe.content.action.itemVerticalPosition.create.tip")}' + detailToolTip='{n("observe.content.action.itemVerticalPosition.detail.tip")}' + modifyToolTip='{n("observe.content.action.itemVerticalPosition.modify.tip")}' + deleteToolTip='{n("observe.content.action.itemVerticalPosition.delete.tip")}' + saveToolTip='{n("observe.content.action.itemVerticalPosition.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.ItemVerticalPositionDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.ItemVerticalPositionDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <ItemVerticalPositionUIModel id='model'/> + + <!-- edit bean --> + <ItemVerticalPositionDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/ItemVerticalPositionUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/ItemVerticalPositionUIModel.java new file mode 100644 index 0000000..4953e2c --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/ItemVerticalPositionUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.ItemVerticalPositionDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ItemVerticalPositionUIModel extends ContentReferenceUIModel<ItemVerticalPositionDto> { + + private static final long serialVersionUID = 1L; + + public ItemVerticalPositionUIModel() { + super(ItemVerticalPositionDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/LightsticksColorUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/LightsticksColorUI.jaxx new file mode 100644 index 0000000..bf759c0 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/LightsticksColorUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='LightsticksColorDto' + contentTitle='{n("observe.content.title.lightsticksColors")}' + listText='{n("observe.content.list.lightsticksColor")}' + createToolTip='{n("observe.content.action.lightsticksColor.create.tip")}' + detailToolTip='{n("observe.content.action.lightsticksColor.detail.tip")}' + modifyToolTip='{n("observe.content.action.lightsticksColor.modify.tip")}' + deleteToolTip='{n("observe.content.action.lightsticksColor.delete.tip")}' + saveToolTip='{n("observe.content.action.lightsticksColor.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.LightsticksColorDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.LightsticksColorDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <LightsticksColorUIModel id='model'/> + + <!-- edit bean --> + <LightsticksColorDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/LightsticksColorUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/LightsticksColorUIModel.java new file mode 100644 index 0000000..161a027 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/LightsticksColorUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.LightsticksColorDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class LightsticksColorUIModel extends ContentReferenceUIModel<LightsticksColorDto> { + + private static final long serialVersionUID = 1L; + + public LightsticksColorUIModel() { + super(LightsticksColorDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/LightsticksTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/LightsticksTypeUI.jaxx new file mode 100644 index 0000000..b7d5fef --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/LightsticksTypeUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='LightsticksTypeDto' + contentTitle='{n("observe.content.title.lightsticksTypes")}' + listText='{n("observe.content.list.lightsticksType")}' + createToolTip='{n("observe.content.action.lightsticksType.create.tip")}' + detailToolTip='{n("observe.content.action.lightsticksType.detail.tip")}' + modifyToolTip='{n("observe.content.action.lightsticksType.modify.tip")}' + deleteToolTip='{n("observe.content.action.lightsticksType.delete.tip")}' + saveToolTip='{n("observe.content.action.lightsticksType.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.LightsticksTypeDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.LightsticksTypeDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <LightsticksTypeUIModel id='model'/> + + <!-- edit bean --> + <LightsticksTypeDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/LightsticksTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/LightsticksTypeUIModel.java new file mode 100644 index 0000000..0e8fa0e --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/LightsticksTypeUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.LightsticksTypeDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class LightsticksTypeUIModel extends ContentReferenceUIModel<LightsticksTypeDto> { + + private static final long serialVersionUID = 1L; + + public LightsticksTypeUIModel() { + super(LightsticksTypeDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/LineTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/LineTypeUI.jaxx new file mode 100644 index 0000000..ad39888 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/LineTypeUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='LineTypeDto' + contentTitle='{n("observe.content.title.lineTypes")}' + listText='{n("observe.content.list.lineType")}' + createToolTip='{n("observe.content.action.lineType.create.tip")}' + detailToolTip='{n("observe.content.action.lineType.detail.tip")}' + modifyToolTip='{n("observe.content.action.lineType.modify.tip")}' + deleteToolTip='{n("observe.content.action.lineType.delete.tip")}' + saveToolTip='{n("observe.content.action.lineType.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.LineTypeDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.LineTypeDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <LineTypeUIModel id='model'/> + + <!-- edit bean --> + <LineTypeDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/LineTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/LineTypeUIModel.java new file mode 100644 index 0000000..ecd739f --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/LineTypeUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.LineTypeDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class LineTypeUIModel extends ContentReferenceUIModel<LineTypeDto> { + + private static final long serialVersionUID = 1L; + + public LineTypeUIModel() { + super(LineTypeDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/MaturityStatusUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/MaturityStatusUI.jaxx new file mode 100644 index 0000000..a102220 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/MaturityStatusUI.jaxx @@ -0,0 +1,179 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='MaturityStatusDto' + contentTitle='{n("observe.content.title.maturityStatuss")}' + listText='{n("observe.content.list.maturityStatus")}' + createToolTip='{n("observe.content.action.maturityStatus.create.tip")}' + detailToolTip='{n("observe.content.action.maturityStatus.detail.tip")}' + modifyToolTip='{n("observe.content.action.maturityStatus.modify.tip")}' + deleteToolTip='{n("observe.content.action.maturityStatus.delete.tip")}' + saveToolTip='{n("observe.content.action.maturityStatus.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.MaturityStatusDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.MaturityStatusDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <MaturityStatusUIModel id='model'/> + + <!-- edit bean --> + <MaturityStatusDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- lowerValue / upperValue --> + <row> + <cell anchor="west"> + <JLabel id='lowerValueUpperValueLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='lowerValueUpperValuePanel' layout='{new GridLayout()}'> + <JTextField id='lowerValue' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setLowerValue(lowerValue.getText())'/> + <JTextField id='upperValue' + onKeyReleased='getBean().setUpperValue(upperValue.getText())'/> + </JPanel> + + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/MaturityStatusUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/MaturityStatusUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/MaturityStatusUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/MaturityStatusUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/MaturityStatusUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/MaturityStatusUIModel.java new file mode 100644 index 0000000..6c44e2b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/MaturityStatusUIModel.java @@ -0,0 +1,45 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.MaturityStatusDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class MaturityStatusUIModel extends ContentReferenceUIModel<MaturityStatusDto> { + + private static final long serialVersionUID = 1L; + + public MaturityStatusUIModel() { + super(MaturityStatusDto.class, + new String[]{MaturityStatusDto.PROPERTY_LOWER_VALUE, MaturityStatusDto.PROPERTY_UPPER_VALUE}, + new String[]{MaturityStatusUI.BINDING_LOWER_VALUE_TEXT, MaturityStatusUI.BINDING_UPPER_VALUE_TEXT} + ); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/MitigationTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/MitigationTypeUI.jaxx new file mode 100644 index 0000000..fdf0616 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/MitigationTypeUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='MitigationTypeDto' + contentTitle='{n("observe.content.title.mitigationTypes")}' + listText='{n("observe.content.list.mitigationType")}' + createToolTip='{n("observe.content.action.mitigationType.create.tip")}' + detailToolTip='{n("observe.content.action.mitigationType.detail.tip")}' + modifyToolTip='{n("observe.content.action.mitigationType.modify.tip")}' + deleteToolTip='{n("observe.content.action.mitigationType.delete.tip")}' + saveToolTip='{n("observe.content.action.mitigationType.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.MitigationTypeDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.MitigationTypeDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <MitigationTypeUIModel id='model'/> + + <!-- edit bean --> + <MitigationTypeDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/MitigationTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/MitigationTypeUIModel.java new file mode 100644 index 0000000..12b76b3 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/MitigationTypeUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.MitigationTypeDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class MitigationTypeUIModel extends ContentReferenceUIModel<MitigationTypeDto> { + + private static final long serialVersionUID = 1L; + + public MitigationTypeUIModel() { + super(MitigationTypeDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SensorBrandUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SensorBrandUI.jaxx new file mode 100644 index 0000000..833732b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SensorBrandUI.jaxx @@ -0,0 +1,108 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='SensorBrandDto' + contentTitle='{n("observe.content.title.sensorBrands")}' + listText='{n("observe.content.list.sensorBrand")}' + createToolTip='{n("observe.content.action.sensorBrand.create.tip")}' + detailToolTip='{n("observe.content.action.sensorBrand.detail.tip")}' + modifyToolTip='{n("observe.content.action.sensorBrand.modify.tip")}' + deleteToolTip='{n("observe.content.action.sensorBrand.delete.tip")}' + saveToolTip='{n("observe.content.action.sensorBrand.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.SensorBrandDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.SensorBrandDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <SensorBrandUIModel id='model'/> + + <!-- edit bean --> + <SensorBrandDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- brandName --> + <row> + <cell anchor="west"> + <JLabel id='brandNameLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='brandName' + onKeyReleased='getBean().setBrandName(brandName.getText())'/> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SensorBrandUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SensorBrandUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SensorBrandUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SensorBrandUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SensorBrandUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SensorBrandUIModel.java new file mode 100644 index 0000000..92ae5c5 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SensorBrandUIModel.java @@ -0,0 +1,45 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.SensorBrandDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class SensorBrandUIModel extends ContentReferenceUIModel<SensorBrandDto> { + + private static final long serialVersionUID = 1L; + + public SensorBrandUIModel() { + super(SensorBrandDto.class, + new String[]{SensorBrandDto.PROPERTY_BRAND_NAME}, + new String[]{SensorBrandUI.BINDING_BRAND_NAME_TEXT} + ); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SensorDataFormatUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SensorDataFormatUI.jaxx new file mode 100644 index 0000000..4a624c7 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SensorDataFormatUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='SensorDataFormatDto' + contentTitle='{n("observe.content.title.sensorDataFormats")}' + listText='{n("observe.content.list.sensorDataFormat")}' + createToolTip='{n("observe.content.action.sensorDataFormat.create.tip")}' + detailToolTip='{n("observe.content.action.sensorDataFormat.detail.tip")}' + modifyToolTip='{n("observe.content.action.sensorDataFormat.modify.tip")}' + deleteToolTip='{n("observe.content.action.sensorDataFormat.delete.tip")}' + saveToolTip='{n("observe.content.action.sensorDataFormat.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.SensorDataFormatDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.SensorDataFormatDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <SensorDataFormatUIModel id='model'/> + + <!-- edit bean --> + <SensorDataFormatDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SensorDataFormatUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SensorDataFormatUIModel.java new file mode 100644 index 0000000..9fd32af --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SensorDataFormatUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.SensorDataFormatDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class SensorDataFormatUIModel extends ContentReferenceUIModel<SensorDataFormatDto> { + + private static final long serialVersionUID = 1L; + + public SensorDataFormatUIModel() { + super(SensorDataFormatDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SensorTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SensorTypeUI.jaxx new file mode 100644 index 0000000..cddac28 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SensorTypeUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='SensorTypeDto' + contentTitle='{n("observe.content.title.sensorTypes")}' + listText='{n("observe.content.list.sensorType")}' + createToolTip='{n("observe.content.action.sensorType.create.tip")}' + detailToolTip='{n("observe.content.action.sensorType.detail.tip")}' + modifyToolTip='{n("observe.content.action.sensorType.modify.tip")}' + deleteToolTip='{n("observe.content.action.sensorType.delete.tip")}' + saveToolTip='{n("observe.content.action.sensorType.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.SensorTypeDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.SensorTypeDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <SensorTypeUIModel id='model'/> + + <!-- edit bean --> + <SensorTypeDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SensorTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SensorTypeUIModel.java new file mode 100644 index 0000000..4dd4f90 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SensorTypeUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.SensorTypeDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class SensorTypeUIModel extends ContentReferenceUIModel<SensorTypeDto> { + + private static final long serialVersionUID = 1L; + + public SensorTypeUIModel() { + super(SensorTypeDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SettingShapeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SettingShapeUI.jaxx new file mode 100644 index 0000000..f9fa545 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SettingShapeUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='SettingShapeDto' + contentTitle='{n("observe.content.title.settingShapes")}' + listText='{n("observe.content.list.settingShape")}' + createToolTip='{n("observe.content.action.settingShape.create.tip")}' + detailToolTip='{n("observe.content.action.settingShape.detail.tip")}' + modifyToolTip='{n("observe.content.action.settingShape.modify.tip")}' + deleteToolTip='{n("observe.content.action.settingShape.delete.tip")}' + saveToolTip='{n("observe.content.action.settingShape.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.SettingShapeDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.SettingShapeDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <SettingShapeUIModel id='model'/> + + <!-- edit bean --> + <SettingShapeDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SettingShapeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SettingShapeUIModel.java new file mode 100644 index 0000000..c8563b0 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SettingShapeUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.SettingShapeDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class SettingShapeUIModel extends ContentReferenceUIModel<SettingShapeDto> { + + private static final long serialVersionUID = 1L; + + public SettingShapeUIModel() { + super(SettingShapeDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SizeMeasureTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SizeMeasureTypeUI.jaxx new file mode 100644 index 0000000..9a9aebd --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SizeMeasureTypeUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='SizeMeasureTypeDto' + contentTitle='{n("observe.content.title.sizeMeasureTypes")}' + listText='{n("observe.content.list.sizeMeasureType")}' + createToolTip='{n("observe.content.action.sizeMeasureType.create.tip")}' + detailToolTip='{n("observe.content.action.sizeMeasureType.detail.tip")}' + modifyToolTip='{n("observe.content.action.sizeMeasureType.modify.tip")}' + deleteToolTip='{n("observe.content.action.sizeMeasureType.delete.tip")}' + saveToolTip='{n("observe.content.action.sizeMeasureType.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.SizeMeasureTypeDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.SizeMeasureTypeDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <SizeMeasureTypeUIModel id='model'/> + + <!-- edit bean --> + <SizeMeasureTypeDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SizeMeasureTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SizeMeasureTypeUIModel.java new file mode 100644 index 0000000..36f5c59 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/SizeMeasureTypeUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.SizeMeasureTypeDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class SizeMeasureTypeUIModel extends ContentReferenceUIModel<SizeMeasureTypeDto> { + + private static final long serialVersionUID = 1L; + + public SizeMeasureTypeUIModel() { + super(SizeMeasureTypeDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/StomacFullnessUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/StomacFullnessUI.jaxx new file mode 100644 index 0000000..709c937 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/StomacFullnessUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='StomacFullnessDto' + contentTitle='{n("observe.content.title.stomacFullnesss")}' + listText='{n("observe.content.list.stomacFullness")}' + createToolTip='{n("observe.content.action.stomacFullness.create.tip")}' + detailToolTip='{n("observe.content.action.stomacFullness.detail.tip")}' + modifyToolTip='{n("observe.content.action.stomacFullness.modify.tip")}' + deleteToolTip='{n("observe.content.action.stomacFullness.delete.tip")}' + saveToolTip='{n("observe.content.action.stomacFullness.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.StomacFullnessDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.StomacFullnessDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <StomacFullnessUIModel id='model'/> + + <!-- edit bean --> + <StomacFullnessDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/StomacFullnessUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/StomacFullnessUIModel.java new file mode 100644 index 0000000..153dff8 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/StomacFullnessUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.StomacFullnessDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class StomacFullnessUIModel extends ContentReferenceUIModel<StomacFullnessDto> { + + private static final long serialVersionUID = 1L; + + public StomacFullnessUIModel() { + super(StomacFullnessDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/TripTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/TripTypeUI.jaxx new file mode 100644 index 0000000..07f338e --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/TripTypeUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='TripTypeDto' + contentTitle='{n("observe.content.title.tripTypes")}' + listText='{n("observe.content.list.tripType")}' + createToolTip='{n("observe.content.action.tripType.create.tip")}' + detailToolTip='{n("observe.content.action.tripType.detail.tip")}' + modifyToolTip='{n("observe.content.action.tripType.modify.tip")}' + deleteToolTip='{n("observe.content.action.tripType.delete.tip")}' + saveToolTip='{n("observe.content.action.tripType.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.TripTypeDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.TripTypeDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <TripTypeUIModel id='model'/> + + <!-- edit bean --> + <TripTypeDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/TripTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/TripTypeUIModel.java new file mode 100644 index 0000000..0b06c90 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/TripTypeUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.TripTypeDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class TripTypeUIModel extends ContentReferenceUIModel<TripTypeDto> { + + private static final long serialVersionUID = 1L; + + public TripTypeUIModel() { + super(TripTypeDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/VesselActivityLonglineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/VesselActivityLonglineUI.jaxx new file mode 100644 index 0000000..8842a47 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/VesselActivityLonglineUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='VesselActivityLonglineDto' + contentTitle='{n("observe.content.title.vesselActivityLonglines")}' + listText='{n("observe.content.list.vesselActivityLongline")}' + createToolTip='{n("observe.content.action.vesselActivityLongline.create.tip")}' + detailToolTip='{n("observe.content.action.vesselActivityLongline.detail.tip")}' + modifyToolTip='{n("observe.content.action.vesselActivityLongline.modify.tip")}' + deleteToolTip='{n("observe.content.action.vesselActivityLongline.delete.tip")}' + saveToolTip='{n("observe.content.action.vesselActivityLongline.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.VesselActivityLonglineDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.VesselActivityLonglineDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <VesselActivityLonglineUIModel id='model'/> + + <!-- edit bean --> + <VesselActivityLonglineDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/VesselActivityLonglineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/VesselActivityLonglineUIModel.java new file mode 100644 index 0000000..4d50a33 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/VesselActivityLonglineUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.VesselActivityLonglineDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class VesselActivityLonglineUIModel extends ContentReferenceUIModel<VesselActivityLonglineDto> { + + private static final long serialVersionUID = 1L; + + public VesselActivityLonglineUIModel() { + super(VesselActivityLonglineDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/WeightMeasureTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/WeightMeasureTypeUI.jaxx new file mode 100644 index 0000000..c2ca11c --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/WeightMeasureTypeUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='WeightMeasureTypeDto' + contentTitle='{n("observe.content.title.weightMeasureTypes")}' + listText='{n("observe.content.list.weightMeasureType")}' + createToolTip='{n("observe.content.action.weightMeasureType.create.tip")}' + detailToolTip='{n("observe.content.action.weightMeasureType.detail.tip")}' + modifyToolTip='{n("observe.content.action.weightMeasureType.modify.tip")}' + deleteToolTip='{n("observe.content.action.weightMeasureType.delete.tip")}' + saveToolTip='{n("observe.content.action.weightMeasureType.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.longline.WeightMeasureTypeDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.longline.WeightMeasureTypeDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <WeightMeasureTypeUIModel id='model'/> + + <!-- edit bean --> + <WeightMeasureTypeDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/WeightMeasureTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/WeightMeasureTypeUIModel.java new file mode 100644 index 0000000..4994128 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/longline/WeightMeasureTypeUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.longline.WeightMeasureTypeDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class WeightMeasureTypeUIModel extends ContentReferenceUIModel<WeightMeasureTypeDto> { + + private static final long serialVersionUID = 1L; + + public WeightMeasureTypeUIModel() { + super(WeightMeasureTypeDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/DetectionModeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/DetectionModeUI.jaxx new file mode 100644 index 0000000..5680dac --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/DetectionModeUI.jaxx @@ -0,0 +1,164 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='DetectionModeDto' + contentTitle='{n("observe.content.title.detectionModes")}' + listText='{n("observe.content.list.detectionMode")}' + createToolTip='{n("observe.content.action.detectionMode.create.tip")}' + detailToolTip='{n("observe.content.action.detectionMode.detail.tip")}' + modifyToolTip='{n("observe.content.action.detectionMode.modify.tip")}' + deleteToolTip='{n("observe.content.action.detectionMode.delete.tip")}' + saveToolTip='{n("observe.content.action.detectionMode.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.seine.DetectionModeDto + + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.seine.DetectionModeDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <DetectionModeUIModel id='model'/> + + <!-- edit bean --> + <DetectionModeDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/DetectionModeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/DetectionModeUIModel.java new file mode 100644 index 0000000..a03e544 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/DetectionModeUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.seine.DetectionModeDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class DetectionModeUIModel extends ContentReferenceUIModel<DetectionModeDto> { + + private static final long serialVersionUID = 1L; + + public DetectionModeUIModel() { + super(DetectionModeDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObjectFateUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObjectFateUI.jaxx new file mode 100644 index 0000000..fb51f8d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObjectFateUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='ObjectFateDto' + contentTitle='{n("observe.content.title.objectFates")}' + listText='{n("observe.content.list.objectFate")}' + createToolTip='{n("observe.content.action.objectFate.create.tip")}' + detailToolTip='{n("observe.content.action.objectFate.detail.tip")}' + modifyToolTip='{n("observe.content.action.objectFate.modify.tip")}' + deleteToolTip='{n("observe.content.action.objectFate.delete.tip")}' + saveToolTip='{n("observe.content.action.objectFate.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.seine.ObjectFateDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.seine.ObjectFateDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <ObjectFateUIModel id='model'/> + + <!-- edit bean --> + <ObjectFateDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObjectFateUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObjectFateUIModel.java new file mode 100644 index 0000000..5469867 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObjectFateUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.seine.ObjectFateDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ObjectFateUIModel extends ContentReferenceUIModel<ObjectFateDto> { + + private static final long serialVersionUID = 1L; + + public ObjectFateUIModel() { + super(ObjectFateDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObjectOperationUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObjectOperationUI.jaxx new file mode 100644 index 0000000..5f4d6c6 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObjectOperationUI.jaxx @@ -0,0 +1,164 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='ObjectOperationDto' + contentTitle='{n("observe.content.title.objectOperations")}' + listText='{n("observe.content.list.objectOperation")}' + createToolTip='{n("observe.content.action.objectOperation.create.tip")}' + detailToolTip='{n("observe.content.action.objectOperation.detail.tip")}' + modifyToolTip='{n("observe.content.action.objectOperation.modify.tip")}' + deleteToolTip='{n("observe.content.action.objectOperation.delete.tip")}' + saveToolTip='{n("observe.content.action.objectOperation.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.seine.ObjectOperationDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.seine.ObjectOperationDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <ObjectOperationUIModel id='model'/> + + <!-- edit bean --> + <ObjectOperationDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' + onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObjectOperationUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObjectOperationUIModel.java new file mode 100644 index 0000000..8630911 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObjectOperationUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.seine.ObjectOperationDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ObjectOperationUIModel extends ContentReferenceUIModel<ObjectOperationDto> { + + private static final long serialVersionUID = 1L; + + public ObjectOperationUIModel() { + super(ObjectOperationDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObjectTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObjectTypeUI.jaxx new file mode 100644 index 0000000..231514c --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObjectTypeUI.jaxx @@ -0,0 +1,164 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='ObjectTypeDto' + contentTitle='{n("observe.content.title.objectTypes")}' + listText='{n("observe.content.list.objectType")}' + createToolTip='{n("observe.content.action.objectType.create.tip")}' + detailToolTip='{n("observe.content.action.objectType.detail.tip")}' + modifyToolTip='{n("observe.content.action.objectType.modify.tip")}' + deleteToolTip='{n("observe.content.action.objectType.delete.tip")}' + saveToolTip='{n("observe.content.action.objectType.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.seine.ObjectTypeDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.seine.ObjectTypeDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <ObjectTypeUIModel id='model'/> + + <!-- edit bean --> + <ObjectTypeDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObjectTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObjectTypeUIModel.java new file mode 100644 index 0000000..0ea5bd1 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObjectTypeUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.seine.ObjectTypeDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ObjectTypeUIModel extends ContentReferenceUIModel<ObjectTypeDto> { + + private static final long serialVersionUID = 1L; + + public ObjectTypeUIModel() { + super(ObjectTypeDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObservedSystemUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObservedSystemUI.jaxx new file mode 100644 index 0000000..d484625 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObservedSystemUI.jaxx @@ -0,0 +1,176 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='ObservedSystemDto' + contentTitle='{n("observe.content.title.observedSystems")}' + listText='{n("observe.content.list.observedSystem")}' + createToolTip='{n("observe.content.action.observedSystem.create.tip")}' + detailToolTip='{n("observe.content.action.observedSystem.detail.tip")}' + modifyToolTip='{n("observe.content.action.observedSystem.modify.tip")}' + deleteToolTip='{n("observe.content.action.observedSystem.delete.tip")}' + saveToolTip='{n("observe.content.action.observedSystem.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.constants.seine.SchoolType + fr.ird.observe.services.dto.referential.seine.ObservedSystemDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.seine.ObservedSystemDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <fr.ird.observe.application.swing.ui.content.ref.impl.seine.ObservedSystemUIModel id='model'/> + + <!-- edit bean --> + <ObservedSystemDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- schoolType --> + <row> + <cell anchor='west'> + <JLabel id='schoolTypeLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <EnumEditor id='schoolType' constructorParams='SchoolType.class' + genericType='SchoolType' + onItemStateChanged='getBean().setSchoolType((SchoolType)schoolType.getSelectedItem())'/> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObservedSystemUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObservedSystemUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObservedSystemUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObservedSystemUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObservedSystemUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObservedSystemUIModel.java new file mode 100644 index 0000000..4858b82 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ObservedSystemUIModel.java @@ -0,0 +1,45 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.seine.ObservedSystemDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ObservedSystemUIModel extends ContentReferenceUIModel<ObservedSystemDto> { + + private static final long serialVersionUID = 1L; + + public ObservedSystemUIModel() { + super(ObservedSystemDto.class, + new String[]{ObservedSystemDto.PROPERTY_SCHOOL_TYPE}, + new String[]{ObservedSystemUI.BINDING_SCHOOL_TYPE_SELECTED_ITEM} + ); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ReasonForDiscardUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ReasonForDiscardUI.jaxx new file mode 100644 index 0000000..854578e --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ReasonForDiscardUI.jaxx @@ -0,0 +1,164 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='ReasonForDiscardDto' + contentTitle='{n("observe.content.title.reasonForDiscards")}' + listText='{n("observe.content.list.reasonForDiscard")}' + createToolTip='{n("observe.content.action.reasonForDiscard.create.tip")}' + detailToolTip='{n("observe.content.action.reasonForDiscard.detail.tip")}' + modifyToolTip='{n("observe.content.action.reasonForDiscard.modify.tip")}' + deleteToolTip='{n("observe.content.action.reasonForDiscard.delete.tip")}' + saveToolTip='{n("observe.content.action.reasonForDiscard.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.seine.ReasonForDiscardDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.seine.ReasonForDiscardDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <ReasonForDiscardUIModel id='model'/> + + <!-- edit bean --> + <ReasonForDiscardDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' + onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ReasonForDiscardUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ReasonForDiscardUIModel.java new file mode 100644 index 0000000..fba5168 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ReasonForDiscardUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.seine.ReasonForDiscardDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ReasonForDiscardUIModel extends ContentReferenceUIModel<ReasonForDiscardDto> { + + private static final long serialVersionUID = 1L; + + public ReasonForDiscardUIModel() { + super(ReasonForDiscardDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ReasonForNoFishingUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ReasonForNoFishingUI.jaxx new file mode 100644 index 0000000..4438508 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ReasonForNoFishingUI.jaxx @@ -0,0 +1,164 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='ReasonForNoFishingDto' + contentTitle='{n("observe.content.title.reasonForNoFishings")}' + listText='{n("observe.content.list.reasonForNoFishing")}' + createToolTip='{n("observe.content.action.reasonForNoFishing.create.tip")}' + detailToolTip='{n("observe.content.action.reasonForNoFishing.detail.tip")}' + modifyToolTip='{n("observe.content.action.reasonForNoFishing.modify.tip")}' + deleteToolTip='{n("observe.content.action.reasonForNoFishing.delete.tip")}' + saveToolTip='{n("observe.content.action.reasonForNoFishing.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.seine.ReasonForNoFishingDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' + autoField='true' + beanClass='fr.ird.observe.services.dto.referential.seine.ReasonForNoFishingDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <ReasonForNoFishingUIModel id='model'/> + + <!-- edit bean --> + <ReasonForNoFishingDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ReasonForNoFishingUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ReasonForNoFishingUIModel.java new file mode 100644 index 0000000..14b8abb --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ReasonForNoFishingUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.seine.ReasonForNoFishingDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ReasonForNoFishingUIModel extends ContentReferenceUIModel<ReasonForNoFishingDto> { + + private static final long serialVersionUID = 1L; + + public ReasonForNoFishingUIModel() { + super(ReasonForNoFishingDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ReasonForNullSetUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ReasonForNullSetUI.jaxx new file mode 100644 index 0000000..3990d37 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ReasonForNullSetUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='ReasonForNullSetDto' + contentTitle='{n("observe.content.title.reasonForNullSets")}' + listText='{n("observe.content.list.reasonForNullSet")}' + createToolTip='{n("observe.content.action.reasonForNullSet.create.tip")}' + detailToolTip='{n("observe.content.action.reasonForNullSet.detail.tip")}' + modifyToolTip='{n("observe.content.action.reasonForNullSet.modify.tip")}' + deleteToolTip='{n("observe.content.action.reasonForNullSet.delete.tip")}' + saveToolTip='{n("observe.content.action.reasonForNullSet.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.seine.ReasonForNullSetDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.seine.ReasonForNullSetDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <ReasonForNullSetUIModel id='model'/> + + <!-- edit bean --> + <ReasonForNullSetDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ReasonForNullSetUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ReasonForNullSetUIModel.java new file mode 100644 index 0000000..8d7c860 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/ReasonForNullSetUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.seine.ReasonForNullSetDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ReasonForNullSetUIModel extends ContentReferenceUIModel<ReasonForNullSetDto> { + + private static final long serialVersionUID = 1L; + + public ReasonForNullSetUIModel() { + super(ReasonForNullSetDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/SpeciesFateUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/SpeciesFateUI.jaxx new file mode 100644 index 0000000..5c8929a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/SpeciesFateUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='SpeciesFateDto' + contentTitle='{n("observe.content.title.speciesFates")}' + listText='{n("observe.content.list.speciesFate")}' + createToolTip='{n("observe.content.action.speciesFate.create.tip")}' + detailToolTip='{n("observe.content.action.speciesFate.detail.tip")}' + modifyToolTip='{n("observe.content.action.speciesFate.modify.tip")}' + deleteToolTip='{n("observe.content.action.speciesFate.delete.tip")}' + saveToolTip='{n("observe.content.action.speciesFate.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.seine.SpeciesFateDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.seine.SpeciesFateDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <SpeciesFateUIModel id='model'/> + + <!-- edit bean --> + <SpeciesFateDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/SpeciesFateUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/SpeciesFateUIModel.java new file mode 100644 index 0000000..0e05ecf --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/SpeciesFateUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.seine.SpeciesFateDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class SpeciesFateUIModel extends ContentReferenceUIModel<SpeciesFateDto> { + + private static final long serialVersionUID = 1L; + + public SpeciesFateUIModel() { + super(SpeciesFateDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/SpeciesStatusUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/SpeciesStatusUI.jaxx new file mode 100644 index 0000000..cadf0b6 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/SpeciesStatusUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='SpeciesStatusDto' + contentTitle='{n("observe.content.title.speciesStatuss")}' + listText='{n("observe.content.list.speciesStatus")}' + createToolTip='{n("observe.content.action.speciesStatus.create.tip")}' + detailToolTip='{n("observe.content.action.speciesStatus.detail.tip")}' + modifyToolTip='{n("observe.content.action.speciesStatus.modify.tip")}' + deleteToolTip='{n("observe.content.action.speciesStatus.delete.tip")}' + saveToolTip='{n("observe.content.action.speciesStatus.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.seine.SpeciesStatusDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.seine.SpeciesStatusDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <SpeciesStatusUIModel id='model'/> + + <!-- edit bean --> + <SpeciesStatusDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/SpeciesStatusUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/SpeciesStatusUIModel.java new file mode 100644 index 0000000..b44b083 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/SpeciesStatusUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.seine.SpeciesStatusDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class SpeciesStatusUIModel extends ContentReferenceUIModel<SpeciesStatusDto> { + + private static final long serialVersionUID = 1L; + + public SpeciesStatusUIModel() { + super(SpeciesStatusDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/SurroundingActivityUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/SurroundingActivityUI.jaxx new file mode 100644 index 0000000..73adc10 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/SurroundingActivityUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='SurroundingActivityDto' + contentTitle='{n("observe.content.title.surroundingActivitys")}' + listText='{n("observe.content.list.surroundingActivity")}' + createToolTip='{n("observe.content.action.surroundingActivity.create.tip")}' + detailToolTip='{n("observe.content.action.surroundingActivity.detail.tip")}' + modifyToolTip='{n("observe.content.action.surroundingActivity.modify.tip")}' + deleteToolTip='{n("observe.content.action.surroundingActivity.delete.tip")}' + saveToolTip='{n("observe.content.action.surroundingActivity.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.seine.SurroundingActivityDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.seine.SurroundingActivityDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <SurroundingActivityUIModel id='model'/> + + <!-- edit bean --> + <SurroundingActivityDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/SurroundingActivityUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/SurroundingActivityUIModel.java new file mode 100644 index 0000000..d5b24fc --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/SurroundingActivityUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.seine.SurroundingActivityDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class SurroundingActivityUIModel extends ContentReferenceUIModel<SurroundingActivityDto> { + + private static final long serialVersionUID = 1L; + + public SurroundingActivityUIModel() { + super(SurroundingActivityDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/TransmittingBuoyOperationUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/TransmittingBuoyOperationUI.jaxx new file mode 100644 index 0000000..24da6ed --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/TransmittingBuoyOperationUI.jaxx @@ -0,0 +1,164 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='TransmittingBuoyOperationDto' + contentTitle='{n("observe.content.title.transmittingBuoyOperations")}' + listText='{n("observe.content.list.operation")}' + createToolTip='{n("observe.content.action.transmittingBuoyOperation.create.tip")}' + detailToolTip='{n("observe.content.action.transmittingBuoyOperation.detail.tip")}' + modifyToolTip='{n("observe.content.action.transmittingBuoyOperation.modify.tip")}' + deleteToolTip='{n("observe.content.action.transmittingBuoyOperation.delete.tip")}' + saveToolTip='{n("observe.content.action.transmittingBuoyOperation.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.seine.TransmittingBuoyOperationDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.seine.TransmittingBuoyOperationDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <fr.ird.observe.application.swing.ui.content.ref.impl.seine.TransmittingBuoyOperationUIModel id='model'/> + + <!-- edit bean --> + <TransmittingBuoyOperationDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' + onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/TransmittingBuoyOperationUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/TransmittingBuoyOperationUIModel.java new file mode 100644 index 0000000..feb56fd --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/TransmittingBuoyOperationUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.seine.TransmittingBuoyOperationDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class TransmittingBuoyOperationUIModel extends ContentReferenceUIModel<TransmittingBuoyOperationDto> { + + private static final long serialVersionUID = 1L; + + public TransmittingBuoyOperationUIModel() { + super(TransmittingBuoyOperationDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/TransmittingBuoyTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/TransmittingBuoyTypeUI.jaxx new file mode 100644 index 0000000..05433f9 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/TransmittingBuoyTypeUI.jaxx @@ -0,0 +1,164 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='TransmittingBuoyTypeDto' + contentTitle='{n("observe.content.title.transmittingBuoyTypes")}' + listText='{n("observe.content.list.transmittingBuoyType")}' + createToolTip='{n("observe.content.action.transmittingBuoyType.create.tip")}' + detailToolTip='{n("observe.content.action.transmittingBuoyType.detail.tip")}' + modifyToolTip='{n("observe.content.action.transmittingBuoyType.modify.tip")}' + deleteToolTip='{n("observe.content.action.transmittingBuoyType.delete.tip")}' + saveToolTip='{n("observe.content.action.transmittingBuoyType.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.seine.TransmittingBuoyTypeDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.seine.TransmittingBuoyTypeDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <TransmittingBuoyTypeUIModel id='model'/> + + <!-- edit bean --> + <TransmittingBuoyTypeDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/TransmittingBuoyTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/TransmittingBuoyTypeUIModel.java new file mode 100644 index 0000000..6503f8a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/TransmittingBuoyTypeUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.seine.TransmittingBuoyTypeDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class TransmittingBuoyTypeUIModel extends ContentReferenceUIModel<TransmittingBuoyTypeDto> { + + private static final long serialVersionUID = 1L; + + public TransmittingBuoyTypeUIModel() { + super(TransmittingBuoyTypeDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/VesselActivitySeineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/VesselActivitySeineUI.jaxx new file mode 100644 index 0000000..05ca454 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/VesselActivitySeineUI.jaxx @@ -0,0 +1,165 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='VesselActivitySeineDto' + contentTitle='{n("observe.content.title.vesselActivitySeines")}' + listText='{n("observe.content.list.vesselActivitySeine")}' + createToolTip='{n("observe.content.action.vesselActivitySeine.create.tip")}' + detailToolTip='{n("observe.content.action.vesselActivitySeine.detail.tip")}' + modifyToolTip='{n("observe.content.action.vesselActivitySeine.modify.tip")}' + deleteToolTip='{n("observe.content.action.vesselActivitySeine.delete.tip")}' + saveToolTip='{n("observe.content.action.vesselActivitySeine.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.seine.VesselActivitySeineDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' + autoField='true' + beanClass='fr.ird.observe.services.dto.referential.seine.VesselActivitySeineDto' + errorTableModel='{getErrorTableModel()}' + context='ui-create'/> + + <!-- model --> + <VesselActivitySeineUIModel id='model'/> + + <!-- edit bean --> + <VesselActivitySeineDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel' styleClass='unique'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' styleClass='unique' + onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/VesselActivitySeineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/VesselActivitySeineUIModel.java new file mode 100644 index 0000000..4122ca5 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/VesselActivitySeineUIModel.java @@ -0,0 +1,42 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.seine.VesselActivitySeineDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class VesselActivitySeineUIModel extends ContentReferenceUIModel<VesselActivitySeineDto> { + + private static final long serialVersionUID = 1L; + + public VesselActivitySeineUIModel() { + super(VesselActivitySeineDto.class); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/WeightCategoryUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/WeightCategoryUI.jaxx new file mode 100644 index 0000000..a2276dc --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/WeightCategoryUI.jaxx @@ -0,0 +1,197 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='WeightCategoryDto' + contentTitle='{n("observe.content.title.weightCategory")}' + listText='{n("observe.content.list.weightCategory")}' + createToolTip='{n("observe.content.action.weightCategory.create.tip")}' + detailToolTip='{n("observe.content.action.weightCategory.detail.tip")}' + modifyToolTip='{n("observe.content.action.weightCategory.modify.tip")}' + deleteToolTip='{n("observe.content.action.weightCategory.delete.tip")}' + saveToolTip='{n("observe.content.action.weightCategory.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.seine.WeightCategoryDto + fr.ird.observe.services.dto.referential.SpeciesDto + fr.ird.observe.application.swing.ui.UIHelper + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + jaxx.runtime.swing.editor.bean.BeanComboBox + + javax.swing.JScrollPane + javax.swing.JTable + javax.swing.table.TableCellRenderer + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.seine.WeightCategoryDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <WeightCategoryUIModel id='model'/> + + <!-- edit bean --> + <WeightCategoryDto id='bean'/> + + <script><![CDATA[ + +@Override +public void decorateUniqueKeyTable(JTable table, + TableCellRenderer renderer, + JScrollPane pane) { + + UIHelper.fixTableColumnWidth(table, 0, 240); + UIHelper.fixTableColumnWidth(table, 1, 60); + UIHelper.fixTableColumnWidth(table, 2, 200); + table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); +} +]]></script> + + <Table id='editTable'> + + <!-- species --> + <row> + <cell anchor='west'> + <JLabel id='speciesLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <BeanComboBox id='species' constructorParams='this' + genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class'/> + </cell> + </row> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/WeightCategoryUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/WeightCategoryUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/WeightCategoryUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/WeightCategoryUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/WeightCategoryUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/WeightCategoryUIModel.java new file mode 100644 index 0000000..28a6bb0 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/WeightCategoryUIModel.java @@ -0,0 +1,46 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.seine.WeightCategoryDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class WeightCategoryUIModel extends ContentReferenceUIModel<WeightCategoryDto> { + + private static final long serialVersionUID = 1L; + + public WeightCategoryUIModel() { + super(WeightCategoryDto.class, + new String[]{WeightCategoryDto.PROPERTY_CODE, WeightCategoryDto.PROPERTY_SPECIES}, + new String[]{WeightCategoryDto.PROPERTY_CODE, WeightCategoryDto.PROPERTY_SPECIES}, + new String[]{WeightCategoryUI.BINDING_CODE_TEXT, WeightCategoryUI.BINDING_SPECIES_SELECTED_ITEM} + ); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/WindUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/WindUI.jaxx new file mode 100644 index 0000000..4fe6220 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/WindUI.jaxx @@ -0,0 +1,186 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI + superGenericType='WindDto' + contentTitle='{n("observe.content.title.windSpeeds")}' + listText='{n("observe.content.list.wind")}' + createToolTip='{n("observe.content.action.wind.create.tip")}' + detailToolTip='{n("observe.content.action.wind.detail.tip")}' + modifyToolTip='{n("observe.content.action.wind.modify.tip")}' + deleteToolTip='{n("observe.content.action.wind.delete.tip")}' + saveToolTip='{n("observe.content.action.wind.save.tip")}' + + > + + <style source="../ReferenceEntity.jcss"/> + <style source="../I18nReferenceEntity.jcss"/> + + <import> + fr.ird.observe.services.dto.constants.ReferenceStatus + fr.ird.observe.services.dto.referential.seine.WindDto + fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- validator --> + <BeanValidator id='validator' autoField='true' + beanClass='fr.ird.observe.services.dto.referential.seine.WindDto' + context='ui-create' + errorTableModel='{getErrorTableModel()}'/> + + <!-- model --> + <WindUIModel id='model'/> + + <!-- edit bean --> + <WindDto id='bean'/> + + <Table id='editTable'> + + <!-- uri --> + <row> + <cell anchor="west"> + <JLabel id='uriLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> + </cell> + </row> + + <!-- code / status --> + <row> + <cell anchor="west"> + <JLabel id='codeStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> + <JTextField id='code' constraints='BorderLayout.WEST' + onKeyReleased='getBean().setCode(code.getText())'/> + <EnumEditor id='status' constraints='BorderLayout.CENTER' + constructorParams='ReferenceStatus.class' + genericType='ReferenceStatus' + onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> + </JPanel> + </cell> + </row> + + <!-- speedRange --> + <row> + <cell anchor="west"> + <JLabel id='speedRangeLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='speedRange' + onKeyReleased='getBean().setSpeedRange(speedRange.getText())'/> + </cell> + </row> + + <!-- waveHeight --> + <row> + <cell anchor="west"> + <JLabel id='waveHeightLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='waveHeight' + onKeyReleased='getBean().setWaveHeight(waveHeight.getText())'/> + </cell> + </row> + + <!-- needComment --> + <row> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <JCheckBox id='needComment' + onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> + </cell> + </row> + </Table> + + <Table id='editI18nTable'> + <row> + <cell anchor="west"> + <JLabel id='label1Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label1' + onKeyReleased='getBean().setLabel1(label1.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label2Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label2' + onKeyReleased='getBean().setLabel2(label2.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label3Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label3' + onKeyReleased='getBean().setLabel3(label3.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label4Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label4' + onKeyReleased='getBean().setLabel4(label4.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label5Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label5' + onKeyReleased='getBean().setLabel5(label5.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label6Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label6' + onKeyReleased='getBean().setLabel6(label6.getText())'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='label7Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label7' + onKeyReleased='getBean().setLabel7(label7.getText())'/> + </cell> + <cell anchor="west"> + <JLabel id='label8Label'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JTextField id='label8' + onKeyReleased='getBean().setLabel8(label8.getText())'/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/WindUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/WindUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/WindUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/WindUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/WindUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/WindUIModel.java new file mode 100644 index 0000000..bcfdba5 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/impl/seine/WindUIModel.java @@ -0,0 +1,45 @@ +package fr.ird.observe.application.swing.ui.content.ref.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.seine.WindDto; +import fr.ird.observe.application.swing.ui.content.ref.ContentReferenceUIModel; + +/** + * Created on 9/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class WindUIModel extends ContentReferenceUIModel<WindDto> { + + private static final long serialVersionUID = 1L; + + public WindUIModel() { + super(WindDto.class, + new String[]{WindDto.PROPERTY_SPEED_RANGE, WindDto.PROPERTY_WAVE_HEIGHT}, + new String[]{WindUI.BINDING_SPEED_RANGE_TEXT, WindUI.BINDING_WAVE_HEIGHT_TEXT} + ); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/package.html b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/package.html similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/package.html rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/ref/package.html diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/CommonTable.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/CommonTable.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/CommonTable.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/CommonTable.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableMeta.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableMeta.java new file mode 100644 index 0000000..06f1ccf --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableMeta.java @@ -0,0 +1,158 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.table; + +import com.google.common.base.Preconditions; +import com.google.common.collect.Iterables; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.util.ObjectUtil; +import org.nuiton.util.beans.BeanUtil; + +import java.beans.PropertyDescriptor; +import java.io.Serializable; +import java.util.Set; +import java.util.function.Predicate; + +/** + * La définition d'une méta donnée d'un tableau, i.e la définition d'une + * colonne. + * + * @param <B> le type de la donnée encapsulée par la colonne + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class ContentTableMeta<B> implements Serializable { + + /** Logger. */ + private static final Log log = LogFactory.getLog(ContentTableMeta.class); + + private static final long serialVersionUID = 1L; + + /** le lastName de la meta (c'est le nom de la colonne) */ + protected final String name; + + /** le type de la meta (c'estle type de la colonne) */ + protected final Class<B> klass; + + /** + * un drapeau pour savoir si on peut modifier cette méta lorsque l'objet + * encapsulé existe déjà en base (pour pouvoir gérer les clefs métiers non + * mutable) + */ + protected final boolean unmodiableWhenExisting; + + /** + * le descripteur de la méta (pour pouvoir récupérer et modifier la + * colonne) + */ + protected transient PropertyDescriptor propertyDescriptor; + + public ContentTableMeta(Class<B> klass, + String name, + boolean unmodiableWhenExisting) { + this.name = name; + this.klass = klass; + this.unmodiableWhenExisting = unmodiableWhenExisting; + if (log.isDebugEnabled()) { + log.debug(this + " : " + name + " : " + getType().getName()); + } + } + + /** @return the name of this meta (will be used as columnName) */ + public String getName() { + return name; + } + + /** @return the type of this meta (will be used as columnClass) */ + public Class<?> getType() { + return getPropertyDescriptor().getPropertyType(); + } + + /** + * @param model le modele qui contient la meta + * @param bean the bean to request + * @param row the current row + * @return the value of the property of the given bean + */ + public Object getValue(ContentTableModel<?, ?> model, + B bean, + int row) { + try { + return getPropertyDescriptor().getReadMethod().invoke(bean); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + /** + * @param model the currentmodel + * @param bean the bean to modifiy + * @param aValue the new value to set + * @param row the current row modified + * @return {@code true} if bean data has changed, {@code false} + * otherwise + */ + public boolean setValue(ContentTableModel<?, ?> model, + B bean, + Object aValue, + int row) { + Object oldValue = getValue(model, bean, row); + /*try { + getPropertyDescriptor().getWriteMethod().invoke(bean, aValue); + } catch (Exception e) { + throw new RuntimeException(e); + }*/ + return oldValue == null && aValue != null || + oldValue != null && !oldValue.equals(aValue); + } + + /** + * Test if the property of a given bean is null. + * + * @param model le modele qui contient la meta + * @param bean the current bean to test + * @param row the current row + * @return {@code true} if data is null for the given meta, + * {@code false} otherwise. + */ + public boolean isNullValue(ContentTableModel<?, ?> model, + B bean, + int row) { + Object value = getValue(model, bean, row); + return ObjectUtil.isNullValue(value); + } + + /** @return the property descriptor of the meta */ + protected PropertyDescriptor getPropertyDescriptor() { + if (propertyDescriptor == null) { + Predicate<PropertyDescriptor> predicate = + input -> BeanUtil.IS_READ_DESCRIPTOR.apply(input) + && name.equals(input.getName()); + Set<PropertyDescriptor> descriptors = BeanUtil.getDescriptors(klass, predicate::test); + Preconditions.checkState(!descriptors.isEmpty(), + "could not find readable property " + name + " for bean " + klass); + propertyDescriptor = Iterables.get(descriptors, 0); + } + return propertyDescriptor; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableModel.java new file mode 100644 index 0000000..620168b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableModel.java @@ -0,0 +1,748 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.table; + +import fr.ird.observe.services.dto.AbstractObserveDto; +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.application.swing.ui.UIHelper; +import jaxx.runtime.validator.swing.SwingValidator; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.i18n.I18n; + +import javax.swing.JOptionPane; +import javax.swing.table.AbstractTableModel; +import java.beans.PropertyChangeListener; +import java.beans.PropertyChangeSupport; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; + +/** + * Le modele d'un tableau où les données sont une association sur une entité. + * + * Ce modèle n'est pas éditable. + * + * Les données sont stockées dans la liste {@link #data} qui sert de cache, car + * on veut pouvoir valider en temps réel l'entité principale (celle qui contient + * l'association), il faut donc toujours que les données de l'association soient + * synchronisées. L'utilisation d'un cache est cependant requise car sinon cela + * est trop couteux (notamment pour le rendu du tableau...). + * + * Le cache sera recalculé à chaque fois que l'on modifie la structure des + * données de l'association (ajout d'une entrée, suppression d'une entrée). + * + * De plus le cache permet de travailler sur une liste (alors que l'association + * n'est peut-être pas ordonnée) et cela facilite les opérations sur les données + * du tableau). + * + * Le modèle définit plusieurs propriétés : <ul> <li>{@link #editable} : un + * drapeau pour savoir si le modèle est editable</li> <li>{@link #modified} : un + * drapeau pour savoir si le modèle est modifié</li> <li>{@link #create} : un + * drapeau pour savoir si l'entrée en cours d'édition est une nouvelle + * entrée</li> <li>{@link #selectedRow} : l'index de l'entrée sélectionnée</li> + * </ul> FIXME a finir... + * + * @param <P> le type de l'entité qui contient la liste + * @param <B> le type de l'entite d'une entrée de la liste + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public abstract class ContentTableModel<P extends IdDto, B extends IdDto> extends AbstractTableModel { + + /** Le nom de la propriété de la ligne en cours d'édition */ + public static final String SELECTED_ROW_PROPERTY = "selectedRow"; + + /** Le nom de la propriété modifié du modèle */ + public static final String MODIFIED_PROPERTY = "modified"; + + /** Le nom de la propriété pour editer le modele */ + public static final String EDITABLE_PROPERTY = "editable"; + + /** + * Le nom de la propriété pour indiquer que l'entrée en cours d'édition est + * en mode création + */ + public static final String CREATE_PROPERTY = "create"; + + /** Le nom de la propriété pour savoir si le modèle est vide */ + public static final String EMPTY_PROPERTY = "empty"; + + private static final long serialVersionUID = 1L; + + /** Logger */ + private static final Log log = LogFactory.getLog(ContentTableModel.class); + + /** la liste des métas du modèle */ + protected final List<ContentTableMeta<B>> metas; + + /** pour la propagation des modifications d'états */ + protected final PropertyChangeSupport pcs = new PropertyChangeSupport(this); + + /** la liste des données du modèle */ + protected List<B> data = new ArrayList<>(); + + /** un drapeau pour savoir si le modèle a été modifié */ + protected boolean modified; + + /** un drapeau pour savoir si le modèle est éditable */ + protected boolean editable; + + /** un drapeau pour savoir si on edite une nouvelle entree */ + protected boolean create; + + /** + * un drapeau pour modifier la selection de la ligne en cours sans aucune + * verification. + */ + protected boolean valueAdjusting; + + /** l'entrée sélectionnée (-1 quand pas de sélection) */ + protected int selectedRow = -1; + + /** un message supplémentaire à afficher lors d'une suppression de ligne */ + protected String deleteExtraMessage; + + /** un drapeau pour savoir si le modèle a ete initialisé. */ + private boolean init; + + private ObserveContentTableUI<P, B> context; + + @SuppressWarnings("unchecked") + public ContentTableModel(ObserveContentTableUI<P, B> context, + List<ContentTableMeta<B>> metas) { + if (CollectionUtils.isEmpty(metas)) { + throw new NullPointerException("meta parameter can not be null, nor empty"); + } + + this.context = context; + this.metas = Collections.unmodifiableList(metas); + } + + public static <D extends AbstractObserveDto> ContentTableMeta<D> newTableMeta( + Class<D> childType, + String property, + boolean unmodiableWhenExisting) { + + return new ContentTableMeta<>(childType, + property, unmodiableWhenExisting); + } + + /** + * Positionne un bean dans le modèle. + * + * Cela va initialiser la liste à utiliser. + */ + public void attachModel() { + // pas de ligne selectionne + setSelectedRow(-1); + + // pas en mode creation + setCreate(false); + + setInit(true); + + updateEmpty(); + + if (log.isDebugEnabled()) { + log.debug("editable : " + isEditable()); + log.debug("size : " + getRowCount()); + } + + // notify listeners + fireTableDataChanged(); + } + + public void dettachModel() { + setModified(false); + int size = getRowCount(); + // on indique que le modele n'est plus lie au bean + // cela permet de ne plus charger l'association dans le cache + setInit(false); + if (size > 0) { + // il y avait des données que l'on a supprimé + fireTableRowsDeleted(0, size - 1); + updateEmpty(); + } + setSelectedRow(-1); + setCreate(false); + } + + /** Permet l'ajout d'une nouvelle entrée à editer */ + public void addNewEntry() { + ensureEditable(); + + if (getSelectedRow() > -1) { + // il y avait une ligne precedemment selectionnee, + // on doit verifier que l'on peut changer d'entree + if (!isCanQuitEditingRow()) { + // on ne peut pas quitter la ligne en cours d'édition + // on annule donc l'opération + return; + } + } + + // on est autorise a ajouter une nouvelle entrée + + int row = getRowCount(); + + B bean = null; + try { + bean = getModel().newTableEditBean(); + } catch (Exception e) { + UIHelper.handlingError(e); + } + data.add(bean); + + updateBeanList(false); + + fireTableRowsInserted(row, row); + updateEmpty(); + + // on est en mode creation + setCreate(true); + + // la nouvelle ligne est celle en cours d'edition + changeSelectedRow(row); + } + + protected ContentTableUIModel<P, B> getModel() { + return getHandler().getModel(); + } + + public void doRemoveRow(int rowToDelete, boolean force) { + B bean = getValueAt(rowToDelete); + ContentTableMeta<B> meta = getColumnMeta(getColumnCount() - 1); + + if (force || UIHelper.confirmForEntityDelete(null, meta.klass, bean, deleteExtraMessage)) { + // delete row + removeRow(rowToDelete); + rowToDelete--; + + // on veut selectionner la ligne precedente si elle existe + // ou bien la meme ligne (si on etait sur la premiere ligne) + + + // on force toujours le passage sur la ligne d'avant + // afin que le binding se deroule bien meme si ensuite on rechange + // la ligne selectionne (cas ou on etait sur la premier ligne et + // que le modele n'est pas vide) + changeSelectedRow(rowToDelete); + if (rowToDelete == -1 && !isEmpty()) { + // on repasse sur la premiere ligne + // car le modele n'est pas vide + changeSelectedRow(0); + } + } + } + + public boolean isCanQuitEditingRow() { + if (selectedRow == -1) { + // aucune ligne selectionne + // on peut changer la ligne sans verification + return true; + } + + if (!create && !isModelModified()) { + // on est sur une ligne en mode mise a jour + // et aucune changement n'a ete effectue + // on peut continuer sans rien tester + return true; + } + + // une ligne etait precemment en cours d'edition et a ete modifiee + + if (log.isDebugEnabled()) { + log.debug("editing row " + getSelectedRow() + " was modified, need confirmation"); + } + + boolean canContinue = false; + + if (isModelValid()) { + // la ligne est valide, on demande a l'utilisateur s'il + // veut la sauvegarder + + int reponse = UIHelper.askUser( + I18n.t("observe.title.need.confirm"), + I18n.t("observe.message.table.editBean.modified"), + JOptionPane.WARNING_MESSAGE, + new Object[]{ + I18n.t("observe.choice.save"), + I18n.t("observe.choice.doNotSave"), + I18n.t("observe.choice.cancel")}, + 0); + if (log.isDebugEnabled()) { + log.debug("response : " + reponse); + } + + switch (reponse) { + case JOptionPane.CLOSED_OPTION: + case 2: + + break; + case 0: + // will save ui + // sauvegarde des modifications + updateRowFromEditBean(); + canContinue = true; + break; + case 1: + // edition annulé + canContinue = true; + if (create) { + + // on doit supprimer la ligne de creation + removeRow(getSelectedRow()); + } else { + + // reset row + resetRow(getSelectedRow()); + } + break; + } + + } else { + + // le validateur n'est pas ok, on ne peut que proposer la perte + // des donnees car elles sont ne pas enregistrables + + int reponse = UIHelper.askUser( + I18n.t("observe.title.need.confirm"), + I18n.t("observe.message.table.editBean.modified.but.invalid"), + JOptionPane.ERROR_MESSAGE, + new Object[]{ + I18n.t("observe.choice.continue"), + I18n.t("observe.choice.cancel")}, + 0); + if (log.isDebugEnabled()) { + log.debug("response : " + reponse); + } + switch (reponse) { + case 0: + // wil reset ui + canContinue = true; + if (create) { + // on doit supprimer la ligne de creation + removeRow(getSelectedRow()); + } + break; + } + } + return canContinue; + } + + protected void resetRow(int row) { + // do nothing by default + } + + /** + * Selectionne la ligne dont l'index est donné. + * + * @param row l'index de la nouvelle ligne a editer + */ + public void changeSelectedRow(int row) { + + if (log.isDebugEnabled()) { + log.debug("row : " + row); + log.debug("editable : " + isEditable()); + log.debug("size : " + getRowCount()); + } + + if (editable) { + // on force la suppression de l'ancien validateur + getValidator().setBean(null); + } + + if (row == -1) { + // cas special lors de la suppression de la selection, par exemple + // lors d'une suppression de colonne + setSelectedRow(row); + return; + } + + ensureRowIndex(row); + + if (editable) { + // on recharge le bean dans le validateur + // cela permettre de faire fonctionner les binding + // lors de la construction du nouveau editBean + getValidator().setBean(getRowBean()); + } + + // recherche du bean d'édition + B beanToBind; + + // on recupere le bean existant + beanToBind = getValueAt(row); + + // on charge le bean d'edition + load(beanToBind, getRowBean()); + + // on modifie la ligne d'edition + setSelectedRow(row); + + if (editable) { + // pas de modification sur le validateur + getValidator().setChanged(false); + } + } + + /** + * Pour mettre a jour la ligne en cours d'edition a partir du bean + * d'edition + */ + public void updateRowFromEditBean() { + ensureEditable(); + + int editingRow = getSelectedRow(); + + // mettre a jour la ligne + B bean = getValueAt(editingRow); + load(getRowBean(), bean); + fireTableRowsUpdated(editingRow, editingRow); + + if (create) { + // la ligne n'est plus en mode creation + setCreate(false); + } + + // plus de modification sur le bean d'edition + getValidator().setChanged(false); + + // le model a ete modifie + setModified(true); + // on valide le bean principal + // pour cela on doit recharger l'association dans le bean principale + // car vu que l'on travaille sur des collections, si on ne supprime + // pas la liste avant de vouloir valider, alors aucune validation ne + // sera declanchée (car pas de propriété modifié dans le bean...) + getParentValidator().doValidate(); + } + + public void resetEditBean() { + B bean = getValueAt(getSelectedRow()); + + load(bean, getRowBean()); + // plus de modification sur le bean d'edition + getValidator().setChanged(false); + } + + @SuppressWarnings("unchecked") + protected ContentTableUIHandler<P, B> getHandler() { + ContentTableUIHandler<P, B> handler = context.getHandler(); + return handler; + } + + protected abstract Collection<B> getChilds(P bean); + + protected abstract void load(B source, B target); + + protected P getBean() { + ContentTableUIModel<P, B> model = getModel(); + return model == null ? null : model.getBean(); + } + + public B getRowBean() { + ContentTableUIModel<P, B> model = getModel(); + return model == null ? null : model.getTableEditBean(); + } + + public boolean isNewRow() { + return getRowBean().getId() == null; + } + + public boolean isCreate() { + return create; + } + + public void setCreate(boolean create) { + boolean old = this.create; + this.create = create; + firePropertyChange(CREATE_PROPERTY, old, create); + } + + public int getSelectedRow() { + return selectedRow; + } + + public void setSelectedRow(int selectedRow) { + int old = this.selectedRow; + this.selectedRow = selectedRow; + firePropertyChange(SELECTED_ROW_PROPERTY, old, selectedRow); + } + + public String getDeleteExtraMessage() { + return deleteExtraMessage; + } + + public void setDeleteExtraMessage(String deleteExtraMessage) { + this.deleteExtraMessage = deleteExtraMessage; + } + + public boolean isModified() { + return modified; + } + + public void setModified(boolean modified) { + boolean oldModified = this.modified; + this.modified = modified; + firePropertyChange(MODIFIED_PROPERTY, oldModified, modified); + } + + public boolean isEditable() { + return editable; + } + + public void setEditable(boolean editable) { + boolean oldModified = this.editable; + this.editable = editable; + firePropertyChange(EDITABLE_PROPERTY, oldModified, editable); + } + + public boolean isValueAdjusting() { + return valueAdjusting; + } + + public boolean isEmpty() { + return getRowCount() == 0; + } + + public List<B> getData() { + if (data == null) { + if (init) { + // le modèle a ete initialise + // on recupere donc la liste a partir du bean principal + P bean = getBean(); + + Collection<B> childs = getChilds(bean); + if (childs == null || childs.isEmpty()) { + data = new ArrayList<>(); + } else { + data = new ArrayList<>(childs); + } + } else { + // le modèle n'est pas encore initialisé + // on retourne donc une liste vide + data = new ArrayList<>(); + } + } + return data; + } + + public int getColumn(String columnName) { + int i = 0; + for (ContentTableMeta<B> m : metas) { + if (m.getName().equals(columnName)) { + return i; + } + i++; + } + return -1; + } + + @Override + public int getRowCount() { + List<B> list = getData(); + return list == null ? 0 : list.size(); + } + + @Override + public int getColumnCount() { + return metas.size(); + } + + @Override + public String getColumnName(int columnIndex) { + ensureColumnIndex(columnIndex); + return metas.get(columnIndex).getName(); + } + + @Override + public Class<?> getColumnClass(int columnIndex) { + ensureColumnIndex(columnIndex); + return metas.get(columnIndex).getType(); + } + + public ContentTableMeta<B> getColumnMeta(int columnIndex) { + ensureColumnIndex(columnIndex); + return metas.get(columnIndex); + } + + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + // dans ce type de modele rien n'est editable + return false; + } + + @Override + public Object getValueAt(int row, int column) { + ensureColumnIndex(column); + ContentTableMeta<B> meta = getColumnMeta(column); + B bean = getValueAt(row); + return bean == null ? null : getValueAt(bean, row, meta); + } + + public B getValueAt(int row) { + ensureRowIndex(row); + List<B> list = getData(); + return list == null ? null : list.get(row); + } + + public void updateEmpty() { + firePropertyChange(EMPTY_PROPERTY, null, isEmpty()); + } + + /** + * @param <T> the type of the column property + * @param column the column to scan + * @return the list of used properties for a given column + */ + @SuppressWarnings({"unchecked"}) + public <T> List<T> getColumnValues(int column) { + List<T> result = new ArrayList<>(); + if (!isEmpty()) { + for (int i = 0; i < getRowCount(); i++) { + T value = (T) getValueAt(i, column); + if (value != null) { + result.add(value); + } + } + } + + return result; + } + + public void addPropertyChangeListener(PropertyChangeListener listener) { + pcs.addPropertyChangeListener(listener); + } + + public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { + pcs.addPropertyChangeListener(propertyName, listener); + } + + public void removePropertyChangeListener(PropertyChangeListener listener) { + pcs.removePropertyChangeListener(listener); + } + + public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { + pcs.removePropertyChangeListener(propertyName, listener); + } + + public void firePropertyChange(String propertyName, Object oldValue, Object newValue) { + pcs.firePropertyChange(propertyName, oldValue, newValue); + } + + @SuppressWarnings("unchecked") + protected SwingValidator<B> getValidator() { + return context == null ? null : context.getValidatorTable(); + } + + @SuppressWarnings("unchecked") + protected SwingValidator<P> getParentValidator() { + return context == null ? null : context.getValidator(); + } + + protected void removeRow(int row) { + ensureRowIndex(row); + setSelectedRow(-1); + getData().remove(row); + + updateBeanList(!create); + + if (log.isDebugEnabled()) { + log.debug(row); + } + // model has changed + if (!create) { + setModified(true); + } + fireTableRowsDeleted(row, row); + if (create) { + // on quitte le mode creation + setCreate(false); + } + updateEmpty(); + } + + protected Object getValueAt(B bean, int row, ContentTableMeta<B> meta) { + return meta.getValue(this, bean, row); + } + + protected boolean setValueAt(B bean, Object aValue, int row, ContentTableMeta<B> meta) { + return meta.setValue(this, bean, aValue, row); + } + + protected void ensureColumnIndex(int columnIndex) throws ArrayIndexOutOfBoundsException { + if (columnIndex < 0 || columnIndex >= metas.size()) { + throw new ArrayIndexOutOfBoundsException("column index should be in [0," + metas.size() + "], but was " + columnIndex); + } + } + + protected void ensureRowIndex(int rowIndex) throws ArrayIndexOutOfBoundsException { + int size = getRowCount(); + if (rowIndex < 0 || rowIndex >= size) { + throw new ArrayIndexOutOfBoundsException("row index should be in [0," + (getRowCount() - 1) + "], but was " + rowIndex); + } + } + + protected void ensureEditable() throws IllegalStateException { + if (!editable) { + throw new IllegalStateException("can not edit this model since it is marked as none editable " + this); + } + } + + protected void setInit(boolean init) { + this.init = init; + // le changement de l'état init provoque toujours le vidage du cache + clearCache(); + } + + protected void clearCache() { + data = null; + } + + protected void updateBeanList(boolean shouldChanged) { + SwingValidator<P> parentValidator = getParentValidator(); + boolean wasChanged = parentValidator.isChanged(); + + // on repositionne la liste sur le bean principal + // pour avoir la validation en temps reel sur le bean principal + setChilds(getBean(), data); + parentValidator.doValidate(); + if (!shouldChanged && !wasChanged) { + // on repositionne le drapeau changed a faux + parentValidator.setChanged(false); + } + } + + protected abstract void setChilds(P parent, List<B> childs); + + protected boolean isModelModified() { + return getValidator().isChanged(); + } + + protected boolean isModelValid() { + return getValidator().isValid(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableUI.jaxx new file mode 100644 index 0000000..4ef6950 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableUI.jaxx @@ -0,0 +1,201 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.ContentUI + abstract='true' + superGenericType='E' implements="fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI<E,D>" + genericType='E extends IdDto, D extends IdDto'> + + <import> + fr.ird.observe.application.swing.ui.actions.shared.ResetEditUIAction + fr.ird.observe.application.swing.ui.actions.shared.SaveEditUIAction + + jaxx.runtime.swing.BlockingLayerUI + jaxx.runtime.validator.swing.SwingValidator + + fr.ird.observe.services.dto.AbstractObserveDto + fr.ird.observe.services.dto.IdDto + + java.awt.Dimension + + javax.swing.UIManager + + static org.nuiton.i18n.I18n.n + + </import> + + <!-- les libellés et info-bulles des actions sur l'éditeur d'un entrée --> + <String id='newEntryText' javaBean='n("observe.action.new.entry")'/> + <String id='newEntryTip' javaBean='n("observe.action.new.entry.tip")'/> + <String id='resetEntryText' javaBean='n("observe.content.action.reset")'/> + <String id='resetEntryTip' javaBean='n("observe.content.action.reset.entry.tip")'/> + <String id='resetNewEntryText' javaBean='n("observe.content.action.reset")'/> + <String id='resetNewEntryTip' javaBean='n("observe.content.action.reset.new.entry.tip")'/> + <String id='saveEntryText' javaBean='n("observe.action.save")'/> + <String id='saveEntryTip' javaBean='n("observe.action.save.entry.tip")'/> + <String id='saveNewEntryText' javaBean='n("observe.action.create")'/> + <String id='saveNewEntryTip' javaBean='n("observe.content.action.create.entry.tip")'/> + <String id='deleteEntryText' javaBean='n("observe.action.delete")'/> + <String id='deleteEntryTip' javaBean='n("observe.action.delete.entry.tip")'/> + + <!-- Handler --> + <ContentTableUIHandler id='handler' genericType='E, D'/> + + <!-- Model --> + <ContentTableUIModel id='model' genericType='E, D' initializer='ContentTableUIModel.newModel(this)'/> + + <!-- le modèle du tableau --> + <ContentTableModel id='tableModel' genericType='E, D' initializer='getModel().getTableModel()'/> + + <!-- le modèle de selection dans le tableau --> + <ListSelectionModel id='selectionModel' initializer='getModel().getSelectionModel()' + onValueChanged='getHandler().updateEditor(event)'/> + + <!-- le bloqueur de l'editeur d'une entrée du tableau --> + <BlockingLayerUI id='editorBlockLayerUI'/> + + <IdDto id='tableEditBean' initializer='getModel().getTableEditBean()'/> + + <!-- icone des donnees observees --> + <Icon id='iconDataObserve' initializer='SwingUtil.getUIManagerActionIcon("data-observe")'/> + + <!-- icone des donnees calculees --> + <Icon id='iconDataCalcule' initializer='SwingUtil.getUIManagerActionIcon("data-calcule")'/> + + <script><![CDATA[ + +public abstract SwingValidator<E> getValidator(); + +public abstract SwingValidator<D> getValidatorTable(); + +]]> + </script> + + <JPanel id="body"> + + <JPanel id='hideForm' layout='{new BorderLayout()}' + constraints="BorderLayout.CENTER"> + <JLabel id='hideFormInformation'/> + </JPanel> + + <Table id='showForm' insets="0" weightx="1" fill="both" + constraints="BorderLayout.CENTER"> + + <row weighty="0.3"> + <cell> + + <!-- le tableau --> + <JScrollPane id='tableScrollPane'> + <JTable id='table'/> + </JScrollPane> + + </cell> + </row> + + <row> + <cell> + + <!-- éditeur d'une entrée du tableau --> + <Table id='editor' fill='both' insets='0' decorator='boxed'> + + <!-- le panel d'edition d'une entrée à surcharger pour chaque écran --> + + <row> + <cell fill='both' weightx='1'> + <Table id='editorPanel' decorator='boxed'/> + </cell> + </row> + + <!--les actions sur l'éditeur d'une entrée du tableau --> + + <row> + <cell> + <Table fill='both' id='editorActions'> + <row> + <cell weightx='1'> + <!-- ajouter une nouvelle entrée --> + <JButton id='newEntry' + onActionPerformed='getTableModel().addNewEntry()'/> + </cell> + <cell weightx='1'> + <!-- annuler la création d'une nouvelle entrée (en mode creation) --> + <JButton id='resetNewEntry' + onActionPerformed='getTableModel().doRemoveRow(getTableModel().getSelectedRow(), true)'/> + </cell> + <cell weightx='1'> + <!-- réinitialiser l'entrée en cours d'édition (en mode mise a jour) --> + <JButton id='resetEntry' + onActionPerformed='getHandler().resetEditBean()'/> + </cell> + <cell weightx='1'> + <!-- sauver dans le tableau l'entrée en cours d'édition (en mode mise a jour)--> + <JButton id='saveEntry' + onActionPerformed='getTableModel().updateRowFromEditBean()'/> + </cell> + <cell weightx='1'> + <!-- sauver dans le tableau la nouvelle entrée (en mode creation) --> + <JButton id='saveNewEntry' + onActionPerformed='getTableModel().updateRowFromEditBean()'/> + </cell> + <cell weightx='1'> + <!-- supprimer l'entrée courante dans le tableau (en mode mise a jour)--> + <JButton id='deleteEntry' + onActionPerformed='getHandler().removeSelectedRow(getTableModel().getSelectedRow())'/> + </cell> + </row> + </Table> + </cell> + </row> + </Table> + </cell> + </row> + <row> + <cell> + + <Table id='extraZone' decorator='boxed'/> + + </cell> + </row> + </Table> + + </JPanel> + + <!-- actions de l'écran --> + + <Table id="actions" fill='both' weightx='1' insets='0'> + <row fill="both"> + <!-- remonter dans l'arbre de navigation --> + <!--cell weightx="0.5"> + <JButton id='up'/> + </cell--> + <cell weightx="0.5"> + <!-- réinitialiser l'écran --> + <JButton id='reset'/> + </cell> + <cell weightx="0.5"> + <!-- sauver les modifications de l'écran --> + <JButton id='save'/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableUI.jcss new file mode 100644 index 0000000..904fa75 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableUI.jcss @@ -0,0 +1,144 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#model { + valid:{getValidator().isValid() && getValidatorTable().isValid()}; + modified:{tableModel.isModified() || getValidator().isChanged()}; + canSaveRow:{getValidatorTable().isChanged() && getValidatorTable().isValid()}; + canResetRow:{getValidatorTable().isChanged()}; + editable:true; + enabled:{!model.isReadingMode()}; +} + +#body { + layout:{new BorderLayout()}; +} + +#tableModel { + editable:{!model.isReadingMode()}; +} + +#selectionModel { + selectionMode:{ListSelectionModel.SINGLE_SELECTION}; +} + +#editorBlockLayerUI { + useIcon:false; + blockingColor:{UIManager.getColor("BlockingLayerUI.blockingColor")}; + block:{!tableModel.isEditable()}; +} + +#tableScrollPane { + columnHeaderView:{table.getTableHeader()}; + minimumSize:{new Dimension(10, 100)}; +} + +#table { + model:{tableModel}; + selectionModel:{selectionModel}; + rowSelectionAllowed:true; + autoResizeMode:2; + fillsViewportHeight:true; +} + +#editor { + border:{new TitledBorder("")}; +} + +#editorPanel { + visible:{!tableModel.isEmpty()}; +} + +#editorActions { + visible:{tableModel.isEditable()}; +} + +#newEntry { + text:{getNewEntryText()}; + toolTipText:{getNewEntryTip()}; + actionIcon:"add"; + visible:{tableModel.isEditable() && !tableModel.isCreate()}; +} + +#resetNewEntry{ + text:{getResetNewEntryText()}; + toolTipText:{getResetNewEntryTip()}; + actionIcon:"revert"; + enabled:true; + visible:{tableModel.isEditable() && tableModel.isCreate()}; +} + +#resetEntry { + text:{getResetEntryText()}; + toolTipText:{getResetEntryTip()}; + actionIcon:"revert"; + enabled:{model.isCanResetRow()}; + visible:{tableModel.isEditable() && !tableModel.isEmpty() && !tableModel.isCreate()}; +} + +#saveEntry{ + text:{getSaveEntryText()}; + toolTipText:{getSaveEntryTip()}; + actionIcon:"save"; + visible:{tableModel.isEditable() && !tableModel.isEmpty() && !tableModel.isCreate()}; + enabled:{model.isCanSaveRow()}; +} + +#saveNewEntry { + text:{getSaveNewEntryText()}; + toolTipText:{getSaveNewEntryTip()}; + actionIcon:"add"; + visible:{tableModel.isEditable() && !tableModel.isEmpty() && tableModel.isCreate()}; + enabled:{model.isCanSaveRow()}; +} + +#deleteEntry { + text:{getDeleteEntryText()}; + toolTipText:{getDeleteEntryTip()}; + actionIcon:"delete"; + visible:{tableModel.isEditable() && !tableModel.isEmpty() && !tableModel.isCreate()}; +} + +#up { + _observeAction:{fr.ird.observe.application.swing.ui.actions.shared.GoUpUIAction.ACTION_NAME}; + visible:{!model.isCreatingMode()}; +} + +#reset { + _observeAction:{ResetEditUIAction.ACTION_NAME}; + visible:{model.isEnabled()}; + enabled:{model.isModified()}; +} + +#save { + _observeAction:{SaveEditUIAction.ACTION_NAME}; + _toolTipText:{t("observe.action.save.all.tip")}; + visible:{model.isEnabled()}; + enabled:{model.isModified() && model.isValid() && !tableModel.isCreate()}; +} + +#hideFormInformation { + actionIcon:"information"; + font-size:11; + verticalAlignment:"center"; + horizontalAlignment:"center"; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableUIHandler.java new file mode 100644 index 0000000..2323a87 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableUIHandler.java @@ -0,0 +1,484 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.table; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.SpeciesDto; +import fr.ird.observe.services.dto.referential.seine.WeightCategoryDto; +import fr.ird.observe.services.dto.seine.TargetCatchDto; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.ContentUIHandler; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; +import fr.ird.observe.application.swing.ui.content.table.impl.longline.WeightMeasuresTableModel; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.util.table.EditableTableModelSupport; +import fr.ird.observe.application.swing.ui.util.table.InlineTableAutotSelectRowAndShowPopupAction; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.ListSelectionModel; +import javax.swing.SwingUtilities; +import javax.swing.event.ListSelectionEvent; +import javax.swing.event.TableModelEvent; +import javax.swing.table.DefaultTableCellRenderer; +import java.awt.Rectangle; +import java.beans.PropertyChangeListener; +import java.io.Serializable; +import java.util.List; +import java.util.Optional; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Le controleur d'un écran d'édition avec tableau. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public abstract class ContentTableUIHandler<E extends IdDto, D extends IdDto> extends ContentUIHandler<E> { + + /** Logger */ + private static final Log log = LogFactory.getLog(ContentTableUIHandler.class); + + protected ContentTableUIHandler(ObserveContentTableUI<E, D> ui, DataContextType dataContextType) { + super(ui, dataContextType, null); + } + + /** + * Hook lors du changement d'entrée éditée. + * + * @param editingRow la nouvelle entrée à editer + * @param bean le bean d'édition d'une entrée + * @param create un drapeau pour savoir si l'entrée est en création + */ + protected abstract void onSelectedRowChanged(int editingRow, D bean, boolean create); + + @Override + protected boolean computeCanWrite(ObserveSwingDataSource source) { + return source.canWriteData(); + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + // par defaut, on suppose qu'on peut afficher les données + getModel().setShowData(true); + + String activityId = dataContext.getSelectedActivityId(); + + if (getOpenDataManager().isOpenActivity(activityId)) { + + // mode mise a jour + return ContentMode.UPDATE; + } + + // mode lecture + + if (dataContext.isSelectedActivityLongline()) { + + addInfoMessage(t("observe.storage.activityLongline.message.not.open")); + + } else { + + addInfoMessage(t("observe.storage.activitySeine.message.not.open")); + + } + + return ContentMode.READ; + } + + @Override + public ContentTableUIModel<E, D> getModel() { + return (ContentTableUIModel<E, D>) super.getModel(); + } + + @Override + public ObserveContentTableUI<E, D> getUi() { + return (ObserveContentTableUI<E, D>) super.getUi(); + } + + public final D getTableEditBean() { + return getModel().getTableEditBean(); + } + + public final void updateEditor(ListSelectionEvent event) { + + final ObserveContentTableUI<E, D> ui = getUi(); + + if (ui.getValidatorTable() == null) { + log.debug("skip validator is null!"); + return; + } + if (getBean() == null) { + log.debug("skip bean is null!"); + return; + } + if (log.isDebugEnabled()) { + log.debug(event); + } + if (getTableModel().isEmpty()) { + // le modele est vide, on ne propage rien + //FIXME le modèle de selection ne devrait plus declancher des evenement + //FIXME des que le modele est vide ? + log.debug("empty model, do nothing"); + return; + } + + ListSelectionModel sModel = (ListSelectionModel) event.getSource(); + int newIndex = sModel.getAnchorSelectionIndex(); + + if (newIndex == -1 || sModel.isSelectionEmpty()) { + //FIXME le modèle de selection ne devrait plus declancher des evenement + //FIXME des que le modele est vide ? + log.debug("skip with row == -1, or empty selection, do nothing"); + return; + } + + SwingUtilities.invokeLater(() -> { + if (!ui.getSelectionModel().isSelectionEmpty()) { + // on veut toujours que la ligne sélectionnée soit visible + Rectangle rect = ui.getTable().getCellRect(ui.getSelectionModel().getAnchorSelectionIndex(), 0, false); + ui.getTable().scrollRectToVisible(rect); + } + }); + + int selectedRow = getTableModel().getSelectedRow(); + if (newIndex == selectedRow) { + // on bloque du code re-entrant + log.debug("new index already set in model " + newIndex + ", do nothing"); + return; + } + // on doit changer de ligne selectionne dans le modele + getTableModel().changeSelectedRow(newIndex); + } + + protected abstract void initTableUI(DefaultTableCellRenderer renderer); + + protected abstract String getEditBeanIdToLoad(); + + protected E loadEditBean(ContentMode mode) { + + String id = getEditBeanIdToLoad(); + + if (id == null) { + throw new IllegalStateException("Could not find id form " + this); + } + + E editBean = getBean(); + + // preparation du bean d'édition + loadEditBean(id); + + // initialisation du modèle du tableau + getUi().getTableModel().attachModel(); + + return editBean; + } + + protected abstract void loadEditBean(String beanId); + + //FIXME +// @Override +// protected final void onLoad(TopiaContext tx, E bean) throws TopiaException { +// super.onLoad(tx, bean); +// +// // on duplique la liste des fils traites dans le tableau +// // sinon on reste sur les references d'origine et on aura pas +// // la possibilité d'annuler l'edition ensuite car on aura modifie +// // les entrées d'origine... +// E editBean = getBean(); +// Collection<D> data = loadChilds(tx, editBean); +// getModel().getChildsUpdator().setChilds(editBean, data); +// } + + //FIXME +// protected Collection<D> loadChilds(TopiaContext tx, E bean) throws TopiaException { +// Collection<D> childs = getModel().getChildsUpdator().getChilds(bean); +// Collection<D> data = new ArrayList<D>(); +// if (CollectionUtils.isNotEmpty(childs)) { +// Loador<D> loader = getModel().getChildLoador(); +// TopiaDAO<D> dao = getMainDataSource().getDAO(tx, getTableEditBean()); +// for (D c : childs) { +// try { +// D cUp = dao.findByTopiaId(c.getTopiaId()); +// D c2 = getModel().newTableEditBean(); +// loader.load(cUp, c2, true); +// data.add(c2); +// } catch (Exception e) { +// throw new RuntimeException(e); +// } +// } +// } +// return data; +// } + + @Override + public void initUI() { + + final ContentTableUIInitializer<E, D, ObserveContentTableUI<E, D>> uiInitializer = + new ContentTableUIInitializer<>(getUi()); + uiInitializer.initUI(); + + getModel().addPropertyChangeListener(ContentUIModel.PROPERTY_FORM, evt -> updateUiWithReferenceSetsFromModel()); + + } + + @Override + public void openUI() { + + super.openUI(); + + // récupération du mode de l'écran + ContentMode mode = computeContentMode(); + + ObserveContentTableUI<E, D> ui = getUi(); + + int oldIndex = ui.getTableModel().getSelectedRow(); + + ui.getTableModel().dettachModel(); + + getModel().setMode(mode); + + // chargement du bean d'édition + loadEditBean(mode); + + boolean canEdit = mode == ContentMode.UPDATE; + + if (canEdit) { + // on lance le mode edition + ui.startEdit(null); + } + + if (!ui.getTableModel().isEmpty()) { + if (ui.getTableModel().getRowCount() <= oldIndex) { + oldIndex = 0; + } + if (oldIndex == -1) { + oldIndex = 0; + } + + // le tableau contient au moins une entrée + // on la sélectionne la première entrée + ui.getTableModel().changeSelectedRow(oldIndex); + } + + if (canEdit) { + + // on force l'ecran en non modification + //FIXME normalement, on ne devrait pas a avoir a faire ca ? + //FIXME mais il est possible que les validateurs modifient l'état + //FIXME modified sur l'ecran lors des bindings d'initilisation... + getModel().setModified(false); + } + } + + @Override + public void startEditUI(String... binding) { + + addUpdateInfoMessage(); + super.startEditUI(binding); + } + + protected void addUpdateInfoMessage() { + String message = n("observe.entity.message.updating"); + ObserveNode node = getTreeHelper(getUi()).getSelectedNode(); + String entityLabel = + getEntityLabel(node.getParent().getInternalClass()); + message = t(message, t(entityLabel)); + addMessage(getUi(), NuitonValidatorScope.INFO, entityLabel, message); + } + + public void removeSelectedRow(int selectedRow) { + try { + getTableModel().doRemoveRow(selectedRow, false); + } finally { + + // always reset busy model to false + ObserveSwingApplicationContext.get().getMainUI().setBusy(false); + } + } + + @Override + protected boolean doSave(E bean) throws Exception { + + ObserveContentTableUI<E, D> ui = getUi(); + + List<D> objets = ui.getTableModel().getData(); + + boolean canContinue; + try { + canContinue = prepareSave(bean, objets); + } catch (Exception e) { + UIHelper.handlingError(e); + canContinue = false; + } + if (!canContinue) { + + // l'utilisateur a choisi de ne pas sauvegarder + return false; + } + doPersist(bean); + + return true; + } + + protected abstract void doPersist(E bean); + + //FIXME +// @Override +// protected E onUpdate(TopiaContext tx, Object parentBean, E beanToSave) throws TopiaException { +// +// List<D> childs = getUi().getTableModel().getData(); +// +// E editBean = getBean(); +// +// TopiaEntityBinder<E> binder = getLoadBinder(); +// +// Loador<D> childBinder = getModel().getChildLoador(); +// +// EntityListUpdator<E, D> childUpdator = getModel().getChildsUpdator(); +// +// // recopie des propriétés du bean en excluant toujours la liste des fils +// binder.copyExcluding(editBean, beanToSave, childUpdator.getPropertyName()); +// +// // on conserve l'ancienne liste des fils (pour traitement ultérieure) +// Collection<D> oldChilds = +// new ArrayList<D>(childUpdator.getChilds(beanToSave)); +// +// // suppression des fils dans le bean a sauver +// childUpdator.removeAll(beanToSave); +// +// TopiaDAO<D> dao = ObserveDAOHelper.getDAO(tx, getModel().getChildType()); +// +// for (D child : childs) { +// +// D childToSave; +// +// if (child.getTopiaId() == null) { +// +// // creation du fils +// Map<String, Object> map = childBinder.obtainProperties(child); +// +// childToSave = dao.create(map); +// +// } else { +// +// // mise a jour du fils +// +// childToSave = dao.findByTopiaId(child.getTopiaId()); +// +// childBinder.load(child, childToSave, false); +// } +// +// // ajout du fils au bean à sauver +// childUpdator.addToList(beanToSave, childToSave); +// } +// +// // on donne la main aux implantations pour faire des traitements +// // supplémentaires +// onUpdateFinalize(tx, beanToSave, oldChilds); +// +// return beanToSave; +// } + + @Override + protected void afterSave(boolean refresh) { + + // on recharge l'écran + resetEditUI(); + } + + protected boolean prepareSave(E editBean, List<D> objets) throws Exception { + + // par defaut, rien de specifique a faire avant de faire la sauvegarde + return true; + } + + //FIXME +// protected void onUpdateFinalize(TopiaContext tx, E bean, Collection<D> oldChilds) throws TopiaException { +// // par défaut, rien à faire +// } + + protected ContentTableModel<E, D> getTableModel() { + return getUi().getTableModel(); + } + + protected void resetEditBean() { + getTableModel().resetEditBean(); + } + + /** + * @param weightCategory la catégorie de poids + * @return la référence sur l'espèce de la catégorie de poids + */ + protected Optional<ReferentialReference<SpeciesDto>> getWeightCategorySpecies(ReferentialReference<WeightCategoryDto> weightCategory) { + + String speciesId = (String) weightCategory.getPropertyValue(WeightCategoryDto.PROPERTY_SPECIES); + + Optional<ReferentialReference<SpeciesDto>> optionalSpecies = getModel().tryGetReferentialReferenceById(TargetCatchDto.PROPERTY_SPECIES, speciesId); + + return optionalSpecies; + } + + protected <EE extends Serializable, MM extends EditableTableModelSupport<EE>> void initInlineTable(JScrollPane pane, + JTable table, + MM tableModel, + PropertyChangeListener modifiedListener, + JPopupMenu popup, + JMenuItem addMeasure, + JMenuItem deleteMeasure) { + + tableModel.addPropertyChangeListener(WeightMeasuresTableModel.MODIFIED_PROPERTY, modifiedListener); + + ListSelectionModel selectionModel = table.getSelectionModel(); + selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); + tableModel.installSelectionListener(table); + tableModel.installTableKeyListener(table); + + tableModel.addTableModelListener(e -> { + if (e.getType() == TableModelEvent.DELETE) { + tableModel.validate(); + } + }); + + new InlineTableAutotSelectRowAndShowPopupAction<>( + pane, + table, + tableModel, + popup, + addMeasure, + deleteMeasure); + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableUIInitializer.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableUIInitializer.java new file mode 100644 index 0000000..06a59ba --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableUIInitializer.java @@ -0,0 +1,257 @@ +package fr.ird.observe.application.swing.ui.content.table; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.application.swing.ui.content.ContentUIInitializer; +import fr.ird.observe.application.swing.ui.util.BooleanEditor; +import jaxx.runtime.SwingUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.jaxx.application.bean.JavaBeanObjectUtil; + +import javax.swing.AbstractButton; +import javax.swing.ActionMap; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.table.DefaultTableCellRenderer; +import java.awt.BorderLayout; +import java.awt.event.ItemEvent; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; + +/** + * To initialize ui. + * + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.7 + */ +public class ContentTableUIInitializer<E extends IdDto, D extends IdDto, UI extends ObserveContentTableUI<E, D>> extends ContentUIInitializer<E, UI> { + + public static final String CLIENT_PROPERTY_TABLE_PROPERTY_NAME = "tablePropertyName"; + + public static final String CLIENT_PROPERTY_RESET_TABLE_PROPERTY_NAME = "resetTablePropertyName"; + + /** Logger. */ + private static final Log log = LogFactory.getLog(ContentTableUIInitializer.class); + + public ContentTableUIInitializer(UI ui) { + super(ui); + } + + protected D getTableEditBean() { + return getModel().getTableEditBean(); + } + + protected ContentTableUIModel<E, D> getModel() { + return ui.getModel(); + } + + protected ContentTableUIHandler<E, D> getHandler() { + return ui.getHandler(); + } + + @Override + public void initUI() { + + super.initUI(); + + ContentTableModel<?, ?> tableModel = ui.getTableModel(); + ui.setContextValue(tableModel); + + if (ui.getBody() != null) { + + // on supprime le layer de blocage en mode disable + SwingUtil.setLayerUI(ui.getBody(), null); + + } + + if (ui.getExtraZone() != null) { + + // et on le remet sur les zones non clicables de l'ui + SwingUtil.setLayerUI(ui.getExtraZone(), ui.getBlockLayerUI()); + + } + + // on ajoute un layer pour bloquer l'édition des entrées si nécessaire + SwingUtil.setLayerUI(ui.getEditor(), ui.getEditorBlockLayerUI()); + + // préparation du tableau dans l'ui + getHandler().initTableUI(new DefaultTableCellRenderer()); + + // ajout d'un listener pour preparer l'éditeur d'une entrée selectionnée + tableModel.addPropertyChangeListener( + ContentTableModel.SELECTED_ROW_PROPERTY, + evt -> { + ContentTableModel<E, D> model; + model = (ContentTableModel<E, D>) evt.getSource(); + D bean = model.getRowBean(); + boolean create = bean.getId() == null; + Integer selectedRow = (Integer) evt.getNewValue(); + if (log.isDebugEnabled()) { + log.debug("callback new selectedRow : " + selectedRow + " : " + bean.getId()); + } + getHandler().onSelectedRowChanged(selectedRow, bean, create); + getModel().setRowSaved(!create); + if (selectedRow == -1) { + if (log.isDebugEnabled()) { + log.debug(">>>>>>>>>> will clear selection..."); + } + // on supprime la selection + ui.getSelectionModel().clearSelection(); + if (log.isDebugEnabled()) { + log.debug("<<<<<<<<<< has clear selection..."); + } + } else { + // on met a jour le modele de selection + ui.getSelectionModel().setSelectionInterval( + selectedRow, selectedRow); + } + }); + + getModel().addPropertyChangeListener( + ContentTableUIModel.PROPERTY_SHOW_DATA, + evt -> { + + Boolean newValue = (Boolean) evt.getNewValue(); + onShowDataChanged(newValue); + + }); + + } + + @Override + protected void initBlockLayerUI(String... doNotBlockComponentIds) { + + super.initBlockLayerUI(doNotBlockComponentIds); + + //tchemit-2014-12-29 We should use a spearate list for this, but there is no collision possible... + ui.getEditorBlockLayerUI().setAcceptedComponentNames(doNotBlockComponentIds); + + } + + protected void onShowDataChanged(Boolean showData) { + + JComponent body = ui.getBody(); + if (showData != null && showData) { + body.remove(ui.getHideForm()); + body.add(ui.getShowForm(), BorderLayout.CENTER); + } else { + body.remove(ui.getShowForm()); + body.add(ui.getHideForm(), BorderLayout.CENTER); + } + } + + @Override + protected void init(ActionMap actionMap, + AbstractButton editor) { + + super.init(actionMap, editor); + + String actionId = (String) editor.getClientProperty(ContentUIInitializer.OBSERVE_ACTION); + if (actionId == null) { + + // le boutton n'est pas commun + + final String propertyName = (String) editor.getClientProperty(CLIENT_PROPERTY_RESET_TABLE_PROPERTY_NAME); + if (propertyName != null) { + editor.addActionListener(e -> JavaBeanObjectUtil.setProperty(getTableEditBean(), propertyName, null)); + } + + } + + } + + @Override + protected void init(JTextField editor) { + + super.init(editor); + + final String propertyName = (String) editor.getClientProperty(CLIENT_PROPERTY_TABLE_PROPERTY_NAME); + if (propertyName != null) { + editor.addKeyListener(new KeyAdapter() { + @Override + public void keyReleased(KeyEvent e) { + JTextField source = (JTextField) e.getSource(); + String text = source.getText(); + JavaBeanObjectUtil.setProperty(getTableEditBean(), propertyName, text); + } + }); + } + + } + + @Override + protected void init(JTextArea editor) { + + final String propertyName = (String) editor.getClientProperty(CLIENT_PROPERTY_TABLE_PROPERTY_NAME); + if (propertyName != null) { + editor.addKeyListener(new KeyAdapter() { + @Override + public void keyReleased(KeyEvent e) { + JTextArea source = (JTextArea) e.getSource(); + String text = source.getText(); + JavaBeanObjectUtil.setProperty(getTableEditBean(), propertyName, text); + } + }); + } + + } + + @Override + protected void init(final JCheckBox editor) { + + super.init(editor); + + final String propertyName = (String) editor.getClientProperty(CLIENT_PROPERTY_TABLE_PROPERTY_NAME); + if (propertyName != null) { + editor.addItemListener(event -> { + Boolean newValue = ((JCheckBox) event.getSource()).isSelected(); + JavaBeanObjectUtil.setProperty(getTableEditBean(), propertyName, newValue); + }); + } + + } + + @Override + protected void init(BooleanEditor editor) { + + super.init(editor); + + final String propertyName = (String) editor.getClientProperty(CLIENT_PROPERTY_TABLE_PROPERTY_NAME); + if (propertyName != null) { + editor.addItemListener(event -> { + if (event.getStateChange() == ItemEvent.SELECTED) { + + Boolean newValue = ((BooleanEditor) event.getSource()).getBooleanValue(); + JavaBeanObjectUtil.setProperty(getTableEditBean(), propertyName, newValue); + } + }); + } + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableUIModel.java new file mode 100644 index 0000000..fe897b8 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ContentTableUIModel.java @@ -0,0 +1,313 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.table; + +import fr.ird.observe.application.swing.ObserveSwingBinderService; +import fr.ird.observe.application.swing.ObserveSwingTechnicalException; +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; +import org.apache.commons.lang3.reflect.ConstructorUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.util.beans.BinderModelBuilder; + +import javax.swing.DefaultListSelectionModel; +import javax.swing.ListSelectionModel; +import java.util.List; + +/** + * Le modèle d'un écran d'édition avec tableau. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public abstract class ContentTableUIModel<E extends IdDto, D extends IdDto> extends ContentUIModel<E> { + + public static final String PROPERTY_CAN_SAVE_ROW = "canSaveRow"; + + public static final String PROPERTY_CAN_RESET_ROW = "canResetRow"; + + public static final String PROPERTY_SHOW_DATA = "showData"; + + public static final String PROPERTY_ROW_SAVED = "rowSaved"; + + private static final long serialVersionUID = 1L; + + /** Logger */ + private static final Log log = LogFactory.getLog(ContentTableUIModel.class); + + protected final Class<D> childType; + + protected final String[] parentProperties; + + protected final String[] childProperties; + + private final transient ListSelectionModel selectionModel; + + protected D tableEditBean; + + protected boolean canSaveRow; + + protected boolean canResetRow; + + /** + * Pour savoir si on peut voir les données du l'écran. + * + * Cela diffère du mode de l'écran, à utiliser par exemple pour les écrans + * d'échantillons lorsqu'aucune discarded n'est effectuée. on se retrouve en + * mode ContentMode.READ mais ce n'est pas suffisant. + * + * @since 3.0 + */ + protected boolean showData; + + protected boolean rowSaved; + + private ContentTableModel<E, D> tableModel; + + public ContentTableUIModel(Class<E> beanType, + Class<D> childType, + String[] parentProperties, + String[] childProperties) { + super(beanType); + this.childType = childType; + this.parentProperties = parentProperties; + this.childProperties = childProperties; + this.selectionModel = new ContentTableListSelectionModel(); + } + + public static <E extends IdDto, D extends IdDto> ContentTableUIModel<E, D> newModel(ObserveContentTableUI<E, D> ui) { + + String uiName = ui.getClass().getName(); + String modelName = uiName + "Model"; + + try { + + Class<ContentTableUIModel<E, D>> modelClass = (Class<ContentTableUIModel<E, D>>) Class.forName(modelName); + ContentTableUIModel<E, D> model = ConstructorUtils.invokeConstructor(modelClass, ui); + return model; + + } catch (Exception e) { + throw new ObserveSwingTechnicalException("Could not create model for ui: " + ui, e); + } + + } + + public void initModel(ObserveContentTableUI<E, D> ui, List<ContentTableMeta<D>> metas) { + + this.tableModel = createTableModel(ui, metas); + + } + + protected abstract ContentTableModel<E, D> createTableModel(ObserveContentTableUI<E, D> ui, List<ContentTableMeta<D>> metas) ; + + public Class<D> getChildType() { + return childType; + } + + public String[] getParentProperties() { + return parentProperties; + } + + public String[] getChildProperties() { + return childProperties; + } + + public ContentTableModel<E, D> getTableModel() { + return tableModel; + } + + public ListSelectionModel getSelectionModel() { + return selectionModel; + } + + /** @return le bean d'une ligne du tableau actuellement sélectionné */ + public D getTableEditBean() { + if (tableEditBean == null) { + try { + tableEditBean = newTableEditBean(); + } catch (Exception e) { + + // ne devrait jamais arrive... + if (log.isErrorEnabled()) { + log.error(e); + } + } + } + return tableEditBean; + } + + public final D newTableEditBean() { + try { + + D result = getChildType().getConstructor().newInstance(); + return result; + + } catch (Exception ex) { + throw new RuntimeException(ex); + + } + } + + public boolean isCanSaveRow() { + return canSaveRow; + } + + public void setCanSaveRow(boolean canSaveRow) { + boolean oldValue = this.canSaveRow; + this.canSaveRow = canSaveRow; + firePropertyChange(PROPERTY_CAN_SAVE_ROW, oldValue, canSaveRow); + } + + public boolean isCanResetRow() { + return canResetRow; + } + + public void setCanResetRow(boolean canResetRow) { + boolean oldValue = this.canResetRow; + this.canResetRow = canResetRow; + firePropertyChange(PROPERTY_CAN_RESET_ROW, oldValue, canResetRow); + } + + public boolean isRowSaved() { + return rowSaved; + } + + public void setRowSaved(boolean rowSaved) { + boolean oldValue = this.rowSaved; + this.rowSaved = rowSaved; + firePropertyChange(PROPERTY_ROW_SAVED, oldValue, rowSaved); + } + + public boolean isShowData() { + return showData; + } + + public void setShowData(boolean showData) { + boolean oldValue = this.showData; + this.showData = showData; + firePropertyChange(PROPERTY_SHOW_DATA, oldValue, showData); + } + + protected BinderModelBuilder<D, D> prepareChildLoador(ObserveSwingBinderService binderService, String binderName) { + + String[] properties = getChildProperties(); + + BinderModelBuilder<D, D> builder = binderService.newBinderBuilder(childType, properties); + + return builder; + + } + + /** + * Le modèle de sélection pour un tableau. + * + * Le modèle permet le blocage du changement de ligne selectionnee dans le + * tableau lorsque les conditions suivantes sont remplies : + * + * - le tableau est editable - une entrée etait precedemment selectionne - + * l'entrée en cours d'édition est modifié + * + * Si on ne peut pas explicitement changer de ligne d'édition, on demande alors + * à l'utilisateur s'il veut sauver l'entrée en cours d'édition (si elle est + * valide), ou bien la perte des données (si elle n'est pas valide). + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ + public class ContentTableListSelectionModel extends DefaultListSelectionModel { + + private static final long serialVersionUID = 1L; + + public ContentTableListSelectionModel() { + } + + @Override + public void setSelectionInterval(int index0, int index1) { + if (log.isTraceEnabled()) { + log.trace(index0 + " - " + index1); + } + + ContentTableModel<?, ?> model = getTableModel(); + + boolean canContinue = canContinue(model, index0); + + if (log.isDebugEnabled()) { + log.debug("can continue for row " + index0 + " : " + canContinue); + } + + if (canContinue) { + // on peut aller sur la nouvelle ligne demandée + super.setSelectionInterval(index0, index1); + } + } + + protected boolean canContinue(ContentTableModel<?, ?> model, int newIndex) { + boolean canContinue; + if (model == null) { + // le model n'est pas encore disponible + return false; + } + + if (!model.isEditable()) { + // le modèle n'est pas editable + // donc aucun controle a effectuer + // on peut change de selection + return true; + } + + if (model.isValueAdjusting()) { + // le modele a demande un ajustement + // donc rien a valider + return true; + } + + // le modèle est editable + + int editingRow = model.getSelectedRow(); + + if (isSelectionEmpty() || editingRow == -1) { + // pas de precedente selection + // ou pas de ligne en cours d'edition + // on peut donc selectionner cette nouvelle ligne + return true; + } + + // le modele a une ligne en cours d'edition + + if (editingRow == newIndex) { + // on veut aller sur la ligne en cours d'edition + // aucune verification a faire + // ce cas peut arriver lors d'un adjustement de ligne + return true; + } + + // une ligne en cours d'edition est différente de celle qu'on + // veut attendre on demande au modèle si on peut quitter cette ligne + canContinue = model.isCanQuitEditingRow(); + + return canContinue; + } + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ObserveContentTableUI.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ObserveContentTableUI.java new file mode 100644 index 0000000..9bbc5c7 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/ObserveContentTableUI.java @@ -0,0 +1,68 @@ +package fr.ird.observe.application.swing.ui.content.table; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.application.swing.ui.content.ObserveContentUI; +import jaxx.runtime.swing.BlockingLayerUI; +import jaxx.runtime.validator.swing.SwingValidator; + +import javax.swing.*; + +/** + * Created on 10/5/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public interface ObserveContentTableUI<E extends IdDto, D extends IdDto> extends ObserveContentUI<E> { + + ContentTableUIHandler<E, D> getHandler(); + + ContentTableUIModel<E, D> getModel(); + + ContentTableModel<E, D> getTableModel(); + + JTable getTable(); + + + JComponent getBody(); + + JComponent getExtraZone(); + + JComponent getEditor(); + + JComponent getHideForm(); + + JComponent getShowForm(); + + ListSelectionModel getSelectionModel(); + + BlockingLayerUI getBlockLayerUI(); + + BlockingLayerUI getEditorBlockLayerUI(); + + SwingValidator<E> getValidator(); + + SwingValidator<D> getValidatorTable(); +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BaitsCompositionUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BaitsCompositionUI.jaxx new file mode 100644 index 0000000..7ec18d5 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BaitsCompositionUI.jaxx @@ -0,0 +1,141 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.table.ContentTableUI + superGenericType='SetLonglineGlobalCompositionDto, BaitsCompositionDto' + contentTitle='{n("observe.content.baitsComposition.title")}' + saveNewEntryText='{n("observe.content.baitsComposition.action.create")}' + saveNewEntryTip='{n("observe.content.baitsComposition.action.create.tip")}'> + + <style source="../../CommonTable.jcss"/> + + <import> + fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto + fr.ird.observe.services.dto.longline.BaitsCompositionDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.longline.BaitTypeDto + fr.ird.observe.services.dto.referential.longline.BaitSettingStatusDto + fr.ird.observe.application.swing.ui.content.table.* + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <BaitsCompositionUIHandler id='handler'/> + + <!-- model --> + <BaitsCompositionUIModel id='model'/> + + <!-- edit bean --> + <SetLonglineGlobalCompositionDto id='bean'/> + + <!-- table edit bean --> + <BaitsCompositionDto id='tableEditBean'/> + + <!-- table model --> + <ContentTableModel id='tableModel'/> + + <!-- le validateur de l'écran --> + <BeanValidator id='validator' autoField='true' context='ui-update-baitsComposition' + beanClass='fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto' + errorTableModel='{getErrorTableModel()}'> + <field name="baitsComposition" component="editorPanel"/> + </BeanValidator> + + <!-- le validateur d'une entrée de tableau --> + <BeanValidator id='validatorTable' autoField='true' context='ui-update' + beanClass='fr.ird.observe.services.dto.longline.BaitsCompositionDto' + errorTableModel='{getErrorTableModel()}'/> + + <Table id='editorPanel' fill='both' insets='1'> + + <!-- baitType --> + <row> + <cell> + <JLabel id='baitTypeLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='baitType' constructorParams='this' genericType='ReferentialReference<BaitTypeDto>' _entityClass='BaitTypeDto.class'/> + </cell> + </row> + + <!-- baitSettingStatus --> + <row> + <cell> + <JLabel id='baitSettingStatusLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='baitSettingStatus' constructorParams='this' genericType='ReferentialReference<BaitSettingStatusDto>' _entityClass='BaitSettingStatusDto.class'/> + </cell> + </row> + + <!-- individualSize --> + <row> + <cell> + <JLabel id='individualSizeLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='individualSize' constructorParams='this'/> + </cell> + </row> + + <!-- individualWeight --> + <row> + <cell> + <JLabel id='individualWeightLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='individualWeight' constructorParams='this'/> + </cell> + </row> + + <!-- proportion --> + <row> + <cell> + <JLabel id='proportionLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='proportion' constructorParams='this'/> + </cell> + </row> + + </Table> + + <Table id='extraZone' fill='both'> + + <!-- proportion sum --> + <row> + <cell> + <JLabel id='baitsCompositionProportionSumLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <JLabel id='baitsCompositionProportionSum'/> + </cell> + </row> + + </Table> + +</fr.ird.observe.application.swing.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BaitsCompositionUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BaitsCompositionUI.jcss new file mode 100644 index 0000000..4cb6e80 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BaitsCompositionUI.jcss @@ -0,0 +1,90 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#baitTypeLabel { + text:"observe.content.baitsComposition.baitType"; + labelFor:{baitType}; +} + +#baitType { + property:{BaitsCompositionDto.PROPERTY_BAIT_TYPE}; + selectedItem:{tableEditBean.getBaitType()}; + _validatorLabel:{t("observe.content.baitsComposition.baitType")}; +} + +#baitSettingStatusLabel { + text:"observe.content.baitsComposition.baitSettingStatus"; + labelFor:{baitSettingStatus}; +} + +#baitSettingStatus { + property:{BaitsCompositionDto.PROPERTY_BAIT_SETTING_STATUS}; + selectedItem:{tableEditBean.getBaitSettingStatus()}; + _validatorLabel:{t("observe.content.baitsComposition.baitSettingStatus")}; +} + +#individualSizeLabel { + text:"observe.content.baitsComposition.individualSize"; + labelFor:{individualSize}; +} + +#individualSize { + property:{BaitsCompositionDto.PROPERTY_INDIVIDUAL_SIZE}; + model:{tableEditBean.getIndividualSize()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.baitsComposition.individualSize")}; +} + +#individualWeightLabel { + text:"observe.content.baitsComposition.individualWeight"; + labelFor:{individualWeight}; +} + +#individualWeight { + property:{BaitsCompositionDto.PROPERTY_INDIVIDUAL_WEIGHT}; + model:{tableEditBean.getIndividualWeight()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL3_PATTERN}; + _validatorLabel:{t("observe.content.baitsComposition.individualWeight")}; +} + +#proportionLabel { + text:"observe.content.baitsComposition.proportion"; + labelFor:{proportion}; +} + +#proportion { + property:{BaitsCompositionDto.PROPERTY_PROPORTION}; + model:{tableEditBean.getProportion()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.baitsComposition.proportion")}; +} + +#baitsCompositionProportionSumLabel { + text:"observe.content.baitsComposition.proportionSum"; + labelFor:{baitsCompositionProportionSum}; +} + +#baitsCompositionProportionSum { + text:{getStringValue(bean.getBaitsCompositionProportionSum())}; + _validatorLabel:{t("observe.content.baitsComposition.proportionSum")}; + font-weight:bold; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BaitsCompositionUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BaitsCompositionUIHandler.java new file mode 100644 index 0000000..de32823 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BaitsCompositionUIHandler.java @@ -0,0 +1,124 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.longline.BaitsCompositionDto; +import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto; +import fr.ird.observe.services.dto.referential.longline.BaitSettingStatusDto; +import fr.ird.observe.services.dto.referential.longline.BaitTypeDto; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; + +import static org.nuiton.i18n.I18n.n; + +/** + * Created on 12/6/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.9 + */ +public class BaitsCompositionUIHandler extends ContentTableUIHandler<SetLonglineGlobalCompositionDto, BaitsCompositionDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(BaitsCompositionUIHandler.class); + + public BaitsCompositionUIHandler(BaitsCompositionUI ui) { + super(ui, DataContextType.SetLongline); + } + + @Override + public BaitsCompositionUI getUi() { + return (BaitsCompositionUI) super.getUi(); + } + + @Override + protected void onSelectedRowChanged(int editingRow, BaitsCompositionDto bean, boolean create) { + + if (getTableModel().isEditable()) { + if (log.isDebugEnabled()) { + log.debug("Row has changed to " + editingRow); + } + getUi().getBaitType().requestFocus(); + } + + } + + @Override + protected void initTableUI(DefaultTableCellRenderer renderer) { + + JTable table = getUi().getTable(); + + UIHelper.setI18nTableHeaderRenderer( + table, + n("observe.content.baitsComposition.table.baitType"), + n("observe.content.baitsComposition.table.baitType.tip"), + n("observe.content.baitsComposition.table.baitSettingStatus"), + n("observe.content.baitsComposition.table.baitSettingStatus.tip"), + n("observe.content.baitsComposition.table.individualSize"), + n("observe.content.baitsComposition.table.individualSize.tip"), + n("observe.content.baitsComposition.table.individualWeight"), + n("observe.content.baitsComposition.table.individualWeight.tip"), + n("observe.content.baitsComposition.table.proportion"), + n("observe.content.baitsComposition.table.proportion.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, BaitTypeDto.class)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, BaitSettingStatusDto.class)); + UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 4, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + + // when model change in table, let's recompute the proportion sum + table.getModel().addTableModelListener(e -> { + int proportionSum = getBean().getBaitsCompositionProportionSum(); + getBean().setBaitsCompositionProportionSum(proportionSum); + }); + + } + + @Override + protected String getEditBeanIdToLoad() { + return getDataContext().getSelectedSetId(); + } + + @Override + protected void doPersist(SetLonglineGlobalCompositionDto bean) { + // fait par le doSave de LonglineGlobalCompositionUIHandler + } + + @Override + protected void loadEditBean(String beanId) { + // fait par le loadEditBean de LonglineGlobalCompositionUIHandler + } + + @Override + public void afterSave(boolean refresh) { + super.afterSave(refresh); + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BaitsCompositionUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BaitsCompositionUIModel.java new file mode 100644 index 0000000..b3fa3ce --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BaitsCompositionUIModel.java @@ -0,0 +1,94 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import fr.ird.observe.services.dto.longline.BaitsCompositionDto; +import fr.ird.observe.services.dto.longline.BaitsCompositionDtos; +import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; + +import java.util.Collection; +import java.util.List; + +/** + * Created on 12/6/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.9 + */ +public class BaitsCompositionUIModel extends ContentTableUIModel<SetLonglineGlobalCompositionDto, BaitsCompositionDto> { + + private static final long serialVersionUID = 1L; + + public BaitsCompositionUIModel(BaitsCompositionUI ui) { + super(SetLonglineGlobalCompositionDto.class, + BaitsCompositionDto.class, + new String[]{ + SetLonglineGlobalCompositionDto.PROPERTY_BAITS_COMPOSITION + }, + new String[]{BaitsCompositionDto.PROPERTY_BAIT_TYPE, + BaitsCompositionDto.PROPERTY_BAIT_SETTING_STATUS, + BaitsCompositionDto.PROPERTY_INDIVIDUAL_SIZE, + BaitsCompositionDto.PROPERTY_INDIVIDUAL_WEIGHT, + BaitsCompositionDto.PROPERTY_PROPORTION}); + + List<ContentTableMeta<BaitsCompositionDto>> metas = Lists.newArrayList( + ContentTableModel.newTableMeta(BaitsCompositionDto.class, BaitsCompositionDto.PROPERTY_BAIT_TYPE, false), + ContentTableModel.newTableMeta(BaitsCompositionDto.class, BaitsCompositionDto.PROPERTY_BAIT_SETTING_STATUS, false), + ContentTableModel.newTableMeta(BaitsCompositionDto.class, BaitsCompositionDto.PROPERTY_INDIVIDUAL_SIZE, false), + ContentTableModel.newTableMeta(BaitsCompositionDto.class, BaitsCompositionDto.PROPERTY_INDIVIDUAL_WEIGHT, false), + ContentTableModel.newTableMeta(BaitsCompositionDto.class, BaitsCompositionDto.PROPERTY_PROPORTION, false)); + + initModel(ui, metas); + + } + + @Override + protected ContentTableModel<SetLonglineGlobalCompositionDto, BaitsCompositionDto> createTableModel( + ObserveContentTableUI<SetLonglineGlobalCompositionDto, BaitsCompositionDto> ui, + List<ContentTableMeta<BaitsCompositionDto>> contentTableMetas) { + + return new ContentTableModel<SetLonglineGlobalCompositionDto, BaitsCompositionDto>(ui, contentTableMetas) { + private static final long serialVersionUID = 1L; + + @Override + protected Collection<BaitsCompositionDto> getChilds(SetLonglineGlobalCompositionDto bean) { + return bean.getBaitsComposition(); + } + + @Override + protected void load(BaitsCompositionDto source, BaitsCompositionDto target) { + BaitsCompositionDtos.copyBaitsCompositionDto(source, target); + } + + @Override + protected void setChilds(SetLonglineGlobalCompositionDto parent, List<BaitsCompositionDto> childs) { + parent.setBaitsComposition(childs); + } + }; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BranchlinesCompositionUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BranchlinesCompositionUI.jaxx new file mode 100644 index 0000000..768184d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BranchlinesCompositionUI.jaxx @@ -0,0 +1,130 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.table.ContentTableUI + superGenericType='SetLonglineGlobalCompositionDto, BranchlinesCompositionDto' + contentTitle='{n("observe.content.branchlinesComposition.title")}' + saveNewEntryText='{n("observe.content.branchlinesComposition.action.create")}' + saveNewEntryTip='{n("observe.content.branchlinesComposition.action.create.tip")}'> + + <style source="../../CommonTable.jcss"/> + + <import> + fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto + fr.ird.observe.services.dto.longline.BranchlinesCompositionDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.longline.LineTypeDto + fr.ird.observe.application.swing.ui.content.table.* + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <BranchlinesCompositionUIHandler id='handler'/> + + <!-- model --> + <BranchlinesCompositionUIModel id='model'/> + + <!-- edit bean --> + <SetLonglineGlobalCompositionDto id='bean'/> + + <!-- table edit bean --> + <BranchlinesCompositionDto id='tableEditBean'/> + + <!-- table model --> + <ContentTableModel id='tableModel'/> + + <!-- le validateur de l'écran --> + <BeanValidator id='validator' autoField='true' context='ui-update-branchlinesComposition' + beanClass='fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto' + errorTableModel='{getErrorTableModel()}'> + <field name="branchlinesComposition" component="editorPanel"/> + </BeanValidator> + + <!-- le validateur d'une entrée de tableau --> + <BeanValidator id='validatorTable' autoField='true' context='ui-update' + beanClass='fr.ird.observe.services.dto.longline.BranchlinesCompositionDto' + errorTableModel='{getErrorTableModel()}'/> + + <Table id='editorPanel' fill='both' insets='1'> + + <!-- topType --> + <row> + <cell> + <JLabel id='topTypeLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='topType' constructorParams='this' genericType='ReferentialReference<LineTypeDto>' _entityClass='LineTypeDto.class'/> + </cell> + </row> + + <!-- tracelineType --> + <row> + <cell> + <JLabel id='tracelineTypeLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='tracelineType' constructorParams='this' genericType='ReferentialReference<LineTypeDto>' _entityClass='LineTypeDto.class'/> + </cell> + </row> + + <!-- length --> + <row> + <cell> + <JLabel id='lengthLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='length' constructorParams='this'/> + </cell> + </row> + + <!-- proportion --> + <row> + <cell> + <JLabel id='proportionLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='proportion' constructorParams='this'/> + </cell> + </row> + + </Table> + + <Table id='extraZone' fill='both'> + + <!-- proportion sum --> + <row> + <cell> + <JLabel id='branchlinesCompositionProportionSumLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <JLabel id='branchlinesCompositionProportionSum'/> + </cell> + </row> + + </Table> + +</fr.ird.observe.application.swing.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BranchlinesCompositionUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BranchlinesCompositionUI.jcss new file mode 100644 index 0000000..3579780 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BranchlinesCompositionUI.jcss @@ -0,0 +1,78 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#topTypeLabel { + text:"observe.content.branchlinesComposition.topType"; + labelFor:{topType}; +} + +#topType { + property:{BranchlinesCompositionDto.PROPERTY_TOP_TYPE}; + selectedItem:{tableEditBean.getTopType()}; + _validatorLabel:{t("observe.content.branchlinesComposition.topType")}; +} + +#tracelineTypeLabel { + text:"observe.content.branchlinesComposition.tracelineType"; + labelFor:{tracelineType}; +} + +#tracelineType { + property:{BranchlinesCompositionDto.PROPERTY_TRACELINE_TYPE}; + selectedItem:{tableEditBean.getTracelineType()}; + _validatorLabel:{t("observe.content.branchlinesComposition.tracelineType")}; +} + +#lengthLabel { + text:"observe.content.branchlinesComposition.length"; + labelFor:{length}; +} + +#length { + property:{BranchlinesCompositionDto.PROPERTY_LENGTH}; + model:{tableEditBean.getLength()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL3_PATTERN}; + _validatorLabel:{t("observe.content.branchlinesComposition.length")}; +} + +#proportionLabel { + text:"observe.content.branchlinesComposition.proportion"; + labelFor:{proportion}; +} + +#proportion { + property:{BranchlinesCompositionDto.PROPERTY_PROPORTION}; + model:{tableEditBean.getProportion()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.branchlinesComposition.proportion")}; +} + +#branchlinesCompositionProportionSumLabel { + text:"observe.content.branchlinesComposition.proportionSum"; + labelFor:{branchlinesCompositionProportionSum}; +} + +#branchlinesCompositionProportionSum { + text:{getStringValue(bean.getBranchlinesCompositionProportionSum())}; + _validatorLabel:{t("observe.content.branchlinesComposition.proportionSum")}; + font-weight:bold; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BranchlinesCompositionUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BranchlinesCompositionUIHandler.java new file mode 100644 index 0000000..ac2f12e --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BranchlinesCompositionUIHandler.java @@ -0,0 +1,121 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.longline.BranchlinesCompositionDto; +import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto; +import fr.ird.observe.services.dto.referential.longline.HookSizeDto; +import fr.ird.observe.services.dto.referential.longline.HookTypeDto; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; + +import static org.nuiton.i18n.I18n.n; + +/** + * Created on 12/6/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.9 + */ +public class BranchlinesCompositionUIHandler extends ContentTableUIHandler<SetLonglineGlobalCompositionDto, BranchlinesCompositionDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(BranchlinesCompositionUIHandler.class); + + public BranchlinesCompositionUIHandler(BranchlinesCompositionUI ui) { + super(ui, DataContextType.SetLongline); + } + + @Override + public BranchlinesCompositionUI getUi() { + return (BranchlinesCompositionUI) super.getUi(); + } + + @Override + protected void onSelectedRowChanged(int editingRow, BranchlinesCompositionDto bean, boolean create) { + + if (getTableModel().isEditable()) { + if (log.isDebugEnabled()) { + log.debug("Row has changed to " + editingRow); + } + getUi().getTopType().requestFocus(); + } + + } + + @Override + protected void initTableUI(DefaultTableCellRenderer renderer) { + + JTable table = getUi().getTable(); + + UIHelper.setI18nTableHeaderRenderer( + table, + n("observe.content.branchlinesComposition.table.topType"), + n("observe.content.branchlinesComposition.table.topType.tip"), + n("observe.content.branchlinesComposition.table.tracelineType"), + n("observe.content.branchlinesComposition.table.tracelineType.tip"), + n("observe.content.branchlinesComposition.table.length"), + n("observe.content.branchlinesComposition.table.length.tip"), + n("observe.content.branchlinesComposition.table.proportion"), + n("observe.content.branchlinesComposition.table.proportion.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, HookTypeDto.class)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, HookSizeDto.class)); + UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + + // when model change in table, let's recompute the proportion sum + table.getModel().addTableModelListener(e -> { + int proportionSum = getBean().getBranchlinesCompositionProportionSum(); + getBean().setBranchlinesCompositionProportionSum(proportionSum); + }); + + } + + @Override + protected String getEditBeanIdToLoad() { + return getDataContext().getSelectedSetId(); + } + + @Override + public void afterSave(boolean refresh) { + super.afterSave(refresh); + } + + @Override + protected void doPersist(SetLonglineGlobalCompositionDto bean) { + // fait par le doSave de LonglineGlobalCompositionUIHandler + } + + @Override + protected void loadEditBean(String beanId) { + // fait par le loadEditBean de LonglineGlobalCompositionUIHandler + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BranchlinesCompositionUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BranchlinesCompositionUIModel.java new file mode 100644 index 0000000..06d14b3 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/BranchlinesCompositionUIModel.java @@ -0,0 +1,93 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import fr.ird.observe.services.dto.longline.BranchlinesCompositionDto; +import fr.ird.observe.services.dto.longline.BranchlinesCompositionDtos; +import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; + +import java.util.Collection; +import java.util.List; + +/** + * Created on 12/6/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.9 + */ +public class BranchlinesCompositionUIModel extends ContentTableUIModel<SetLonglineGlobalCompositionDto, BranchlinesCompositionDto> { + + private static final long serialVersionUID = 1L; + + public BranchlinesCompositionUIModel(BranchlinesCompositionUI ui) { + super(SetLonglineGlobalCompositionDto.class, + BranchlinesCompositionDto.class, + new String[]{ + SetLonglineGlobalCompositionDto.PROPERTY_BRANCHLINES_COMPOSITION + }, + new String[]{BranchlinesCompositionDto.PROPERTY_TOP_TYPE, + BranchlinesCompositionDto.PROPERTY_TRACELINE_TYPE, + BranchlinesCompositionDto.PROPERTY_LENGTH, + BranchlinesCompositionDto.PROPERTY_PROPORTION}); + + List<ContentTableMeta<BranchlinesCompositionDto>> metas = Lists.newArrayList( + ContentTableModel.newTableMeta(BranchlinesCompositionDto.class, BranchlinesCompositionDto.PROPERTY_TOP_TYPE, false), + ContentTableModel.newTableMeta(BranchlinesCompositionDto.class, BranchlinesCompositionDto.PROPERTY_TRACELINE_TYPE, false), + ContentTableModel.newTableMeta(BranchlinesCompositionDto.class, BranchlinesCompositionDto.PROPERTY_LENGTH, false), + ContentTableModel.newTableMeta(BranchlinesCompositionDto.class, BranchlinesCompositionDto.PROPERTY_PROPORTION, false)); + + initModel(ui, metas); + + } + + + @Override + protected ContentTableModel<SetLonglineGlobalCompositionDto, BranchlinesCompositionDto> createTableModel( + ObserveContentTableUI<SetLonglineGlobalCompositionDto, BranchlinesCompositionDto> ui, + List<ContentTableMeta<BranchlinesCompositionDto>> contentTableMetas) { + + return new ContentTableModel<SetLonglineGlobalCompositionDto, BranchlinesCompositionDto>(ui, contentTableMetas) { + private static final long serialVersionUID = 1L; + + @Override + protected Collection<BranchlinesCompositionDto> getChilds(SetLonglineGlobalCompositionDto bean) { + return bean.getBranchlinesComposition(); + } + + @Override + protected void load(BranchlinesCompositionDto source, BranchlinesCompositionDto target) { + BranchlinesCompositionDtos.copyBranchlinesCompositionDto(source, target); + } + + @Override + protected void setChilds(SetLonglineGlobalCompositionDto parent, List<BranchlinesCompositionDto> childs) { + parent.setBranchlinesComposition(childs); + } + }; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchAcquisitionModeEnum.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchAcquisitionModeEnum.java new file mode 100644 index 0000000..591cc6f --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchAcquisitionModeEnum.java @@ -0,0 +1,66 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 9/10/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.7 + */ +public enum CatchAcquisitionModeEnum { + + INDIVIDUAL(n("observe.catchAcquisitionModeEnum.INDIVIDUAL")), + + GROUPED(n("observe.catchAcquisitionModeEnum.GROUPED")); + + private final String i18nKey; + + CatchAcquisitionModeEnum(String i18nKey) { + this.i18nKey = i18nKey; + } + + public static CatchAcquisitionModeEnum valueOf(int ordinal) + throws IllegalArgumentException { + for (CatchAcquisitionModeEnum o : values()) { + if (o.ordinal() == ordinal) { + return o; + } + } + throw new IllegalArgumentException( + "could not find a " + CatchAcquisitionModeEnum.class.getSimpleName() + + " value for ordinal " + ordinal); + } + + public String getI18nKey() { + return i18nKey; + } + + @Override + public String toString() { + return t(i18nKey); + } +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchLonglineContentTableUIInitializer.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchLonglineContentTableUIInitializer.java new file mode 100644 index 0000000..ac0fa0a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchLonglineContentTableUIInitializer.java @@ -0,0 +1,65 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + + +import fr.ird.observe.services.dto.longline.CatchLonglineDto; +import fr.ird.observe.services.dto.longline.SetLonglineCatchDto; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIInitializer; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.jaxx.application.bean.JavaBeanObjectUtil; + +import javax.swing.JCheckBox; + +/** + * Created on 3/17/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.15 + */ +public class CatchLonglineContentTableUIInitializer extends ContentTableUIInitializer<SetLonglineCatchDto, CatchLonglineDto, CatchLonglineUI> { + + /** Logger. */ + private static final Log log = LogFactory.getLog(CatchLonglineContentTableUIInitializer.class); + + public CatchLonglineContentTableUIInitializer(CatchLonglineUI ui) { + super(ui); + } + + @Override + protected void init(JCheckBox editor) { + if (log.isDebugEnabled()) { + log.debug("init simple boolean editor " + editor.getName()); + } + super.init(editor); + final String propertyName = (String) editor.getClientProperty("branchlineBeanPropertyName"); + if (propertyName != null) { + editor.addItemListener(event -> { + Boolean newValue = ((JCheckBox) event.getSource()).isSelected(); + JavaBeanObjectUtil.setProperty(ui.getBranchlineBean(), propertyName, newValue); + }); + } + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchLonglineTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchLonglineTableModel.java new file mode 100644 index 0000000..fe59f15 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchLonglineTableModel.java @@ -0,0 +1,161 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.longline.CatchLonglineDto; +import fr.ird.observe.services.dto.longline.CatchLonglineDtos; +import fr.ird.observe.services.dto.longline.SetLonglineCatchDto; +import fr.ird.observe.services.dto.longline.SizeMeasureDto; +import fr.ird.observe.services.dto.longline.WeightMeasureDto; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; + +/** + * Created on 12/4/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.8 + */ +public class CatchLonglineTableModel extends ContentTableModel<SetLonglineCatchDto, CatchLonglineDto> { + + /** Logger. */ + private static final Log log = LogFactory.getLog(CatchLonglineTableModel.class); + + private static final long serialVersionUID = 1L; + + public CatchLonglineTableModel(ObserveContentTableUI<SetLonglineCatchDto, CatchLonglineDto> context, + List<ContentTableMeta<CatchLonglineDto>> contentTableMetas) { + super(context, contentTableMetas); + } + + @Override + public void addNewEntry() { + + int editingRow = getSelectedRow(); + + if (editingRow > -1) { + + // store sizes and weights for the selected row + // before creating a new one ? + CatchLonglineUIModel model = getModel(); + model.getSizeMeasuresTableModel().storeInCacheForRow(editingRow); + model.getWeightMeasuresTableModel().storeInCacheForRow(editingRow); + + } + + super.addNewEntry(); + } + + @Override + public void updateRowFromEditBean() { + + // store sizes and weights for the selected row + + int editingRow = getSelectedRow(); + + CatchLonglineUIModel model = getModel(); + + model.getSizeMeasuresTableModel().storeInCacheForRow(editingRow); + + List<SizeMeasureDto> sizeMeasures = model.getSizeMeasuresTableModel().getData().stream() + .filter(sizeMeasureDto -> sizeMeasureDto.getSizeMeasureType() != null) + .collect(Collectors.toList()); + + getRowBean().setSizeMeasure(sizeMeasures); + + model.getWeightMeasuresTableModel().storeInCacheForRow(editingRow); + + List<WeightMeasureDto> weightMeasures = model.getWeightMeasuresTableModel().getData().stream() + .filter(weightMeasureDto -> weightMeasureDto.getWeightMeasureType() != null) + .collect(Collectors.toList()); + + getRowBean().setWeightMeasure(weightMeasures); + + super.updateRowFromEditBean(); + + + } + + @Override + protected void removeRow(int row) { + super.removeRow(row); + + // remove sizes and weights for the deleted row + // also update rows to row - 1 (when after the deleted row) + CatchLonglineUIModel model = getModel(); + model.getSizeMeasuresTableModel().removeCacheForRow(row); + model.getWeightMeasuresTableModel().removeCacheForRow(row); + + } + + @Override + protected void setChilds(SetLonglineCatchDto parent, List<CatchLonglineDto> childs) { + parent.setCatchLongline(childs); + } + + @Override + public void resetEditBean() { + + int row = getSelectedRow(); + if (log.isInfoEnabled()) { + log.info("Reset edit bean at row: " + row); + } + CatchLonglineUIModel model = getModel(); + model.getSizeMeasuresTableModel().resetCacheForRow(row); + model.getWeightMeasuresTableModel().resetCacheForRow(row); + + super.resetEditBean(); + + } + + @Override + protected Collection<CatchLonglineDto> getChilds(SetLonglineCatchDto bean) { + return bean.getCatchLongline(); + } + + @Override + protected void load(CatchLonglineDto source, CatchLonglineDto target) { + CatchLonglineDtos.copyCatchLonglineDto(source, target); + } + + @Override + protected void resetRow(int row) { + super.resetRow(row); + + CatchLonglineUIModel model = getModel(); + model.getSizeMeasuresTableModel().resetCacheForRow(row); + model.getWeightMeasuresTableModel().resetCacheForRow(row); + } + + @Override + protected CatchLonglineUIModel getModel() { + return (CatchLonglineUIModel) super.getModel(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchLonglineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchLonglineUI.jaxx new file mode 100644 index 0000000..84aee5a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchLonglineUI.jaxx @@ -0,0 +1,434 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.table.ContentTableUI superGenericType='SetLonglineCatchDto, CatchLonglineDto' + contentTitle='{n("observe.content.catchLongline.title")}' + newEntryText='{n("observe.content.catchLongline.action.new")}' + newEntryTip='{n("observe.content.catchLongline.action.new.tip")}' + saveNewEntryText='{n("observe.content.catchLongline.action.create")}' + saveNewEntryTip='{n("observe.content.catchLongline.action.create.tip")}'> + + <style source="../../CommonTable.jcss"/> + + <import> + fr.ird.observe.services.dto.DataReference + fr.ird.observe.services.dto.CommentableDto + fr.ird.observe.services.dto.longline.BasketDto + fr.ird.observe.services.dto.longline.BranchlineDto + fr.ird.observe.services.dto.longline.CatchLonglineDto + fr.ird.observe.services.dto.longline.SectionDto + fr.ird.observe.services.dto.longline.SetLonglineCatchDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.SpeciesDto + fr.ird.observe.services.dto.referential.SexDto + fr.ird.observe.services.dto.referential.longline.BaitHaulingStatusDto + fr.ird.observe.services.dto.referential.longline.CatchFateLonglineDto + fr.ird.observe.services.dto.referential.longline.HealthnessDto + fr.ird.observe.services.dto.referential.longline.HookPositionDto + fr.ird.observe.services.dto.referential.longline.MaturityStatusDto + fr.ird.observe.services.dto.referential.longline.StomacFullnessDto + fr.ird.observe.application.swing.ui.content.table.* + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + org.nuiton.jaxx.widgets.select.FilterableDoubleList + org.nuiton.jaxx.widgets.datetime.DateTimeEditor + + java.awt.Dimension + + java.util.Collection + + org.apache.commons.lang3.BooleanUtils + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <CatchLonglineUIHandler id='handler'/> + + <!-- model --> + <CatchLonglineUIModel id='model'/> + + <SizeMeasuresTableModel id='sizeMeasuresTableModel' initializer="getModel().getSizeMeasuresTableModel()"/> + + <WeightMeasuresTableModel id='weightMeasuresTableModel' initializer="getModel().getWeightMeasuresTableModel()"/> + + <!-- edit bean --> + <SetLonglineCatchDto id='bean'/> + + <!-- table edit bean --> + <CatchLonglineDto id='tableEditBean'/> + + <!-- table model --> + <ContentTableModel id='tableModel'/> + + <!-- edit branchline --> + <BranchlineDto id='branchlineBean' initializer='new BranchlineDto()'/> + + <!-- le validateur de l'écran --> + <BeanValidator id='validator' context='ui-update' + beanClass='fr.ird.observe.services.dto.longline.SetLonglineCatchDto' + errorTableModel='{getErrorTableModel()}'> + </BeanValidator> + + <!-- le validateur d'une entrée de tableau --> + <BeanValidator id='validatorTable' autoField='true' context='ui-update' + beanClass='fr.ird.observe.services.dto.longline.CatchLonglineDto' + errorTableModel='{getErrorTableModel()}' + parentValidator='{validator}'/> + + <!-- le validateur de la branchline --> + <BeanValidator id='branchlineValidator' context='ui-update-catchLongline' + beanClass='fr.ird.observe.services.dto.longline.BranchlineDto' + errorTableModel='{getErrorTableModel()}' + parentValidator='{validator}'> + <field name='depthRecorder' component='depthRecorder'/> + <field name='hookLost' component='hookLost'/> + <field name='traceCutOff' component='traceCutOff'/> + <field name='timer' component='timer'/> + <field name='timeSinceContact' component='timeSinceContact'/> + <field name='timerTimeOnBoard' component='timerTimeOnBoard'/> + <field name='baitHaulingStatus' component='baitHaulingStatus'/> + + </BeanValidator> + + <JPopupMenu id='sizeMeasuresTablePopup'> + <JMenuItem id='addSizeMeasure' onActionPerformed='getHandler().addSizeMeasure()'/> + <JMenuItem id='deleteSelectedSizeMeasure' onActionPerformed='getHandler().deleteSelectedSizeMeasure()'/> + </JPopupMenu> + + <JPopupMenu id='weightMeasuresTablePopup'> + <JMenuItem id='addWeightMeasure' onActionPerformed='getHandler().addWeightMeasure()'/> + <JMenuItem id='deleteSelectedWeightMeasure' onActionPerformed='getHandler().deleteSelectedWeightMeasure()'/> + </JPopupMenu> + + <ButtonGroup id='acquisitionModeGroup' + onStateChanged='getHandler().updateCatchAcquisitionMode((CatchAcquisitionModeEnum) acquisitionModeGroup.getSelectedValue())'/> + + <Table id='editorPanel' fill='both' insets='0'> + <row> + <cell weightx="1" weighty="1"> + <JTabbedPane id='fishingOperationTabPane'> + <tab id='caracteristicTab'> + <Table id='editForm' fill='both' insets='1'> + + <row> + <cell columns="4"> + <JPanel layout="{new GridLayout()}"> + + <!-- acquisition Mode --> + <JPanel id='acquisitionModePanel'> + <JRadioButton id='acquisitionModeIndividual'/> + <JRadioButton id='acquisitionModeGrouped'/> + </JPanel> + + <!-- location on longline --> + <Table id="locationOnLonglinePanel"> + <row> + <cell anchor="west"> + <JLabel id='sectionLabel'/> + </cell> + <cell fill="both" weightx="1"> + <BeanComboBox id='section' genericType='DataReference<SectionDto>' _entityClass='SectionDto.class' constructorParams='this'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='basketLabel'/> + </cell> + <cell fill="both" weightx="1"> + <BeanComboBox id='basket' genericType='DataReference<BasketDto>' _entityClass='BasketDto.class' constructorParams='this'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='branchlineLabel'/> + </cell> + <cell fill="both" weightx="1"> + <BeanComboBox id='branchline' genericType='DataReference<BranchlineDto>' _entityClass='BranchlineDto.class' constructorParams='this'/> + </cell> + </row> + </Table> + </JPanel> + </cell> + </row> + + <!-- speciesCatch --> + <row> + <cell> + <JLabel id='speciesCatchLabel'/> + </cell> + <cell weightx='1' anchor='east' columns="3"> + <BeanComboBox id='speciesCatch' genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class' constructorParams='this'/> + </cell> + + </row> + + <!-- count --> + <!-- total weight --> + <row> + <cell> + <JLabel id='countLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='count' constructorParams='this'/> + </cell> + <cell> + <JLabel id='totalWeightLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='totalWeight' constructorParams='this'/> + </cell> + </row> + + <!-- catch healthness --> + <!-- hook position --> + <row> + <cell> + <JLabel id='catchHealthnessLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='catchHealthness' constructorParams='this' genericType='ReferentialReference<HealthnessDto>' _entityClass='HealthnessDto.class'/> + </cell> + <cell> + <JLabel id='hookPositionLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='hookPosition' constructorParams='this' genericType='ReferentialReference<HookPositionDto>' _entityClass='HookPositionDto.class'/> + </cell> + </row> + + <!-- catch fate --> + <!-- discard healthness --> + <row> + <cell> + <JLabel id='catchFateLonglineLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='catchFateLongline' constructorParams='this' genericType='ReferentialReference<CatchFateLonglineDto>' _entityClass='CatchFateLonglineDto.class'/> + </cell> + <cell> + <JLabel id='discardHealthnessLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='discardHealthness' constructorParams='this' genericType='ReferentialReference<HealthnessDto>' _entityClass='HealthnessDto.class'/> + </cell> + </row> + + <!-- hookWhenDiscarded --> + <!-- photoReferences --> + <row> + <cell anchor='west' fill="both" columns="2"> + <JCheckBox id='hookWhenDiscarded'/> + </cell> + <cell anchor='west'> + <JLabel id='photoReferencesLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both"> + <JPanel layout='{new BorderLayout()}'> + <JToolBar id='photoReferencesToolbar' constraints='BorderLayout.WEST'> + <JButton id='resetPhotoReferences' styleClass='resetButton'/> + </JToolBar> + <JTextField id='photoReferences' constraints='BorderLayout.CENTER'/> + </JPanel> + </cell> + </row> + + </Table> + </tab> + + <tab id='depredatedFormTab'> + + <Table id='depredatedForm' fill='both' insets='1'> + + <!-- depredated --> + <row> + <cell anchor='west' fill="both"> + <JCheckBox id='depredated'/> + </cell> + </row> + + <!-- beatDiameter --> + <row> + <cell> + <JLabel id='beatDiameterLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='beatDiameter' constructorParams='this'/> + </cell> + </row> + + <!-- predator --> + <row> + <cell columns="2" fill="both" weighty="0.7"> + <JScrollPane id='predatorPane'> + <FilterableDoubleList id='predator' genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class'/> + </JScrollPane> + </cell> + </row> + + </Table> + </tab> + + <tab id='foodAndSexualFormTab'> + + <JPanel layout="{new BorderLayout()}"> + <Table id='foodAndSexualForm' fill='both' insets='1' constraints='BorderLayout.NORTH'> + + <!-- stomac fullness --> + <row> + <cell> + <JLabel id='stomacFullnessLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='stomacFullness' constructorParams='this' genericType='ReferentialReference<StomacFullnessDto>' _entityClass='StomacFullnessDto.class'/> + </cell> + </row> + + <!-- sex --> + <row> + <cell> + <JLabel id='sexLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='sex' constructorParams='this' genericType='ReferentialReference<SexDto>' _entityClass='SexDto.class'/> + </cell> + </row> + + <!-- maturity status --> + <row> + <cell> + <JLabel id='maturityStatusLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='maturityStatus' constructorParams='this' genericType='ReferentialReference<MaturityStatusDto>' _entityClass='MaturityStatusDto.class'/> + </cell> + </row> + + <!-- gonadeWeight --> + <row> + <cell> + <JLabel id='gonadeWeightLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='gonadeWeight' constructorParams='this'/> + </cell> + </row> + + </Table> + </JPanel> + + </tab> + + <tab id='sizeMeasuresFormTab'> + + <JScrollPane id='sizeMeasuresScrollPane'> + <JTable id='sizeMeasuresTable'/> + </JScrollPane> + + </tab> + + <tab id='weightMeasuresFormTab'> + + <JScrollPane id='weightMeasuresScrollPane'> + <JTable id='weightMeasuresTable'/> + </JScrollPane> + + </tab> + + <tab id='branchlineFormTab'> + + <JPanel layout="{new BorderLayout()}"> + <Table id='branchlineForm' fill='both' insets='3' constraints='BorderLayout.NORTH'> + + <!-- depthRecorder --> + <!-- hookLost --> + <!-- traceCutOff --> + <row> + <cell columns="3"> + <JPanel layout="{new GridLayout()}"> + <JCheckBox id='depthRecorder'/> + <JCheckBox id='hookLost'/> + <JCheckBox id='traceCutOff'/> + </JPanel> + </cell> + </row> + + <!-- timer --> + <!-- timeSinceContact --> + <row> + <cell anchor='east'> + <JCheckBox id='timer'/> + </cell> + <cell> + <JLabel id='timeSinceContactLabel'/> + </cell> + <cell> + <NumberEditor id='timeSinceContact' constructorParams='this'/> + </cell> + </row> + + <!-- timerTimeOnBoard --> + <row> + <cell columns="3"> + <DateTimeEditor id='timerTimeOnBoard' constructorParams='this'/> + </cell> + </row> + + <!-- baitHaulingStatus --> + <row> + <cell anchor='west'> + <JLabel id='baitHaulingStatusLabel'/> + </cell> + <cell anchor='east' weightx="1" fill="both" columns="2"> + <BeanComboBox id='baitHaulingStatus' constructorParams='this' genericType='ReferentialReference<BaitHaulingStatusDto>' _entityClass='BaitHaulingStatusDto.class'/> + </cell> + </row> + + <row> + <cell columns="3"> + <JPanel id='branchlineActions' layout="{new GridLayout()}"> + <JButton id='resetBranchline' onActionPerformed='getHandler().resetBranchline()'/> + <JButton id='saveBranchline' onActionPerformed='getHandler().saveBranchline()'/> + </JPanel> + </cell> + </row> + + </Table> + </JPanel> + + </tab> + + </JTabbedPane> + </cell> + </row> + <row> + <cell weighty='1'> + <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2'/> + </JScrollPane> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchLonglineUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchLonglineUI.jcss new file mode 100644 index 0000000..251fb3d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchLonglineUI.jcss @@ -0,0 +1,475 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#model { + valid:{validator.isValid() && validatorTable.isValid() && getSizeMeasuresTableModel().isValid() && getWeightMeasuresTableModel().isValid()}; + canSaveRow:{validatorTable.isChanged() && validatorTable.isValid() && getSizeMeasuresTableModel().isValid() && getWeightMeasuresTableModel().isValid()}; + /*canSaveRow:{getHandler().canSaveRow(tableModel.isModified() , validatorTable.isChanged() , validatorTable.isValid() , getSizeMeasuresTableModel().isValid() , getWeightMeasuresTableModel().isValid())};*/ + canResetRow:{validatorTable.isChanged()}; + /*canResetRow:{getHandler().canResetRow(tableModel.isModified() , validatorTable.isChanged())};*/ +} + +/* ***************************************************************************** */ +/* CARACTERISTIC TAB ********************************************************** */ +/* ***************************************************************************** */ + +#caracteristicTab { + title:{t("observe.content.catchLongline.tab.caracteristics")}; + icon:{handler.getErrorIconIfFalse(model.isCaracteristicsTabValid())}; +} + +#acquisitionModeGroup { + selectedValue:{CatchAcquisitionModeEnum.valueOf(tableEditBean.getAcquisitionMode())}; +} + +#acquisitionModePanel { + border:{new TitledBorder(t("observe.content.catchLongline.acquisitionMode"))}; + layout:{new GridLayout(0,1)}; +} + +#acquisitionModeIndividual { + buttonGroup:acquisitionModeGroup; + value:{CatchAcquisitionModeEnum.INDIVIDUAL}; + text:{CatchAcquisitionModeEnum.INDIVIDUAL.getI18nKey()}; + selected:{tableEditBean.getAcquisitionMode() == 0}; + enabled:{!tableModel.isEditable() || tableModel.isCreate()}; +} + +#acquisitionModeGrouped { + buttonGroup:acquisitionModeGroup; + value:{CatchAcquisitionModeEnum.GROUPED}; + text:{CatchAcquisitionModeEnum.GROUPED.getI18nKey()}; + selected:{tableEditBean.getAcquisitionMode() == 1}; + enabled:{!tableModel.isEditable() || tableModel.isCreate()}; +} + +#locationOnLonglinePanel { + border:{new TitledBorder(t("observe.content.catchLongline.locationOnLongline"))}; +} +#sectionLabel { + text:"observe.content.catchLongline.section"; + labelFor:{section}; +} + +#section { + property:{CatchLonglineDto.PROPERTY_SECTION}; + selectedItem:{tableEditBean.getSection()}; + _listNoLoad:{true}; +} + +#basketLabel { + text:"observe.content.catchLongline.basket"; + labelFor:{basket}; +} + +#basket { + property:{CatchLonglineDto.PROPERTY_BASKET}; + selectedItem:{tableEditBean.getBasket()}; + _listNoLoad:{true}; +} + +#branchlineLabel { + text:"observe.content.catchLongline.branchline"; + labelFor:{branchline}; +} + +#branchline { + property:{CatchLonglineDto.PROPERTY_BRANCHLINE}; + selectedItem:{tableEditBean.getBranchline()}; + _listNoLoad:{true}; +} + +#speciesCatchLabel { + text:"observe.content.catchLongline.speciesCatch"; + labelFor:{speciesCatch}; +} + +#speciesCatch { + property:{CatchLonglineDto.PROPERTY_SPECIES_CATCH}; + selectedItem:{tableEditBean.getSpeciesCatch()}; + _validatorLabel:{t("observe.content.catchLongline.speciesCatch")}; +} + +#photoReferencesLabel{ + text:"observe.content.catchLongline.photoReferences"; + labelFor:{photoReferences}; +} + +#resetPhotoReferences{ + toolTipText:"observe.content.catchLongline.action.reset.photoReferences.tip"; + _resetTablePropertyName:{CatchLonglineDto.PROPERTY_PHOTO_REFERENCES}; +} + +#photoReferences { + text:{getStringValue(tableEditBean.getPhotoReferences())}; + _tablePropertyName:{CatchLonglineDto.PROPERTY_PHOTO_REFERENCES}; +} + +#countLabel { + text:"observe.content.catchLongline.count"; + labelFor:{count}; +} + +#count { + property:{CatchLonglineDto.PROPERTY_COUNT}; + model:{tableEditBean.getCount()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel: {t("observe.content.catchLongline.count")}; +} + +#totalWeightLabel { + text:"observe.content.catchLongline.totalWeight"; + labelFor:{totalWeight}; +} + +#totalWeight { + property:{CatchLonglineDto.PROPERTY_TOTAL_WEIGHT}; + model:{tableEditBean.getTotalWeight()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL3_PATTERN}; + _validatorLabel: {t("observe.content.catchLongline.totalWeight")}; +} + +#hookWhenDiscarded { + horizontalTextPosition:{JCheckBox.LEFT}; + text:"observe.content.catchLongline.hookWhenDiscarded"; + _tablePropertyName:{CatchLonglineDto.PROPERTY_HOOK_WHEN_DISCARDED}; + selected:{BooleanUtils.isTrue(tableEditBean.getHookWhenDiscarded())}; +} + +#catchFateLonglineLabel { + text:"observe.content.catchLongline.catchFateLongline"; + labelFor:{catchFateLongline}; +} + +#catchFateLongline { + property:{CatchLonglineDto.PROPERTY_CATCH_FATE_LONGLINE}; + selectedItem:{tableEditBean.getCatchFateLongline()}; + _validatorLabel: {t("observe.content.catchLongline.catchFateLongline")}; +} + +#catchHealthnessLabel { + text:"observe.content.catchLongline.catchHealthness"; + labelFor:{catchHealthness}; +} + +#catchHealthness { + property:{CatchLonglineDto.PROPERTY_CATCH_HEALTHNESS}; + selectedItem:{tableEditBean.getCatchHealthness()}; + _validatorLabel: {t("observe.content.catchLongline.catchHealthness")}; +} + +#discardHealthnessLabel { + text:"observe.content.catchLongline.discardHealthness"; + labelFor:{discardHealthness}; +} + +#discardHealthness { + property:{CatchLonglineDto.PROPERTY_DISCARD_HEALTHNESS}; + selectedItem:{tableEditBean.getDiscardHealthness()}; + _validatorLabel: {t("observe.content.catchLongline.discardHealthness")}; +} + +#catchFateLonglineLabel { + text:"observe.content.catchLongline.catchFateLongline"; + labelFor:{catchFateLongline}; +} + +#catchFateLongline { + property:{CatchLonglineDto.PROPERTY_CATCH_FATE_LONGLINE}; + selectedItem:{tableEditBean.getCatchFateLongline()}; + _validatorLabel: {t("observe.content.catchLongline.catchFateLongline")}; +} + +#hookPositionLabel { + text:"observe.content.catchLongline.hookPosition"; + labelFor:{hookPosition}; +} + +#hookPosition { + property:{CatchLonglineDto.PROPERTY_HOOK_POSITION}; + selectedItem:{tableEditBean.getHookPosition()}; + _validatorLabel: {t("observe.content.catchLongline.hookPosition")}; +} + +#comment { + columnHeaderView:{new JLabel(t("observe.content.catchLongline.comment"))}; +} + +#comment2 { + _tablePropertyName: {CommentableDto.PROPERTY_COMMENT}; + text:{getStringValue(tableEditBean.getComment())}; +} + +/* ***************************************************************************** */ +/* DEPREDATED TAB ************************************************************* */ +/* ***************************************************************************** */ + +#depredatedFormTab { + title:{t("observe.content.catchLongline.tab.depredated")}; + icon:{handler.getErrorIconIfFalse(model.isDepredatedTabValid())}; +} + +#beatDiameterLabel { + text:"observe.content.catchLongline.beatDiameter"; + labelFor:{beatDiameter}; +} + +#beatDiameter { + property:{CatchLonglineDto.PROPERTY_BEAT_DIAMETER}; + model:{tableEditBean.getBeatDiameter()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL3_PATTERN}; + _validatorLabel: {t("observe.content.catchLongline.beatDiameter")}; +} + +#depredated { + horizontalTextPosition:{JCheckBox.LEFT}; + text:"observe.content.catchLongline.depredated"; + _tablePropertyName:{CatchLonglineDto.PROPERTY_DEPREDATED}; + selected:{BooleanUtils.isTrue(tableEditBean.getDepredated())}; +} + +#predatorPane { + minimumSize:{new Dimension(10,150)}; +} + +#predator { + property: predator; + selected:{(Collection)tableEditBean.getPredator()}; + _validatorLabel: {t("observe.content.catchLongline.predator")}; + showListLabel: true; + universeLabel:{t("observe.content.catchLongline.availablePredator")}; + selectedLabel:{t("observe.content.catchLongline.selectedPredator")}; +} + +/* ***************************************************************************** */ +/* FOOD AND SEXUAL TAB ******************************************************** */ +/* ***************************************************************************** */ + +#foodAndSexualFormTab { + title:{t("observe.content.catchLongline.tab.foodAndSexual")}; + icon:{handler.getErrorIconIfFalse(model.isFoodAndSexualTabValid())}; +} + +#foodAndSexualForm { + border:{new TitledBorder( (String) null)}; +} + +#sexLabel { + text:"observe.content.catchLongline.sex"; + labelFor:{sex}; +} + +#sex { + property:{CatchLonglineDto.PROPERTY_SEX}; + selectedItem:{tableEditBean.getSex()}; + _validatorLabel:{t("observe.content.catchLongline.sex")}; +} + +#stomacFullnessLabel { + text:"observe.content.catchLongline.stomacFullness"; + labelFor:{stomacFullness}; +} + +#stomacFullness { + property:{CatchLonglineDto.PROPERTY_STOMAC_FULLNESS}; + selectedItem:{tableEditBean.getStomacFullness()}; + _validatorLabel:{t("observe.content.catchLongline.stomacFullness")}; +} + +#maturityStatusLabel { + text:"observe.content.catchLongline.maturityStatus"; + labelFor:{maturityStatus}; +} + +#maturityStatus { + property:{CatchLonglineDto.PROPERTY_MATURITY_STATUS}; + selectedItem:{tableEditBean.getMaturityStatus()}; + _validatorLabel:{t("observe.content.catchLongline.maturityStatus")}; +} + +#gonadeWeightLabel { + text:"observe.content.catchLongline.gonadeWeight"; + labelFor:{gonadeWeight}; +} + +#gonadeWeight { + property:{CatchLonglineDto.PROPERTY_GONADE_WEIGHT}; + model:{tableEditBean.getGonadeWeight()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL3_PATTERN}; + _validatorLabel:{t("observe.content.catchLongline.gonadeWeight")}; +} + +/* ***************************************************************************** */ +/* SIZE MEASURES TAB ********************************************************** */ +/* ***************************************************************************** */ + +#sizeMeasuresFormTab { + title:{t("observe.content.catchLongline.tab.sizeMeasures")}; + icon:{handler.getErrorIconIfFalse(sizeMeasuresTableModel.isValid())}; +} + +#sizeMeasuresTable { + model: {sizeMeasuresTableModel}; +} + +#addSizeMeasure { + text: "observe.content.catchLongline.action.addSizeMeasure"; + toolTipText: "observe.content.catchLongline.action.addSizeMeasure.tip"; + actionIcon: add; +} + +#deleteSelectedSizeMeasure { + text: "observe.content.catchLongline.action.deleteSelectedSizeMeasure"; + toolTipText: "observe.content.catchLongline.action.deleteSelectedSizeMeasure.tip"; + actionIcon: delete; +} + +/* ***************************************************************************** */ +/* WEIGHT MEASURES TAB ******************************************************** */ +/* ***************************************************************************** */ + +#weightMeasuresFormTab { + title:{t("observe.content.catchLongline.tab.weightMeasures")}; + icon:{handler.getErrorIconIfFalse(weightMeasuresTableModel.isValid())}; +} + +#weightMeasuresTable { + model: {weightMeasuresTableModel}; +} + +#addWeightMeasure { + text: "observe.content.catchLongline.action.addWeightMeasure"; + toolTipText: "observe.content.catchLongline.action.addWeightMeasure.tip"; + actionIcon: add; +} + +#deleteSelectedWeightMeasure { + text: "observe.content.catchLongline.action.deleteSelectedWeightMeasure"; + toolTipText: "observe.content.catchLongline.action.deleteSelectedWeightMeasure.tip"; + actionIcon: delete; +} + +/* ***************************************************************************** */ +/* BRANCHLINE TAB ************************************************************* */ +/* ***************************************************************************** */ + +#branchlineFormTab { + title:{t("observe.content.catchLongline.tab.branchline")}; + icon:{handler.getErrorIconIfFalse(model.isBranchlineTabValid())}; + enabled:{tableEditBean.getBranchline() != null}; +} + +#branchlineForm { + border:{new TitledBorder( (String) null)}; + visible:{tableEditBean.getBranchline() != null}; +} + + +#depthRecorder { + horizontalTextPosition:{JCheckBox.LEFT}; + text:"observe.content.branchline.depthRecorder"; + _branchlineBeanPropertyName:{BranchlineDto.PROPERTY_DEPTH_RECORDER}; + selected:{BooleanUtils.isTrue(branchlineBean.getDepthRecorder())}; + _validatorLabel:{t("observe.content.branchline.depthRecorder")}; +} + +#hookLost { + horizontalTextPosition:{JCheckBox.LEFT}; + text:"observe.content.branchline.hookLost"; + _branchlineBeanPropertyName:{BranchlineDto.PROPERTY_HOOK_LOST}; + selected:{BooleanUtils.isTrue(branchlineBean.getHookLost())}; + _validatorLabel:{t("observe.content.branchline.hookLost")}; +} + +#traceCutOff { + horizontalTextPosition:{JCheckBox.LEFT}; + text:"observe.content.branchline.traceCutOff"; + _branchlineBeanPropertyName:{BranchlineDto.PROPERTY_TRACE_CUT_OFF}; + selected:{BooleanUtils.isTrue(branchlineBean.getTraceCutOff())}; + _validatorLabel:{t("observe.content.branchline.traceCutOff")}; +} + +#timer { + text:"observe.content.branchline.timer"; + horizontalTextPosition:{JCheckBox.LEFT}; + _branchlineBeanPropertyName:{BranchlineDto.PROPERTY_TIMER}; + selected:{BooleanUtils.isTrue(branchlineBean.getTimer())}; + _validatorLabel:{t("observe.content.branchline.timer")}; +} + +#timeSinceContactLabel { + text:"observe.content.branchline.timeSinceContact"; + labelFor:{timeSinceContact}; +} + +#timeSinceContact { + property:{BranchlineDto.PROPERTY_TIME_SINCE_CONTACT}; + bean:{branchlineBean}; + enabled:{BooleanUtils.isTrue(branchlineBean.getTimer())}; + model:{branchlineBean.getTimeSinceContact()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.LONG_10_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.branchline.timeSinceContact")}; +} + +#timerTimeOnBoardLabel { + text:"observe.content.branchline.timerTimeOnBoard"; + labelFor:{timerTimeOnBoard}; +} + +#timerTimeOnBoard { + date:{branchlineBean.getTimerTimeOnBoard()}; + propertyDate: {BranchlineDto.PROPERTY_TIMER_TIME_ON_BOARD}; + bean:{branchlineBean}; + enabled:{BooleanUtils.isTrue(branchlineBean.getTimer())}; + label:{t("observe.content.branchline.timerTimeOnBoard")}; + _validatorLabel:{t("observe.content.branchline.timerTimeOnBoard")}; +} + +#baitHaulingStatusLabel { + text:"observe.content.branchline.baitHaulingStatus"; + labelFor:{baitHaulingStatus}; +} + +#baitHaulingStatus { + property:{BranchlineDto.PROPERTY_BAIT_HAULING_STATUS}; + bean:{branchlineBean}; + selectedItem:{branchlineBean.getBaitHaulingStatus()}; + _validatorLabel:{t("observe.content.branchline.baitHaulingStatus")}; +} + +#branchlineActions { + visible:{tableModel.isEditable()}; +} + +#resetBranchline { + text:"observe.content.catchLongline.resetBranchline"; + toolTipText:"observe.content.catchLongline.resetBranchline.tip"; + actionIcon:"revert"; + enabled:{branchlineValidator.isChanged()}; +} + +#saveBranchline{ + text:"observe.content.catchLongline.saveBranchline"; + toolTipText:"observe.content.catchLongline.saveBranchline.tip"; + actionIcon:"save"; + enabled:{branchlineValidator.isChanged() && branchlineValidator.isValid()}; +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchLonglineUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchLonglineUIHandler.java new file mode 100644 index 0000000..a19c143 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchLonglineUIHandler.java @@ -0,0 +1,938 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.longline.BasketDto; +import fr.ird.observe.services.dto.longline.BranchlineDto; +import fr.ird.observe.services.dto.longline.BranchlineDtos; +import fr.ird.observe.services.dto.longline.CatchLonglineDto; +import fr.ird.observe.services.dto.longline.SectionDto; +import fr.ird.observe.services.dto.longline.SetLonglineCatchDto; +import fr.ird.observe.services.dto.longline.SetLonglineCatchDtos; +import fr.ird.observe.services.dto.longline.SizeMeasureDto; +import fr.ird.observe.services.dto.longline.WeightMeasureDto; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.ReferentialReferences; +import fr.ird.observe.services.dto.referential.SpeciesDto; +import fr.ird.observe.services.dto.referential.longline.CatchFateLonglineDto; +import fr.ird.observe.services.dto.referential.longline.HealthnessDto; +import fr.ird.observe.services.dto.referential.longline.SizeMeasureTypeDto; +import fr.ird.observe.services.dto.referential.longline.WeightMeasureTypeDto; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.service.longline.BranchlineService; +import fr.ird.observe.services.service.longline.SetLonglineCatchService; +import fr.ird.observe.services.service.longline.TripLonglineService; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.ContentUIInitializer; +import fr.ird.observe.application.swing.ui.content.ContentUIModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIHandler; +import jaxx.runtime.context.JAXXContextEntryDef; +import jaxx.runtime.validator.swing.SwingValidator; +import jaxx.runtime.validator.swing.SwingValidatorMessage; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; +import org.apache.commons.lang3.BooleanUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.JComponent; +import javax.swing.JOptionPane; +import javax.swing.JTable; +import javax.swing.event.TableModelListener; +import javax.swing.table.DefaultTableCellRenderer; +import java.beans.PropertyChangeListener; +import java.util.Collection; +import java.util.Collections; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 9/11/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.7 + */ +public class CatchLonglineUIHandler extends ContentTableUIHandler<SetLonglineCatchDto, CatchLonglineDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(CatchLonglineUIHandler.class); + + // Compute valid state of tab from the error table + protected final TableModelListener computeTabValidStateListener; + + private final PropertyChangeListener catchFateChanged; + + private final PropertyChangeListener branchlineChanged; + + private final PropertyChangeListener depredatedChanged; + + private final PropertyChangeListener sizeTableModelModified; + + private final PropertyChangeListener weightTableModelModified; + + private final JAXXContextEntryDef<LonglinePositionHelper<CatchLonglineDto>> POSITION_HELPER_ENTRY = + UIHelper.newContextEntryDef("CatchLonglineUI-positionHelper", LonglinePositionHelper.class); + + public CatchLonglineUIHandler(CatchLonglineUI ui) { + super(ui, DataContextType.SetLongline); + computeTabValidStateListener = e -> { + + SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); + computeTabValidState(source); + + }; + catchFateChanged = evt -> onCatchFateChanged((ReferentialReference<CatchFateLonglineDto>) evt.getNewValue(), (CatchLonglineDto) evt.getSource()); + branchlineChanged = evt -> onBranchlineChanged((DataReference<BranchlineDto>) evt.getNewValue()); + weightTableModelModified = evt -> onWeightTableModelModified((Boolean) evt.getNewValue()); + sizeTableModelModified = evt -> onSizeTableModelModified((Boolean) evt.getNewValue()); + depredatedChanged = evt -> onDepretadedChanged((Boolean) evt.getNewValue(), (CatchLonglineDto) evt.getSource()); + } + + @Override + public CatchLonglineUI getUi() { + return (CatchLonglineUI) super.getUi(); + } + + @Override + public CatchLonglineUIModel getModel() { + return (CatchLonglineUIModel) super.getModel(); + } + + @Override + public void initUI() { + + final CatchLonglineContentTableUIInitializer uiInitializer = new CatchLonglineContentTableUIInitializer(getUi()); + uiInitializer.initUI(); + + getModel().addPropertyChangeListener(CatchLonglineUIModel.PROPERTY_SHOW_INDIVIDUAL_TABS, evt -> { + Boolean newValue = (Boolean) evt.getNewValue(); + showIndividualTabs(newValue); + }); + + getModel().addPropertyChangeListener(CatchLonglineUIModel.PROPERTY_EDITABLE, evt -> { + Boolean newValue = (Boolean) evt.getNewValue(); + setTableModelEditable(newValue); + }); + + getModel().addPropertyChangeListener(ContentUIModel.PROPERTY_FORM, evt -> updateUiWithReferenceSetsFromModel()); + + setTableModelEditable(getModel().isEditable()); + + LonglinePositionHelper<CatchLonglineDto> positionHelper = new LonglinePositionHelper<>( + getUi().getSection(), + getUi().getBasket(), + getUi().getBranchline(), + getTableEditBean()); + + POSITION_HELPER_ENTRY.setContextValue(getUi(), positionHelper); + + } + + @Override + public void openUI() { + + if (log.isInfoEnabled()) { + log.info("OpenUI: " + getModel()); + } + + super.openUI(); + + // Reset all sections + LonglinePositionHelper<CatchLonglineDto> positionHelper = POSITION_HELPER_ENTRY.getContextValue(getUi()); + getUi().getSection().setData(positionHelper.getSections()); + + // To be sure always remove listener (could prevent some leaks) + getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); + // listen messages to see if required to add + getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); + + SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); + computeTabValidState(errorTableModel); + + } + + public void resetBranchline() { + + onBranchlineChanged(null); + + onBranchlineChanged(getTableEditBean().getBranchline()); + + } + + public void saveBranchline() { + + if (log.isInfoEnabled()) { + log.info("Saved modified branchline"); + } + + CatchLonglineUI ui = getUi(); + + BranchlineDto branchline = ui.getBranchlineBean(); + + String openSetLonglineId = getDataContext().getSelectedSetLonglineId(); + SaveResultDto saveResult = getBranchLineService().save(openSetLonglineId, branchline); + saveResult.toDto(branchline); + + // on recopie le last update car c'est le laste update de SetLongline qui est renvoyé. + getBean().setLastUpdateDate(saveResult.getLastUpdateDate()); + + getUi().getBranchlineValidator().setChanged(false); + + } + + public void updateCatchAcquisitionMode(CatchAcquisitionModeEnum newMode) { + + if (log.isDebugEnabled()) { + log.debug("Change CatchAcquisitionMode " + newMode); + } + if (newMode == null) { + + // mode null (cela peut arriver avec les bindings) + return; + } + + CatchLonglineUI ui = getUi(); + + boolean createMode = ui.getTableModel().isCreate(); + + CatchLonglineDto editBean = ui.getTableEditBean(); + + switch (newMode) { + + case GROUPED: + + if (createMode) { + + editBean.setTotalWeight(null); + editBean.setCount(null); + editBean.setHookPosition(null); + + } + + break; + + case INDIVIDUAL: + + if (createMode) { + + // on positionne le count à 1 (seule valeur possible) + editBean.setCount(1); + + } + + break; + } + + boolean isGrouped = CatchAcquisitionModeEnum.GROUPED.equals(newMode); + + ui.getTotalWeight().setEnabled(isGrouped); + ui.getCount().setEnabled(isGrouped); + + boolean isIndividual = CatchAcquisitionModeEnum.INDIVIDUAL.equals(newMode); + + ui.getHookPosition().setEnabled(isIndividual); + ui.getSection().setEnabled(isIndividual); + ui.getBasket().setEnabled(isIndividual); + ui.getBranchline().setEnabled(isIndividual); + + if (createMode) { + + // on propage le mode de saisie dans le bean + editBean.setAcquisitionMode(newMode.ordinal()); + + } + + boolean showIndividualTabs = !createMode && isIndividual; + + ui.getModel().setShowIndividualTabs(showIndividualTabs); + + } + + @Override + protected void onSelectedRowChanged(int editingRow, CatchLonglineDto bean, boolean create) { + + if (log.isInfoEnabled()) { + log.info("Selected row changed: " + editingRow + ", create? " + create); + } + + CatchLonglineUI ui = getUi(); + + UIHelper.stopEditing(ui.getSizeMeasuresTable()); + UIHelper.stopEditing(ui.getWeightMeasuresTable()); + + CatchLonglineTableModel tableModel = getTableModel(); + CatchLonglineUIModel model = getModel(); + + boolean emptySelection = editingRow == -1; + + // load size measures + + SizeMeasuresTableModel sizeMeasuresTableModel = model.getSizeMeasuresTableModel(); + List<SizeMeasureDto> sizes = emptySelection ? Collections.emptyList() : sizeMeasuresTableModel.getCacheForRow(editingRow); + if (sizes == null) { + + if (log.isInfoEnabled()) { + log.info("init size measures for row " + editingRow); + } + + // first time coming on this row + + if (tableModel.isCreate()) { + + // create mode: just init with empty list + sizes = Collections.emptyList(); + + if (log.isInfoEnabled()) { + log.info("create mode, use an empty list"); + } + + } else { + + // updating mode: loading from db + sizes = Lists.newArrayList(bean.getSizeMeasure()); + if (log.isInfoEnabled()) { + log.info("Loaded sizes (" + bean.getId() + "): " + sizes.size()); + } + } + + // init size measures + sizeMeasuresTableModel.initCacheForRow(editingRow, sizes); + + } else { + + if (log.isInfoEnabled()) { + log.info("Using existing sizes for row " + editingRow + " : " + sizes.size()); + } + } + + sizeMeasuresTableModel.setData(sizes); + + // load weight measures + + WeightMeasuresTableModel weightMeasuresTableModel = model.getWeightMeasuresTableModel(); + List<WeightMeasureDto> weights = emptySelection ? Collections.emptyList() : weightMeasuresTableModel.getCacheForRow(editingRow); + + if (weights == null) { + + if (tableModel.isCreate()) { + + // create mode: just init with empty list + weights = Collections.emptyList(); + + } else { + + // updating mode: loading from db + weights = Lists.newArrayList(bean.getWeightMeasure()); + if (log.isInfoEnabled()) { + log.info("Loaded weights (" + bean.getId() + "): " + weights.size()); + } + + } + + // init weights measures + weightMeasuresTableModel.initCacheForRow(editingRow, weights); + + } else { + + if (log.isInfoEnabled()) { + log.info("Using existing weights for row " + editingRow + ": " + weights.size()); + } + } + + weightMeasuresTableModel.setData(weights); + + sizeMeasuresTableModel.setModified(false); + weightMeasuresTableModel.setModified(false); + + if (!tableModel.isEditable()) { + return; + } + + JComponent requestFocus; + + if (tableModel.isCreate()) { + + // go back to first pane + ui.getFishingOperationTabPane().setSelectedIndex(0); + + // select by default individual acquisition mode + ui.getAcquisitionModeGroup().setSelectedValue(null); + ui.getAcquisitionModeGroup().setSelectedValue(CatchAcquisitionModeEnum.INDIVIDUAL); + + ui.getPredator().setEnabled(false); + ui.getHookWhenDiscarded().setEnabled(false); + + ui.getDiscardHealthness().setEnabled(false); + ui.getBeatDiameter().setEnabled(false); + + requestFocus = ui.getSpeciesCatch(); + + } else { + + int acquisitionMode = bean.getAcquisitionMode(); + CatchAcquisitionModeEnum enumValue = CatchAcquisitionModeEnum.valueOf(acquisitionMode); + ui.getAcquisitionModeGroup().setSelectedValue(null); + ui.getAcquisitionModeGroup().setSelectedValue(enumValue); + + if (enumValue.equals(CatchAcquisitionModeEnum.GROUPED)) { + + requestFocus = ui.getCount(); + + } else { + + requestFocus = ui.getCatchHealthness(); + + } + + //FIXME Voir si pas besoin aussi de relancer les binding (catchFateChanged, branchlineChanged) ? + onDepretadedChanged(bean.getDepredated(), bean); + + } + + bean.removePropertyChangeListener(CatchLonglineDto.PROPERTY_CATCH_FATE_LONGLINE, catchFateChanged); + bean.addPropertyChangeListener(CatchLonglineDto.PROPERTY_CATCH_FATE_LONGLINE, catchFateChanged); + + bean.removePropertyChangeListener(CatchLonglineDto.PROPERTY_BRANCHLINE, branchlineChanged); + bean.addPropertyChangeListener(CatchLonglineDto.PROPERTY_BRANCHLINE, branchlineChanged); + + bean.removePropertyChangeListener(CatchLonglineDto.PROPERTY_DEPREDATED, depredatedChanged); + bean.addPropertyChangeListener(CatchLonglineDto.PROPERTY_DEPREDATED, depredatedChanged); + + LonglinePositionHelper<CatchLonglineDto> positionHelper = POSITION_HELPER_ENTRY.getContextValue(ui); + positionHelper.resetPosition(bean); + + requestFocus.requestFocus(); + + } + + @Override + protected void initTableUI(DefaultTableCellRenderer renderer) { + + CatchLonglineUI ui = getUi(); + { + // init main table + + JTable table = ui.getTable(); + + UIHelper.setI18nTableHeaderRenderer( + table, + n("observe.content.catchLongline.table.sectionHaulingId"), + n("observe.content.catchLongline.table.sectionHaulingId.tip"), + n("observe.content.catchLongline.table.basketHaulingId"), + n("observe.content.catchLongline.table.basketHaulingId.tip"), + n("observe.content.catchLongline.table.branchlineHaulingId"), + n("observe.content.catchLongline.table.branchlineHaulingId.tip"), + + n("observe.content.catchLongline.table.speciesCatch"), + n("observe.content.catchLongline.table.speciesCatch.tip"), + n("observe.content.catchLongline.table.acquisitionMode"), + n("observe.content.catchLongline.table.acquisitionMode.tip"), + n("observe.content.catchLongline.table.count"), + n("observe.content.catchLongline.table.count.tip"), + n("observe.content.catchLongline.table.catchHealthness"), + n("observe.content.catchLongline.table.catchHealthness.tip"), + n("observe.content.catchLongline.table.catchFateLongline"), + n("observe.content.catchLongline.table.catchFateLongline.tip"), + n("observe.content.catchLongline.table.discardHealthness"), + n("observe.content.catchLongline.table.discardHealthness.tip"), + n("observe.content.catchLongline.table.depredated"), + n("observe.content.catchLongline.table.depredated.tip"), + n("observe.content.catchLongline.table.comment"), + n("observe.content.catchLongline.table.comment.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newDataReferenceDecorateTableCellRenderer(renderer, SectionDto.class, DecoratorService.HAULING_IDENTIFIER)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newDataReferenceDecorateTableCellRenderer(renderer, BasketDto.class, DecoratorService.HAULING_IDENTIFIER)); + UIHelper.setTableColumnRenderer(table, 2, UIHelper.newDataReferenceDecorateTableCellRenderer(renderer, BranchlineDto.class, DecoratorService.HAULING_IDENTIFIER)); + + UIHelper.setTableColumnRenderer(table, 3, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesDto.class)); + UIHelper.setTableColumnRenderer(table, 4, UIHelper.newEnumTableCellRenderer(renderer, CatchAcquisitionModeEnum.class)); + UIHelper.setTableColumnRenderer(table, 5, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 6, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, HealthnessDto.class)); + UIHelper.setTableColumnRenderer(table, 7, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, CatchFateLonglineDto.class)); + UIHelper.setTableColumnRenderer(table, 8, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, HealthnessDto.class)); + UIHelper.setTableColumnRenderer(table, 9, UIHelper.newBooleanTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 10, UIHelper.newStringTableCellRenderer(renderer, 10, true)); + + } + + { + // init size measures table + JTable table = ui.getSizeMeasuresTable(); + + UIHelper.setI18nTableHeaderRenderer(table, + n("observe.content.catchLongline.table.sizeMeasureType"), + n("observe.content.catchLongline.table.sizeMeasureType.tip"), + n("observe.content.catchLongline.table.size"), + n("observe.content.catchLongline.table.size.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SizeMeasureTypeDto.class)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + + ReferentialReferenceDecorator<SizeMeasureTypeDto> decorator = getReferentialReferenceDecorator(SizeMeasureTypeDto.class); + + List<ReferentialReference<SizeMeasureTypeDto>> sizeMeasureTypes = + Lists.newArrayList(getDataSource().getReferentialReferences(SizeMeasureTypeDto.class)); + + UIHelper.setTableColumnEditor(table, 0, ContentUIInitializer.newDataColumnEditor(sizeMeasureTypes, decorator)); + UIHelper.setTableColumnEditor(table, 1, ContentUIInitializer.newFloatColumnEditor(table)); + + initInlineTable(ui.getSizeMeasuresScrollPane(), + table, + getModel().getSizeMeasuresTableModel(), + sizeTableModelModified, + ui.getSizeMeasuresTablePopup(), + ui.getAddSizeMeasure(), + ui.getDeleteSelectedSizeMeasure()); + + } + + { + // init weight measures table + JTable table = ui.getWeightMeasuresTable(); + + UIHelper.setI18nTableHeaderRenderer(table, + n("observe.content.catchLongline.table.weightMeasureType"), + n("observe.content.catchLongline.table.weightMeasureType.tip"), + n("observe.content.catchLongline.table.weight"), + n("observe.content.catchLongline.table.weight.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, WeightMeasureTypeDto.class)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + + ReferentialReferenceDecorator<WeightMeasureTypeDto> decorator = getReferentialReferenceDecorator(WeightMeasureTypeDto.class); + + List<ReferentialReference<WeightMeasureTypeDto>> weightMeasureTypes = + Lists.newArrayList(getDataSource().getReferentialReferences(WeightMeasureTypeDto.class)); + + UIHelper.setTableColumnEditor(table, 0, ContentUIInitializer.newDataColumnEditor(weightMeasureTypes, decorator)); + UIHelper.setTableColumnEditor(table, 1, ContentUIInitializer.newFloatColumnEditor(table)); + + initInlineTable(ui.getWeightMeasuresScrollPane(), + table, + getModel().getWeightMeasuresTableModel(), + weightTableModelModified, + ui.getWeightMeasuresTablePopup(), + ui.getAddWeightMeasure(), + ui.getDeleteSelectedWeightMeasure()); + + } + + getTableModel().addPropertyChangeListener(ContentTableModel.CREATE_PROPERTY, evt -> { + Boolean oldValue = (Boolean) evt.getOldValue(); + Boolean newValue = (Boolean) evt.getNewValue(); + setTableModelCreate(oldValue, newValue); + }); + } + + @Override + protected String getEditBeanIdToLoad() { + return getDataContext().getSelectedSetLonglineId(); + } + + @Override + protected void doPersist(SetLonglineCatchDto bean) { + SaveResultDto saveResult = getSetLonglineCatchService().save(bean); + bean.setLastUpdateDate(saveResult.getLastUpdateDate()); + } + + @Override + protected void loadEditBean(String beanId) { + + Form<SetLonglineCatchDto> form = getSetLonglineCatchService().loadForm(beanId); + + CatchLonglineUIModel model = getModel(); + + loadReferentialReferenceSetsInModel(form); + + model.setForm(form); + + LonglinePositionHelper<CatchLonglineDto> positionHelper = POSITION_HELPER_ENTRY.getContextValue(getUi()); + positionHelper.initSections( + form.getObject(), + form.getObject().getCatchLongline()); + + SetLonglineCatchDtos.copySetLonglineCatchDto(form.getObject(), getBean()); + + } + + @Override + protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { + + Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); + + switch (propertyName) { + + case CatchLonglineDto.PROPERTY_SPECIES_CATCH: + case CatchLonglineDto.PROPERTY_PREDATOR: { + String speciesListId; + + if (CatchLonglineDto.PROPERTY_SPECIES_CATCH.equals(propertyName)) { + speciesListId = ObserveSwingApplicationContext.get().getConfig().getSpeciesListLonglineCatchId(); + } else { + speciesListId = ObserveSwingApplicationContext.get().getConfig().getSpeciesListLonglineDepredatorId(); + } + + String tripLonglineId = getDataContext().getSelectedTripLonglineId(); + + TripLonglineService tripLonglineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripLonglineService(); + result = (List) tripLonglineService.getSpeciesByListAndTrip(tripLonglineId, speciesListId); + + result = ReferentialReferences.filterEnabled(result); + + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + + break; + } + + } + + return result; + + } + + @Override + protected void closeSafeUI() { + + if (log.isInfoEnabled()) { + log.info("CloseUI: " + getModel()); + } + super.closeSafeUI(); + + // remove listener + getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); + + } + + @Override + protected void resetEditBean() { + + UIHelper.stopEditing(getUi().getSizeMeasuresTable()); + UIHelper.stopEditing(getUi().getWeightMeasuresTable()); + + onBranchlineChanged(null); + + super.resetEditBean(); + + onBranchlineChanged(getTableEditBean().getBranchline()); + + } + + protected void setTableModelEditable(Boolean newValue) { + + getModel().getSizeMeasuresTableModel().setEditable(newValue); + getModel().getWeightMeasuresTableModel().setEditable(newValue); + + } + + protected void setTableModelCreate(Boolean oldValue, Boolean newValue) { + + if (BooleanUtils.isTrue(oldValue) && BooleanUtils.isFalse(newValue)) { + + // just save a row + // reload acquisition mode (will rebind some stuff) + + CatchAcquisitionModeEnum acquisitionModeEnum = (CatchAcquisitionModeEnum) getUi().getAcquisitionModeGroup().getSelectedValue(); + + getUi().getAcquisitionModeGroup().setSelectedValue(null); + getUi().getAcquisitionModeGroup().setSelectedValue(acquisitionModeEnum); + + } + + } + + protected void showIndividualTabs(boolean newValue) { + + if (log.isInfoEnabled()) { + log.info("will show individuals tabs ?" + newValue); + } + + getUi().getFoodAndSexualFormTab().setEnabled(newValue); + getUi().getSizeMeasuresFormTab().setEnabled(newValue); + getUi().getWeightMeasuresFormTab().setEnabled(newValue); + + if (!newValue && getUi().getFishingOperationTabPane().getSelectedIndex() > 2) { + + // go back to first tab + getUi().getFishingOperationTabPane().setSelectedIndex(0); + + } + + } + + protected void onCatchFateChanged(ReferentialReference<CatchFateLonglineDto> newValue, CatchLonglineDto tableEditBean) { + + CatchLonglineUI ui = getUi(); + + if (newValue == null || !"fr.ird.observe.entities.referentiel.longline.CatchFateLongline#1239832686125#0.3".equals(newValue.getId())) { + + // not discarded + ui.getDiscardHealthness().setEnabled(false); + ui.getHookWhenDiscarded().setEnabled(false); + + getTableEditBean().setHookWhenDiscarded(null); + getTableEditBean().setDiscardHealthness(null); + + } else { + + // discarded + ui.getDiscardHealthness().setEnabled(true); + ui.getHookWhenDiscarded().setEnabled(true); + + } + + } + + protected void onBranchlineChanged(DataReference<BranchlineDto> newValue) { + + CatchLonglineUI ui = getUi(); + + BranchlineDto branchline = ui.getBranchlineBean(); + + SwingValidator<BranchlineDto> branchlineValidator = ui.getBranchlineValidator(); + if (newValue == null) { + + if (log.isInfoEnabled()) { + log.info("Remove branchline"); + } + + branchlineValidator.setBean(null); + + } else { + + if (log.isInfoEnabled()) { + log.info("Use branchline: " + newValue); + } + + String setLonglineId = getDataContext().getSelectedSetLonglineId(); + + Form<BranchlineDto> form = getBranchLineService().loadForm(setLonglineId, newValue.getId()); + BranchlineDtos.copyBranchlineDto(form.getObject(), branchline); + + if (ui.getValidator().getBean() == null) { + ui.getValidator().setBean(getBean()); + } + + branchlineValidator.setBean(branchline); + + } + + branchlineValidator.setChanged(false); + + } + + protected void onDepretadedChanged(Boolean newValue, CatchLonglineDto tableEditBean) { + + CatchLonglineUI ui = getUi(); + + if (BooleanUtils.isTrue(newValue)) { + + // depredated + ui.getBeatDiameter().setEnabled(true); + ui.getPredator().setEnabled(true); + + } else { + + // not depredated + ui.getBeatDiameter().setEnabled(false); + ui.getPredator().setEnabled(false); + tableEditBean.setBeatDiameter(null); + tableEditBean.setPredator(null); + + } + + } + + public void addSizeMeasure() { + + SizeMeasuresTableModel tableModel = getUi().getSizeMeasuresTableModel(); + + tableModel.addNewRow(); + + } + + public void deleteSelectedSizeMeasure() { + + SizeMeasuresTableModel tableModel = getUi().getSizeMeasuresTableModel(); + + boolean selectionEmpty = tableModel.isSelectionEmpty(); + + if (!selectionEmpty) { + + SizeMeasureDto data = tableModel.getSelectedRow(); + + if (log.isInfoEnabled()) { + log.info("Delete: " + data); + } + + ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); + int response = UIHelper.askUser(mainUI, + t("observe.title.delete"), + t("observe.content.sizeMeasure.delete.message"), + JOptionPane.WARNING_MESSAGE, + new Object[]{t("observe.choice.confirm.delete"), + t("observe.choice.cancel")}, + 1); + + if (response != 0) { + + // user cancel + return; + } + + tableModel.removeSelectedRow(); + + } + + } + + + protected void onSizeTableModelModified(Boolean newValue) { + + if (newValue) { + + // modify the validator, since this is the best way to prevent table edit form actions + // that something was modified on the form + getUi().getValidatorTable().setChanged(true); + + } + + // recompute table model valid state + getModel().getSizeMeasuresTableModel().validate(); + + } + + public void addWeightMeasure() { + + WeightMeasuresTableModel tableModel = getUi().getWeightMeasuresTableModel(); + + tableModel.addNewRow(); + + } + + public void deleteSelectedWeightMeasure() { + + WeightMeasuresTableModel tableModel = getUi().getWeightMeasuresTableModel(); + + boolean selectionEmpty = tableModel.isSelectionEmpty(); + + if (!selectionEmpty) { + + WeightMeasureDto data = tableModel.getSelectedRow(); + + if (log.isInfoEnabled()) { + log.info("Delete: " + data); + } + + ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); + int response = UIHelper.askUser(mainUI, + t("observe.title.delete"), + t("observe.content.weightMeasure.delete.message"), + JOptionPane.WARNING_MESSAGE, + new Object[]{t("observe.choice.confirm.delete"), + t("observe.choice.cancel")}, + 1); + + if (response != 0) { + + // user cancel + return; + } + + tableModel.removeSelectedRow(); + + } + + } + + protected void onWeightTableModelModified(Boolean newValue) { + + if (newValue) { + + // modify the validator, since this is the best way to prevent table edit form actions + // that something was modified on the form + getUi().getValidatorTable().setChanged(true); + + } + + // recompute table model valid state + getModel().getWeightMeasuresTableModel().validate(); + + } + + protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { + + Set<String> errorProperties = new HashSet<>(); + int rowCount = errorTableModel.getRowCount(); + for (int i = 0; i < rowCount; i++) { + + SwingValidatorMessage row = errorTableModel.getRow(i); + if (NuitonValidatorScope.ERROR.equals(row.getScope())) { + errorProperties.add(row.getField()); + } + } + + boolean caracteristicsTabValid = !errorProperties.removeAll(CatchLonglineUIModel.CARACTERISTIC_TAB_PROPERTIES); + boolean depredatedTabValid = !errorProperties.removeAll(CatchLonglineUIModel.DEPREDATED_TAB_PROPERTIES); + boolean foodAndSexualTabValid = !errorProperties.removeAll(CatchLonglineUIModel.FOOD_AND_SEXUAL_TAB_PROPERTIES); + boolean branchlineTabValid = !errorProperties.removeAll(CatchLonglineUIModel.BRANCHLINE_TAB_PROPERTIES); + + CatchLonglineUIModel model = getModel(); + + model.setCaracteristicsTabValid(caracteristicsTabValid); + model.setDepredatedTabValid(depredatedTabValid); + model.setFoodAndSexualTabValid(foodAndSexualTabValid); + model.setBranchlineTabValid(branchlineTabValid); + + } + + @Override + protected CatchLonglineTableModel getTableModel() { + return (CatchLonglineTableModel) super.getTableModel(); + } + + protected SetLonglineCatchService getSetLonglineCatchService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newSetLonglineCatchService(); + } + + protected BranchlineService getBranchLineService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newBranchlineService(); + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchLonglineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchLonglineUIModel.java new file mode 100644 index 0000000..72badfd --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/CatchLonglineUIModel.java @@ -0,0 +1,233 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import fr.ird.observe.application.swing.ObserveSwingBinderService; +import fr.ird.observe.services.dto.longline.BranchlineDto; +import fr.ird.observe.services.dto.longline.CatchLonglineDto; +import fr.ird.observe.services.dto.longline.SetLonglineCatchDto; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; +import org.nuiton.util.beans.Binder; +import org.nuiton.util.beans.BinderModelBuilder; + +import java.util.List; +import java.util.Set; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.7 + */ +public class CatchLonglineUIModel extends ContentTableUIModel<SetLonglineCatchDto, CatchLonglineDto> { + + public static final String PROPERTY_CARACTERISTICS_TAB_VALID = "caracteristicsTabValid"; + + public static final String PROPERTY_DEPREDATED_TAB_VALID = "depredatedTabValid"; + + public static final String PROPERTY_FOOD_AND_SEXUAL_TAB_VALID = "foodAndSexualTabValid"; + + public static final String PROPERTY_BRANCHLINE_TAB_VALID = "branchlineTabValid"; + + public static final String PROPERTY_SHOW_INDIVIDUAL_TABS = "showIndividualTabs"; + + public static final Set<String> CARACTERISTIC_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(CatchLonglineDto.PROPERTY_SECTION, + CatchLonglineDto.PROPERTY_BASKET, + CatchLonglineDto.PROPERTY_BRANCHLINE, + CatchLonglineDto.PROPERTY_SPECIES_CATCH, + CatchLonglineDto.PROPERTY_PHOTO_REFERENCES, + CatchLonglineDto.PROPERTY_COUNT, + CatchLonglineDto.PROPERTY_TOTAL_WEIGHT, + CatchLonglineDto.PROPERTY_CATCH_HEALTHNESS, + CatchLonglineDto.PROPERTY_HOOK_POSITION, + CatchLonglineDto.PROPERTY_CATCH_FATE_LONGLINE, + CatchLonglineDto.PROPERTY_DISCARD_HEALTHNESS, + CatchLonglineDto.PROPERTY_HOOK_WHEN_DISCARDED).build(); + + public static final Set<String> DEPREDATED_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(CatchLonglineDto.PROPERTY_DEPREDATED, + CatchLonglineDto.PROPERTY_BEAT_DIAMETER, + CatchLonglineDto.PROPERTY_PREDATOR).build(); + + public static final Set<String> FOOD_AND_SEXUAL_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(CatchLonglineDto.PROPERTY_STOMAC_FULLNESS, + CatchLonglineDto.PROPERTY_SEX, + CatchLonglineDto.PROPERTY_MATURITY_STATUS, + CatchLonglineDto.PROPERTY_GONADE_WEIGHT).build(); + + public static final Set<String> BRANCHLINE_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(BranchlineDto.PROPERTY_DEPTH_RECORDER, + BranchlineDto.PROPERTY_HOOK_LOST, + BranchlineDto.PROPERTY_TRACE_CUT_OFF, + BranchlineDto.PROPERTY_TIMER, + BranchlineDto.PROPERTY_TIME_SINCE_CONTACT, + BranchlineDto.PROPERTY_TIMER_TIME_ON_BOARD, + BranchlineDto.PROPERTY_BAIT_HAULING_STATUS).build(); + + + private static final long serialVersionUID = 1L; + + protected final SizeMeasuresTableModel sizeMeasuresTableModel; + + protected final WeightMeasuresTableModel weightMeasuresTableModel; + + /** + * flag to see the individual tabs (only on individual mode + not in create mode). + */ + protected boolean showIndividualTabs; + + protected boolean caracteristicsTabValid; + + protected boolean depredatedTabValid; + + protected boolean foodAndSexualTabValid; + + protected boolean branchlineTabValid; + + public CatchLonglineUIModel(CatchLonglineUI ui) { + super(SetLonglineCatchDto.class, + CatchLonglineDto.class, + new String[]{ + SetLonglineCatchDto.PROPERTY_CATCH_LONGLINE + }, + new String[]{CatchLonglineDto.PROPERTY_SPECIES_CATCH, + CatchLonglineDto.PROPERTY_ACQUISITION_MODE, + CatchLonglineDto.PROPERTY_COUNT, + CatchLonglineDto.PROPERTY_CATCH_HEALTHNESS, + CatchLonglineDto.PROPERTY_CATCH_FATE_LONGLINE, + CatchLonglineDto.PROPERTY_DISCARD_HEALTHNESS, + CatchLonglineDto.PROPERTY_DEPREDATED, + CatchLonglineDto.PROPERTY_NUMBER, + CatchLonglineDto.PROPERTY_HOME_ID, + CatchLonglineDto.PROPERTY_HOOK_POSITION, + CatchLonglineDto.PROPERTY_HOOK_WHEN_DISCARDED, + CatchLonglineDto.PROPERTY_MATURITY_STATUS, + CatchLonglineDto.PROPERTY_PHOTO_REFERENCES, + CatchLonglineDto.PROPERTY_SEX, + CatchLonglineDto.PROPERTY_PREDATOR, + CatchLonglineDto.PROPERTY_STOMAC_FULLNESS, + CatchLonglineDto.PROPERTY_TOTAL_WEIGHT, + CatchLonglineDto.PROPERTY_BEAT_DIAMETER, + CatchLonglineDto.PROPERTY_GONADE_WEIGHT, + CatchLonglineDto.PROPERTY_SECTION, + CatchLonglineDto.PROPERTY_BASKET, + CatchLonglineDto.PROPERTY_BRANCHLINE, + CatchLonglineDto.PROPERTY_COMMENT + }); + + this.sizeMeasuresTableModel = new SizeMeasuresTableModel(); + this.weightMeasuresTableModel = new WeightMeasuresTableModel(); + + List<ContentTableMeta<CatchLonglineDto>> metas = Lists.newArrayList( + ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_SECTION, false), + ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_BASKET, false), + ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_BRANCHLINE, false), + ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_SPECIES_CATCH, false), + ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_ACQUISITION_MODE, false), + ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_COUNT, false), + ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_CATCH_HEALTHNESS, false), + ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_CATCH_FATE_LONGLINE, false), + ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_DISCARD_HEALTHNESS, false), + ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_DEPREDATED, false), + ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_COMMENT, false)); + + initModel(ui, metas); + + } + + public SizeMeasuresTableModel getSizeMeasuresTableModel() { + return sizeMeasuresTableModel; + } + + public WeightMeasuresTableModel getWeightMeasuresTableModel() { + return weightMeasuresTableModel; + } + + public boolean isShowIndividualTabs() { + return showIndividualTabs; + } + + public void setShowIndividualTabs(boolean showIndividualTabs) { + this.showIndividualTabs = showIndividualTabs; + firePropertyChange(PROPERTY_SHOW_INDIVIDUAL_TABS, null, showIndividualTabs); + } + + public boolean isCaracteristicsTabValid() { + return caracteristicsTabValid; + } + + public void setCaracteristicsTabValid(boolean caracteristicsTabValid) { + this.caracteristicsTabValid = caracteristicsTabValid; + firePropertyChange(PROPERTY_CARACTERISTICS_TAB_VALID, null, caracteristicsTabValid); + } + + public boolean isDepredatedTabValid() { + return depredatedTabValid; + } + + public void setDepredatedTabValid(boolean depredatedTabValid) { + this.depredatedTabValid = depredatedTabValid; + firePropertyChange(PROPERTY_DEPREDATED_TAB_VALID, null, depredatedTabValid); + } + + public boolean isFoodAndSexualTabValid() { + return foodAndSexualTabValid; + } + + public void setFoodAndSexualTabValid(boolean foodAndSexualTabValid) { + this.foodAndSexualTabValid = foodAndSexualTabValid; + firePropertyChange(PROPERTY_FOOD_AND_SEXUAL_TAB_VALID, null, foodAndSexualTabValid); + } + + public boolean isBranchlineTabValid() { + return branchlineTabValid; + } + + public void setBranchlineTabValid(boolean branchlineTabValid) { + this.branchlineTabValid = branchlineTabValid; + firePropertyChange(PROPERTY_BRANCHLINE_TAB_VALID, null, branchlineTabValid); + } + + @Override + protected ContentTableModel<SetLonglineCatchDto, CatchLonglineDto> createTableModel(ObserveContentTableUI<SetLonglineCatchDto, CatchLonglineDto> ui, List<ContentTableMeta<CatchLonglineDto>> contentTableMetas) { + return new CatchLonglineTableModel(ui, contentTableMetas); + } + + @Override + protected BinderModelBuilder<CatchLonglineDto, CatchLonglineDto> prepareChildLoador(ObserveSwingBinderService binderService, String binderName) { + + BinderModelBuilder<CatchLonglineDto, CatchLonglineDto> builder = super.prepareChildLoador(binderService, binderName); + + builder.addCollectionStrategy(Binder.CollectionStrategy.duplicate, CatchLonglineDto.PROPERTY_PREDATOR); + + return builder; + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/EncounterUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/EncounterUI.jaxx new file mode 100644 index 0000000..e932f89 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/EncounterUI.jaxx @@ -0,0 +1,129 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.table.ContentTableUI + superGenericType='ActivityLonglineEncounterDto, EncounterDto' + contentTitle='{n("observe.content.encounter.title")}' + saveNewEntryText='{n("observe.content.encounter.action.create")}' + saveNewEntryTip='{n("observe.content.encounter.action.create.tip")}'> + + <style source="../../CommonTable.jcss"/> + + <import> + fr.ird.observe.services.dto.CommentableDto + fr.ird.observe.services.dto.longline.ActivityLonglineEncounterDto + fr.ird.observe.services.dto.longline.EncounterDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.SpeciesDto + fr.ird.observe.services.dto.referential.longline.EncounterTypeDto + fr.ird.observe.application.swing.ui.content.table.* + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + java.awt.Dimension + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <EncounterUIHandler id='handler'/> + + <!-- model --> + <EncounterUIModel id='model'/> + + <!-- edit bean --> + <ActivityLonglineEncounterDto id='bean'/> + + <!-- table edit bean --> + <EncounterDto id='tableEditBean'/> + + <!-- table model --> + <ContentTableModel id='tableModel'/> + + <!-- le validateur de l'écran --> + <BeanValidator id='validator' autoField='true' context='ui-update-encounter' + beanClass='fr.ird.observe.services.dto.longline.ActivityLonglineEncounterDto' + errorTableModel='{getErrorTableModel()}'/> + + <!-- le validateur d'une entrée de tableau --> + <BeanValidator id='validatorTable' autoField='true' context='ui-update' + beanClass='fr.ird.observe.services.dto.longline.EncounterDto' + errorTableModel='{getErrorTableModel()}'/> + + <Table id='editorPanel' fill='both' insets='1'> + + <!-- encounterType --> + <row> + <cell> + <JLabel id='encounterTypeLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='encounterType' constructorParams='this' genericType='ReferentialReference<EncounterTypeDto>' _entityClass='EncounterTypeDto.class'/> + </cell> + </row> + + <!-- species --> + <row> + <cell> + <JLabel id='speciesLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='species' constructorParams='this' genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class'/> + </cell> + </row> + + <!-- distance --> + <row> + <cell> + <JLabel id='distanceLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='distance' constructorParams='this'/> + </cell> + </row> + + <!-- count --> + <row> + <cell> + <JLabel id='countLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='count' constructorParams='this'/> + </cell> + </row> + + </Table> + + <Table id='extraZone' fill='both' weightx='1' insets='1'> + <row> + <cell weighty='1'> + <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2' + onKeyReleased='getBean().setComment(comment2.getText())'/> + </JScrollPane> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/EncounterUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/EncounterUI.jcss new file mode 100644 index 0000000..a942169 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/EncounterUI.jcss @@ -0,0 +1,67 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#encounterTypeLabel { + text:"observe.content.encounter.encounterType"; + labelFor:{encounterType}; +} + +#encounterType { + property:{EncounterDto.PROPERTY_ENCOUNTER_TYPE}; + selectedItem:{tableEditBean.getEncounterType()}; +} + +#speciesLabel { + text:"observe.content.encounter.species"; + labelFor:{species}; +} + +#species { + property:{EncounterDto.PROPERTY_SPECIES}; + selectedItem:{tableEditBean.getSpecies()}; +} + +#countLabel { + text:"observe.content.encounter.count"; + labelFor:{count}; +} + +#count { + property:{EncounterDto.PROPERTY_COUNT}; + model:{tableEditBean.getCount()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; +} + +#distanceLabel { + text:"observe.content.encounter.distance"; + labelFor:{distance}; +} + +#distance { + property:{EncounterDto.PROPERTY_DISTANCE}; + model:{tableEditBean.getDistance()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL3_PATTERN}; +} + +#comment { + columnHeaderView:{new JLabel(t("observe.common.comment.activity"))}; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/EncounterUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/EncounterUIHandler.java new file mode 100644 index 0000000..a0a6071 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/EncounterUIHandler.java @@ -0,0 +1,161 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.longline.ActivityLonglineEncounterDto; +import fr.ird.observe.services.dto.longline.ActivityLonglineEncounterDtos; +import fr.ird.observe.services.dto.longline.EncounterDto; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.ReferentialReferences; +import fr.ird.observe.services.dto.referential.SpeciesDto; +import fr.ird.observe.services.dto.referential.SpeciesListDto; +import fr.ird.observe.services.dto.referential.longline.EncounterTypeDto; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.service.ReferentialService; +import fr.ird.observe.services.service.longline.ActivityLongLineEncounterService; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; +import java.util.Collection; +import java.util.LinkedList; +import java.util.Set; + +import static org.nuiton.i18n.I18n.n; + +/** + * Created on 8/31/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.7 + */ +public class EncounterUIHandler extends ContentTableUIHandler<ActivityLonglineEncounterDto, EncounterDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(EncounterUIHandler.class); + + public EncounterUIHandler(EncounterUI ui) { + super(ui, DataContextType.ActivityLongline); + } + + @Override + public EncounterUI getUi() { + return (EncounterUI) super.getUi(); + } + + @Override + protected void onSelectedRowChanged(int editingRow, EncounterDto bean, boolean create) { + if (getTableModel().isEditable()) { + if (log.isDebugEnabled()) { + log.debug("Row has changed to " + editingRow); + } + getUi().getEncounterType().requestFocus(); + } + } + + @Override + protected void initTableUI(DefaultTableCellRenderer renderer) { + JTable table = getUi().getTable(); + + UIHelper.setI18nTableHeaderRenderer(table, + n("observe.content.encounter.table.encouterType"), + n("observe.content.encounter.table.encouterType.tip"), + n("observe.content.encounter.table.species"), + n("observe.content.encounter.table.species.tip"), + n("observe.content.encounter.table.distance"), + n("observe.content.encounter.table.distance.tip"), + n("observe.content.encounter.table.count"), + n("observe.content.encounter.table.count.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, EncounterTypeDto.class)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesDto.class)); + UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + } + + @Override + protected String getEditBeanIdToLoad() { + return getDataContext().getSelectedActivityId(); + } + + @Override + protected void doPersist(ActivityLonglineEncounterDto bean) { + + SaveResultDto saveResult = getActivityLongLineEncouterService().save(bean); + saveResult.toDto(bean); + + } + + @Override + protected void loadEditBean(String beanId) { + Form<ActivityLonglineEncounterDto> form = getActivityLongLineEncouterService().loadForm(beanId); + loadReferentialReferenceSetsInModel(form); + + getModel().setForm(form); + ActivityLonglineEncounterDtos.copyActivityLonglineEncounterDto(form.getObject(), getBean()); + } + + @Override + protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { + + Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); + + switch (propertyName) { + + case EncounterDto.PROPERTY_SPECIES: { + + String speciesListId = ObserveSwingApplicationContext.get().getConfig().getSpeciesListLonglineEncounterId(); + + ReferentialService referentialService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newReferentialService(); + + Form<SpeciesListDto> speciesListDtoForm = referentialService.loadForm(SpeciesListDto.class, speciesListId); + SpeciesListDto speciesListDto = speciesListDtoForm.getObject(); + + Set<String> speciesIds = speciesListDto.getSpeciesIds(); + + result = ReferentialReferences.filterContains(result, speciesIds); + + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + } + + break; + + } + + return result; + + } + + protected ActivityLongLineEncounterService getActivityLongLineEncouterService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivityLongLineEncounterService(); + } +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/EncounterUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/EncounterUIModel.java new file mode 100644 index 0000000..fb43245 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/EncounterUIModel.java @@ -0,0 +1,92 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import fr.ird.observe.services.dto.longline.ActivityLonglineEncounterDto; +import fr.ird.observe.services.dto.longline.EncounterDto; +import fr.ird.observe.services.dto.longline.EncounterDtos; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; + +import java.util.Collection; +import java.util.List; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.7 + */ +public class EncounterUIModel extends ContentTableUIModel<ActivityLonglineEncounterDto, EncounterDto> { + + private static final long serialVersionUID = 1L; + + public EncounterUIModel(EncounterUI ui) { + super(ActivityLonglineEncounterDto.class, + EncounterDto.class, + new String[]{ + ActivityLonglineEncounterDto.PROPERTY_ENCOUNTER, + ActivityLonglineEncounterDto.PROPERTY_COMMENT}, + new String[]{ + EncounterDto.PROPERTY_SPECIES, + EncounterDto.PROPERTY_DISTANCE, + EncounterDto.PROPERTY_COUNT, + EncounterDto.PROPERTY_ENCOUNTER_TYPE}); + + List<ContentTableMeta<EncounterDto>> metas = Lists.newArrayList( + ContentTableModel.newTableMeta(EncounterDto.class, EncounterDto.PROPERTY_ENCOUNTER_TYPE, false), + ContentTableModel.newTableMeta(EncounterDto.class, EncounterDto.PROPERTY_SPECIES, false), + ContentTableModel.newTableMeta(EncounterDto.class, EncounterDto.PROPERTY_DISTANCE, false), + ContentTableModel.newTableMeta(EncounterDto.class, EncounterDto.PROPERTY_COUNT, false)); + + initModel(ui, metas); + + } + + @Override + protected ContentTableModel<ActivityLonglineEncounterDto, EncounterDto> createTableModel( + ObserveContentTableUI<ActivityLonglineEncounterDto, EncounterDto> ui, + List<ContentTableMeta<EncounterDto>> contentTableMetas) { + return new ContentTableModel<ActivityLonglineEncounterDto, EncounterDto>(ui, contentTableMetas) { + private static final long serialVersionUID = 1L; + + @Override + protected Collection<EncounterDto> getChilds(ActivityLonglineEncounterDto bean) { + return bean.getEncounter(); + } + + @Override + protected void load(EncounterDto source, EncounterDto target) { + EncounterDtos.copyEncounterDto(source, target); + } + + @Override + protected void setChilds(ActivityLonglineEncounterDto parent, List<EncounterDto> childs) { + parent.setEncounter(childs); + } + }; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/FloatlinesCompositionUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/FloatlinesCompositionUI.jaxx new file mode 100644 index 0000000..9dc3a4f --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/FloatlinesCompositionUI.jaxx @@ -0,0 +1,121 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.table.ContentTableUI + superGenericType='SetLonglineGlobalCompositionDto, FloatlinesCompositionDto' + contentTitle='{n("observe.content.floatlinesComposition.title")}' + saveNewEntryText='{n("observe.content.floatlinesComposition.action.create")}' + saveNewEntryTip='{n("observe.content.floatlinesComposition.action.create.tip")}'> + + <style source="../../CommonTable.jcss"/> + + <import> + fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto + fr.ird.observe.services.dto.longline.FloatlinesCompositionDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.longline.LineTypeDto + fr.ird.observe.application.swing.ui.content.table.* + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <FloatlinesCompositionUIHandler id='handler'/> + + <!-- model --> + <FloatlinesCompositionUIModel id='model'/> + + <!-- edit bean --> + <SetLonglineGlobalCompositionDto id='bean'/> + + <!-- table edit bean --> + <FloatlinesCompositionDto id='tableEditBean'/> + + <!-- table model --> + <ContentTableModel id='tableModel'/> + + <!-- le validateur de l'écran --> + <BeanValidator id='validator' context='ui-update-floatlinesComposition' + beanClass='fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto' + errorTableModel='{getErrorTableModel()}'> + <field name="floatlinesCompositionProportionSum" component="floatlinesCompositionProportionSum"/> + <field name="floatlinesComposition" component="editorPanel"/> + </BeanValidator> + + <!-- le validateur d'une entrée de tableau --> + <BeanValidator id='validatorTable' autoField='true' context='ui-update' + beanClass='fr.ird.observe.services.dto.longline.FloatlinesCompositionDto' + errorTableModel='{getErrorTableModel()}'/> + + <Table id='editorPanel' fill='both' insets='1'> + + <!-- lineType --> + <row> + <cell> + <JLabel id='lineTypeLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='lineType' constructorParams='this' genericType='ReferentialReference<LineTypeDto>' _entityClass='LineTypeDto.class'/> + </cell> + </row> + + <!-- length --> + <row> + <cell> + <JLabel id='lengthLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='length' constructorParams='this'/> + </cell> + </row> + + <!-- proportion --> + <row> + <cell> + <JLabel id='proportionLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='proportion' constructorParams='this'/> + </cell> + </row> + + </Table> + + <Table id='extraZone' fill='both'> + + <!-- proportion sum --> + <row> + <cell> + <JLabel id='floatlinesCompositionProportionSumLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <JLabel id='floatlinesCompositionProportionSum'/> + </cell> + </row> + + </Table> + +</fr.ird.observe.application.swing.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/FloatlinesCompositionUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/FloatlinesCompositionUI.jcss new file mode 100644 index 0000000..ac510eb --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/FloatlinesCompositionUI.jcss @@ -0,0 +1,67 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#lineTypeLabel { + text:"observe.content.floatlinesComposition.lineType"; + labelFor:{lineType}; +} + +#lineType { + property:{FloatlinesCompositionDto.PROPERTY_LINE_TYPE}; + selectedItem:{tableEditBean.getLineType()}; + _validatorLabel:{t("observe.content.floatlinesComposition.lineType")}; +} + +#lengthLabel { + text:"observe.content.floatlinesComposition.length"; + labelFor:{length}; +} + +#length { + property:{FloatlinesCompositionDto.PROPERTY_LENGTH}; + model:{tableEditBean.getLength()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL3_PATTERN}; + _validatorLabel:{t("observe.content.floatlinesComposition.length")}; +} + +#proportionLabel { + text:"observe.content.floatlinesComposition.proportion"; + labelFor:{proportion}; +} + +#proportion { + property:{FloatlinesCompositionDto.PROPERTY_PROPORTION}; + model:{tableEditBean.getProportion()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.floatlinesComposition.proportion")}; +} + +#floatlinesCompositionProportionSumLabel { + text:"observe.content.floatlinesComposition.proportionSum"; + labelFor:{floatlinesCompositionProportionSum}; +} + +#floatlinesCompositionProportionSum { + text:{getStringValue(bean.getFloatlinesCompositionProportionSum())}; + _validatorLabel:{t("observe.content.floatlinesComposition.proportionSum")}; + font-weight:bold; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/FloatlinesCompositionUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/FloatlinesCompositionUIHandler.java new file mode 100644 index 0000000..9f53d2b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/FloatlinesCompositionUIHandler.java @@ -0,0 +1,117 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.longline.FloatlinesCompositionDto; +import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto; +import fr.ird.observe.services.dto.referential.longline.LineTypeDto; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; + +import static org.nuiton.i18n.I18n.n; + +/** + * Created on 12/6/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.9 + */ +public class FloatlinesCompositionUIHandler extends ContentTableUIHandler<SetLonglineGlobalCompositionDto, FloatlinesCompositionDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(FloatlinesCompositionUIHandler.class); + + public FloatlinesCompositionUIHandler(FloatlinesCompositionUI ui) { + super(ui, DataContextType.SetLongline); + } + + @Override + public FloatlinesCompositionUI getUi() { + return (FloatlinesCompositionUI) super.getUi(); + } + + @Override + protected void onSelectedRowChanged(int editingRow, FloatlinesCompositionDto bean, boolean create) { + + if (getTableModel().isEditable()) { + if (log.isDebugEnabled()) { + log.debug("Row has changed to " + editingRow); + } + getUi().getLineType().requestFocus(); + } + + } + + @Override + protected void initTableUI(DefaultTableCellRenderer renderer) { + + JTable table = getUi().getTable(); + + UIHelper.setI18nTableHeaderRenderer( + table, + n("observe.content.floatlinesComposition.table.lineType"), + n("observe.content.floatlinesComposition.table.lineType.tip"), + n("observe.content.floatlinesComposition.table.length"), + n("observe.content.floatlinesComposition.table.length.tip"), + n("observe.content.floatlinesComposition.table.proportion"), + n("observe.content.floatlinesComposition.table.proportion.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, LineTypeDto.class)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + + // when model change in table, let's recompute the proportion sum + table.getModel().addTableModelListener(e -> { + + int proportionSum = getBean().getFloatlinesCompositionProportionSum(); + getBean().setFloatlinesCompositionProportionSum(proportionSum); + }); + + } + + @Override + protected String getEditBeanIdToLoad() { + return getDataContext().getSelectedSetId(); + } + + @Override + public void afterSave(boolean refresh) { + super.afterSave(refresh); + } + + @Override + protected void doPersist(SetLonglineGlobalCompositionDto bean) { + // fait par le doSave de LonglineGlobalCompositionUIHandler + } + + @Override + protected void loadEditBean(String beanId) { + // fait par le loadEditBean de LonglineGlobalCompositionUIHandler + } +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/FloatlinesCompositionUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/FloatlinesCompositionUIModel.java new file mode 100644 index 0000000..75d5265 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/FloatlinesCompositionUIModel.java @@ -0,0 +1,90 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import fr.ird.observe.services.dto.longline.FloatlinesCompositionDto; +import fr.ird.observe.services.dto.longline.FloatlinesCompositionDtos; +import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; + +import java.util.Collection; +import java.util.List; + +/** + * Created on 12/6/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.9 + */ +public class FloatlinesCompositionUIModel extends ContentTableUIModel<SetLonglineGlobalCompositionDto, FloatlinesCompositionDto> { + + private static final long serialVersionUID = 1L; + + public FloatlinesCompositionUIModel(FloatlinesCompositionUI ui) { + super(SetLonglineGlobalCompositionDto.class, + FloatlinesCompositionDto.class, + new String[]{ + SetLonglineGlobalCompositionDto.PROPERTY_FLOATLINES_COMPOSITION + }, + new String[]{FloatlinesCompositionDto.PROPERTY_LINE_TYPE, + FloatlinesCompositionDto.PROPERTY_LENGTH, + FloatlinesCompositionDto.PROPERTY_PROPORTION}); + + List<ContentTableMeta<FloatlinesCompositionDto>> metas = Lists.newArrayList( + ContentTableModel.newTableMeta(FloatlinesCompositionDto.class, FloatlinesCompositionDto.PROPERTY_LINE_TYPE, false), + ContentTableModel.newTableMeta(FloatlinesCompositionDto.class, FloatlinesCompositionDto.PROPERTY_LENGTH, false), + ContentTableModel.newTableMeta(FloatlinesCompositionDto.class, FloatlinesCompositionDto.PROPERTY_PROPORTION, false)); + + initModel(ui, metas); + + } + + + @Override + protected ContentTableModel<SetLonglineGlobalCompositionDto, FloatlinesCompositionDto> createTableModel( + ObserveContentTableUI<SetLonglineGlobalCompositionDto, FloatlinesCompositionDto> ui, + List<ContentTableMeta<FloatlinesCompositionDto>> contentTableMetas) { + + return new ContentTableModel<SetLonglineGlobalCompositionDto, FloatlinesCompositionDto>(ui, contentTableMetas) { + private static final long serialVersionUID = 1L; + @Override + protected Collection<FloatlinesCompositionDto> getChilds(SetLonglineGlobalCompositionDto bean) { + return bean.getFloatlinesComposition(); + } + + @Override + protected void load(FloatlinesCompositionDto source, FloatlinesCompositionDto target) { + FloatlinesCompositionDtos.copyFloatlinesCompositionDto(source, target); + } + + @Override + protected void setChilds(SetLonglineGlobalCompositionDto parent, List<FloatlinesCompositionDto> childs) { + parent.setFloatlinesComposition(childs); + } + }; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/GearUseFeaturesLonglineTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/GearUseFeaturesLonglineTableModel.java new file mode 100644 index 0000000..4018f92 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/GearUseFeaturesLonglineTableModel.java @@ -0,0 +1,175 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Sets; +import fr.ird.observe.services.dto.longline.GearUseFeaturesLonglineDto; +import fr.ird.observe.services.dto.longline.GearUseFeaturesLonglineDtos; +import fr.ird.observe.services.dto.longline.GearUseFeaturesMeasurementLonglineDto; +import fr.ird.observe.services.dto.longline.TripLonglineGearUseDto; +import fr.ird.observe.services.dto.referential.GearDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.Collection; +import java.util.List; + +/** + * Created on 4/7/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.16 + */ +public class GearUseFeaturesLonglineTableModel extends ContentTableModel<TripLonglineGearUseDto, GearUseFeaturesLonglineDto> { + + /** Logger. */ + private static final Log log = LogFactory.getLog(GearUseFeaturesLonglineTableModel.class); + + private static final long serialVersionUID = 1L; + + private transient GearUseFeaturesLonglineUIHandler gearUseFeaturesLonglineUIHandler; + + public GearUseFeaturesLonglineTableModel(ObserveContentTableUI<TripLonglineGearUseDto, GearUseFeaturesLonglineDto> context, + List<ContentTableMeta<GearUseFeaturesLonglineDto>> contentTableMetas) { + super(context, contentTableMetas); + } + + public void setGearUseFeaturesLonglineUIHandler(GearUseFeaturesLonglineUIHandler gearUseFeaturesLonglineUIHandler) { + this.gearUseFeaturesLonglineUIHandler = gearUseFeaturesLonglineUIHandler; + } + + @Override + public void addNewEntry() { + + int editingRow = getSelectedRow(); + + if (editingRow > -1) { + + // store sizes and weights for the selected row + // before creating a new one ? + GearUseFeaturesLonglineUIModel model = getModel(); + model.getMeasurementsTableModel().storeInCacheForRow(editingRow); + + } + + super.addNewEntry(); + } + + @Override + public void updateRowFromEditBean() { + + GearUseFeaturesLonglineUIModel model = getModel(); + + int editingRow = getSelectedRow(); + GearUseFeaturesLonglineDto rowBean = getRowBean(); + GearUseFeaturesMeasurementLonglinesTableModel measurementsTableModel = model.getMeasurementsTableModel(); + + List<GearUseFeaturesMeasurementLonglineDto> measurements; + + if (rowBean.getId() == null && CollectionUtils.isEmpty(measurementsTableModel.getCacheForRow(editingRow))) { + + // new gear usage, add default measurements + + ReferentialReference<GearDto> gear = rowBean.getGear(); + measurements = gearUseFeaturesLonglineUIHandler.getDefaultGearUseFeaturesMeasurementLongline(gear.getId()); + if (log.isInfoEnabled()) { + log.info("Create mode, use default measurements: " + measurements.size()); + } + measurementsTableModel.removeCacheForRow(editingRow); + measurementsTableModel.initCacheForRow(editingRow, measurements); + + measurementsTableModel.setData(measurements); + measurementsTableModel.setModified(false); + + } else { + + // store current measurements for the selected row + measurementsTableModel.storeInCacheForRow(editingRow); + measurements = measurementsTableModel.getData(); + } + + rowBean.setGearUseFeaturesMeasurement(Sets.newLinkedHashSet(measurements)); + + super.updateRowFromEditBean(); + + } + + @Override + protected void removeRow(int row) { + super.removeRow(row); + + // remove sizes and weights for the deleted row + // also update rows to row - 1 (when after the deleted row) + GearUseFeaturesLonglineUIModel model = getModel(); + model.getMeasurementsTableModel().removeCacheForRow(row); + + } + + @Override + protected void setChilds(TripLonglineGearUseDto parent, List<GearUseFeaturesLonglineDto> childs) { + parent.getGearUseFeaturesLongline().clear(); + parent.addAllGearUseFeaturesLongline(childs); + } + + @Override + public void resetEditBean() { + + int row = getSelectedRow(); + if (log.isInfoEnabled()) { + log.info("Reset edit bean at row: " + row); + } + GearUseFeaturesLonglineUIModel model = getModel(); + model.getMeasurementsTableModel().resetCacheForRow(row); + + super.resetEditBean(); + + } + + @Override + protected Collection<GearUseFeaturesLonglineDto> getChilds(TripLonglineGearUseDto bean) { + return bean.getGearUseFeaturesLongline(); + } + + @Override + protected void load(GearUseFeaturesLonglineDto source, GearUseFeaturesLonglineDto target) { + GearUseFeaturesLonglineDtos.copyGearUseFeaturesLonglineDto(source, target); + } + + @Override + protected void resetRow(int row) { + super.resetRow(row); + + GearUseFeaturesLonglineUIModel model = getModel(); + model.getMeasurementsTableModel().resetCacheForRow(row); + } + + @Override + protected GearUseFeaturesLonglineUIModel getModel() { + return (GearUseFeaturesLonglineUIModel) super.getModel(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/GearUseFeaturesLonglineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/GearUseFeaturesLonglineUI.jaxx new file mode 100644 index 0000000..efd3652 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/GearUseFeaturesLonglineUI.jaxx @@ -0,0 +1,155 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.table.ContentTableUI + superGenericType='TripLonglineGearUseDto, GearUseFeaturesLonglineDto' + contentTitle='{n("observe.content.gearUseFeaturesLongline.title")}' + saveNewEntryText='{n("observe.content.action.gearUseFeaturesLongline")}' + saveNewEntryTip='{n("observe.content.action.gearUseFeaturesLongline.tip")}'> + + <style source="../../CommonTable.jcss"/> + + <import> + fr.ird.observe.services.dto.CommentableDto + fr.ird.observe.services.dto.longline.TripLonglineDto + fr.ird.observe.services.dto.longline.GearUseFeaturesLonglineDto + fr.ird.observe.services.dto.longline.GearUseFeaturesMeasurementLonglineDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.GearDto + fr.ird.observe.application.swing.ui.content.table.* + fr.ird.observe.application.swing.ui.util.BooleanEditor + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + java.awt.Dimension + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <GearUseFeaturesLonglineUIHandler id='handler' constructorParams='this'/> + + <!-- model --> + <GearUseFeaturesLonglineUIModel id='model' constructorParams='this'/> + + <GearUseFeaturesMeasurementLonglinesTableModel id='measurementsTableModel' + initializer="getModel().getMeasurementsTableModel()"/> + + <!-- edit bean --> + <TripLonglineDto id='bean'/> + + <!-- table edit bean --> + <GearUseFeaturesLonglineDto id='tableEditBean'/> + + <!-- table model --> + <ContentTableModel id='tableModel'/> + + <!-- le validateur de l'écran --> + <BeanValidator id='validator' + beanClass='fr.ird.observe.services.dto.longline.TripLonglineGearUseDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update'/> + + <!-- le validateur d'une entrée de tableau --> + <BeanValidator id='validatorTable' + autoField='true' + beanClass='fr.ird.observe.services.dto.longline.GearUseFeaturesLonglineDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update'/> + + <JPopupMenu id='measurementsTablePopup'> + <JMenuItem id='addMeasurement' onActionPerformed='getHandler().addMeasurement()'/> + <JMenuItem id='deleteSelectedMeasurement' onActionPerformed='getHandler().deleteSelectedMeasurement()'/> + </JPopupMenu> + + <Table id='editorPanel' fill='both' insets='0' weighty="1"> + <row> + <cell weightx="1" weighty="0.9"> + + <JTabbedPane id='gearUseFeaturesTabPane'> + + <tab id='generalTab'> + + <JPanel layout='{new BorderLayout()}'> + + <Table id='editForm' fill='both' insets='1' constraints="BorderLayout.NORTH"> + + <!-- gear --> + <row> + <cell> + <JLabel id='gearLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='gear' constructorParams='this' genericType='ReferentialReference<GearDto>' _entityClass='GearDto.class'/> + </cell> + </row> + + <!-- number --> + <row> + <cell> + <JLabel id='numberLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='number' constructorParams='this'/> + </cell> + </row> + + <!-- usedInTrip --> + <row> + <cell> + <JLabel id='usedInTripLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BooleanEditor id='usedInTrip'/> + </cell> + </row> + + </Table> + + </JPanel> + + + </tab> + + <tab id='measurementsFormTab'> + + <JScrollPane id='measurementsScrollPane'> + <JTable id='measurementsTable'/> + </JScrollPane> + + </tab> + </JTabbedPane> + + </cell> + </row> + <row> + <cell weighty='0.1'> + <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2'/> + </JScrollPane> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/GearUseFeaturesLonglineUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/GearUseFeaturesLonglineUI.jcss new file mode 100644 index 0000000..e384f13 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/GearUseFeaturesLonglineUI.jcss @@ -0,0 +1,105 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#model { + valid:{validator.isValid() && validatorTable.isValid() && getMeasurementsTableModel().isValid()}; + canSaveRow:{validatorTable.isChanged() && validatorTable.isValid() && getMeasurementsTableModel().isValid()}; + canResetRow:{validatorTable.isChanged()}; +} + +/* ***************************************************************************** */ +/* GENERAL TAB **************************************************************** */ +/* ***************************************************************************** */ + +#generalTab { + title:{t("observe.content.gearUseFeaturesLongline.tab.general")}; + icon:{handler.getErrorIconIfFalse(model.isGeneralTabValid())}; +} + +#gearLabel { + text:"observe.content.gearUseFeaturesLongline.gear"; + labelFor:{gear}; +} + +#gear { + property:{GearUseFeaturesLonglineDto.PROPERTY_GEAR}; + selectedItem:{tableEditBean.getGear()}; +} + +#numberLabel { + text:"observe.content.gearUseFeaturesLongline.number"; + labelFor:{number}; +} + +#number { + property:{GearUseFeaturesLonglineDto.PROPERTY_NUMBER}; + model:{tableEditBean.getNumber()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; +} + +#usedInTripLabel { + text:"observe.content.gearUseFeaturesLongline.usedInTrip"; + labelFor:{usedInTrip}; +} + +#usedInTrip { + booleanValue:{tableEditBean.getUsedInTrip()}; + _tablePropertyName:{GearUseFeaturesLonglineDto.PROPERTY_USED_IN_TRIP}; +} + +/* ***************************************************************************** */ +/* MEASUREMENTS TAB *********************************************************** */ +/* ***************************************************************************** */ + +#measurementsFormTab { + title:{t("observe.content.gearUseFeaturesLongline.tab.measurements")}; + icon:{handler.getErrorIconIfFalse(measurementsTableModel.isValid())}; + enabled:{!tableModel.isCreate()}; +} + +#measurementsTable { + model: {measurementsTableModel}; +} + +#comment { + columnHeaderView:{new JLabel(t("observe.content.gearUseFeaturesLongline.comment"))}; + minimumSize:{new Dimension(10,80)}; +} + +#comment2 { + _tablePropertyName: {GearUseFeaturesLonglineDto.PROPERTY_COMMENT}; + text:{getStringValue(tableEditBean.getComment())}; +} + +#addMeasurement { + text: "observe.content.gearUseFeaturesLongline.action.addMeasurement"; + toolTipText: "observe.content.gearUseFeaturesLongline.action.addMeasurement.tip"; + actionIcon: add; +} + + + +#deleteSelectedMeasurement { + text: "observe.content.gearUseFeaturesLongline.action.deleteSelectedMeasurement"; + toolTipText: "observe.content.gearUseFeaturesLongline.action.deleteSelectedMeasurement.tip"; + actionIcon: delete; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/GearUseFeaturesLonglineUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/GearUseFeaturesLonglineUIHandler.java new file mode 100644 index 0000000..32c0d37 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/GearUseFeaturesLonglineUIHandler.java @@ -0,0 +1,508 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.longline.GearUseFeaturesLonglineDto; +import fr.ird.observe.services.dto.longline.GearUseFeaturesMeasurementLonglineDto; +import fr.ird.observe.services.dto.longline.TripLonglineGearUseDto; +import fr.ird.observe.services.dto.longline.TripLonglineGearUseDtos; +import fr.ird.observe.services.dto.referential.GearCaracteristicDto; +import fr.ird.observe.services.dto.referential.GearCaracteristicTypeDtos; +import fr.ird.observe.services.dto.referential.GearDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.service.ReferentialService; +import fr.ird.observe.services.service.longline.TripLonglineGearUseService; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.ContentUIInitializer; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIHandler; +import fr.ird.observe.application.swing.ui.content.table.impl.seine.GearUseFeatureMeasurementCellEditor; +import fr.ird.observe.application.swing.ui.content.table.impl.seine.GearUseFeatureMeasurementCellRenderer; +import jaxx.runtime.SwingUtil; +import jaxx.runtime.validator.swing.SwingValidatorMessage; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.JComponent; +import javax.swing.JOptionPane; +import javax.swing.JTable; +import javax.swing.event.TableModelListener; +import javax.swing.table.DefaultTableCellRenderer; +import java.awt.GridBagConstraints; +import java.awt.Insets; +import java.beans.PropertyChangeListener; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 3/24/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.16 + */ +public class GearUseFeaturesLonglineUIHandler extends ContentTableUIHandler<TripLonglineGearUseDto, GearUseFeaturesLonglineDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(GearUseFeaturesLonglineUIHandler.class); + + // Compute valid state of tab from the error table + protected final TableModelListener computeTabValidStateListener; + + private final PropertyChangeListener measurementsTableModelModified; + + public GearUseFeaturesLonglineUIHandler(GearUseFeaturesLonglineUI ui) { + super(ui, DataContextType.TripLongline); + computeTabValidStateListener = e -> { + + SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); + computeTabValidState(source); + + }; + measurementsTableModelModified = evt -> onMeasurementsTableModelModified((Boolean) evt.getNewValue()); + } + + @Override + public GearUseFeaturesLonglineUI getUi() { + return (GearUseFeaturesLonglineUI) super.getUi(); + } + + @Override + public GearUseFeaturesLonglineUIModel getModel() { + return (GearUseFeaturesLonglineUIModel) super.getModel(); + } + + @Override + public void initUI() { + + super.initUI(); + + getModel().addPropertyChangeListener(GearUseFeaturesLonglineUIModel.PROPERTY_EDITABLE, evt -> { + Boolean newValue = (Boolean) evt.getNewValue(); + setTableModelEditable(newValue); + }); + + setTableModelEditable(getModel().isEditable()); + + getTableModel().setGearUseFeaturesLonglineUIHandler(this); + + } + + @Override + public void openUI() { + + if (log.isInfoEnabled()) { + log.info("OpenUI: " + getModel()); + } + + super.openUI(); + + // To be sure always remove listener (could prevent some leaks) + getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); + // listen messages to see if required to add + getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); + + SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); + computeTabValidState(errorTableModel); + + } + + @Override + public void startEditUI(String... binding) { + + getModel().getMeasurementsTableModel().setEditable(true); + + super.startEditUI(binding); + + } + + public void addMeasurement() { + + GearUseFeaturesMeasurementLonglinesTableModel tableModel = getUi().getMeasurementsTableModel(); + tableModel.addNewRow(); + + } + + public void deleteSelectedMeasurement() { + + GearUseFeaturesMeasurementLonglinesTableModel tableModel = getUi().getMeasurementsTableModel(); + + boolean selectionEmpty = tableModel.isSelectionEmpty(); + + if (!selectionEmpty) { + + GearUseFeaturesMeasurementLonglineDto data = tableModel.getSelectedRow(); + + if (log.isInfoEnabled()) { + log.info("Delete: " + data); + } + + ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); + int response = UIHelper.askUser(mainUI, + t("observe.title.delete"), + t("observe.content.measurement.delete.message"), + JOptionPane.WARNING_MESSAGE, + new Object[]{t("observe.choice.confirm.delete"), + t("observe.choice.cancel")}, + 1); + + if (response != 0) { + + // user cancel + return; + } + + tableModel.removeSelectedRow(); + + } + + } + + public List<GearUseFeaturesMeasurementLonglineDto> getDefaultGearUseFeaturesMeasurementLongline(String gearId) { + + ReferentialService referentialService = getDataSource().newReferentialService(); + + Form<GearDto> gearDtoForm = referentialService.loadForm(GearDto.class, gearId); + + GearDto gearDto = gearDtoForm.getObject(); + + List<GearUseFeaturesMeasurementLonglineDto> measurements = Lists.newArrayList( + Iterables.transform(gearDto.getGearCaracteristic(), + input -> { + GearUseFeaturesMeasurementLonglineDto measurementLonglineDto = new GearUseFeaturesMeasurementLonglineDto(); + measurementLonglineDto.setGearCaracteristic(input); + String gearCaracterisiticTypeId = (String) input.getPropertyValue(GearCaracteristicDto.PROPERTY_GEAR_CARACTERISTIC_TYPE); + if (GearCaracteristicTypeDtos.isBoolean(gearCaracterisiticTypeId)) { + measurementLonglineDto.setMeasurementValue(Boolean.FALSE.toString()); + } + return measurementLonglineDto; + })); + + return measurements; + } + + @Override + protected void onSelectedRowChanged(int editingRow, GearUseFeaturesLonglineDto bean, boolean create) { + + if (log.isInfoEnabled()) { + log.info("Selected row changed: " + editingRow + ", create? " + create); + } + + GearUseFeaturesLonglineUI ui = getUi(); + + UIHelper.stopEditing(ui.getMeasurementsTable()); + + GearUseFeaturesLonglineTableModel tableModel = getTableModel(); + GearUseFeaturesLonglineUIModel model = getModel(); + + boolean emptySelection = editingRow == -1; + + // load size measures + + GearUseFeaturesMeasurementLonglinesTableModel measurementsTableModel = model.getMeasurementsTableModel(); + List<GearUseFeaturesMeasurementLonglineDto> measurements = emptySelection ? Collections.emptyList() : measurementsTableModel.getCacheForRow(editingRow); + if (measurements == null) { + + if (log.isInfoEnabled()) { + log.info("init measurements for row " + editingRow); + } + + // first time coming on this row + + if (tableModel.isCreate()) { + + // create mode: just init with empty list + measurements = Collections.emptyList(); + + if (log.isInfoEnabled()) { + log.info("create mode, use an empty list"); + } + + } else { + + measurements = Lists.newArrayList(bean.getGearUseFeaturesMeasurement()); + + } + + // init measurements + measurementsTableModel.initCacheForRow(editingRow, measurements); + + } else { + + if (log.isInfoEnabled()) { + log.info("Using existing measurements for row " + editingRow + " : " + measurements.size()); + } + } + + measurementsTableModel.setData(measurements); + + measurementsTableModel.setModified(false); + measurementsTableModel.setEditable(tableModel.isEditable()); + + if (!tableModel.isEditable()) { + return; + } + + JComponent requestFocus; + + if (tableModel.isCreate()) { + + // go back to first pane + ui.getGearUseFeaturesTabPane().setSelectedIndex(0); + + requestFocus = ui.getGear(); + + } else { + + requestFocus = ui.getGear(); + + } + + requestFocus.requestFocus(); + + } + + @Override + protected void initTableUI(DefaultTableCellRenderer renderer) { + + { + JTable table = getUi().getTable(); + + UIHelper.setI18nTableHeaderRenderer(table, + n("observe.content.gearUseFeaturesLongline.table.gear"), + n("observe.content.gearUseFeaturesLongline.table.gear.tip"), + n("observe.content.gearUseFeaturesLongline.table.number"), + n("observe.content.gearUseFeaturesLongline.table.number.tip"), + n("observe.content.gearUseFeaturesLongline.table.usedInTrip"), + n("observe.content.gearUseFeaturesLongline.table.usedInTrip.tip"), + n("observe.content.gearUseFeaturesLongline.table.comment"), + n("observe.content.gearUseFeaturesLongline.table.comment.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, GearDto.class)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 2, UIHelper.newBooleanTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 3, UIHelper.newStringTableCellRenderer(renderer, 10, true)); + } + + { + // init measurements table + JTable table = getUi().getMeasurementsTable(); + + UIHelper.setI18nTableHeaderRenderer(table, + n("observe.content.gearUseFeaturesLongline.table.gearCaracteristic"), + n("observe.content.gearUseFeaturesLongline.table.gearCaracteristic.tip"), + n("observe.content.gearUseFeaturesLongline.table.value"), + n("observe.content.gearUseFeaturesLongline.table.value.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, GearCaracteristicDto.class)); + UIHelper.setTableColumnRenderer(table, 1, new GearUseFeatureMeasurementCellRenderer(0, renderer)); + + table.getTableHeader().setReorderingAllowed(false); + + ReferentialReferenceDecorator<GearCaracteristicDto> decorator = getReferentialReferenceDecorator(GearCaracteristicDto.class); + + List<ReferentialReference<GearCaracteristicDto>> caracteristics = Lists.newArrayList(getDataSource().getReferentialReferences(GearCaracteristicDto.class)); + + UIHelper.setTableColumnEditor(table, 0, ContentUIInitializer.newDataColumnEditor(caracteristics, decorator)); + UIHelper.setTableColumnEditor(table, 1, new GearUseFeatureMeasurementCellEditor(0)); + + initInlineTable(getUi().getMeasurementsScrollPane(), + table, + getModel().getMeasurementsTableModel(), + measurementsTableModelModified, + getUi().getMeasurementsTablePopup(), + getUi().getAddMeasurement(), + getUi().getDeleteSelectedMeasurement()); + + } + + // Adapt layout to let more place for the editor + + getUi().getShowForm().remove(1); + getUi().getShowForm().add(SwingUtil.boxComponentWithJxLayer(getUi().getEditor()), new GridBagConstraints(0, 1, 1, 1, 1.0, 0.3, 10, 1, new Insets(0, 0, 0, 0), 0, 0), 1); + getUi().getEditor().remove(0); + getUi().getEditor().add(SwingUtil.boxComponentWithJxLayer(getUi().getEditorPanel()), new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, 10, 1, new Insets(0, 0, 0, 0), 0, 0), 0); + + + } + + @Override + protected String getEditBeanIdToLoad() { + return getDataContext().getSelectedTripLonglineId(); + } + + @Override + protected void closeSafeUI() { + + if (log.isInfoEnabled()) { + log.info("CloseUI: " + getModel()); + } + super.closeSafeUI(); + + // remove listener + getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); + + } + + @Override + protected void resetEditBean() { + + UIHelper.stopEditing(getUi().getMeasurementsTable()); + + super.resetEditBean(); + + } + + @Override + public void resetEditUI() { + + getModel().getMeasurementsTableModel().clear(); + + super.resetEditUI(); + + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + // par defaut, on suppose qu'on peut afficher les données + getModel().setShowData(true); + + String selectedTripId = dataContext.getSelectedTripId(); + + if (getOpenDataManager().isOpenTripLongline(selectedTripId)) { + + // mode mise a jour + return ContentMode.UPDATE; + } + + // mode lecture + + if (dataContext.isSelectedTripLongline()) { + + addInfoMessage(t("observe.content.tripLongline.message.not.open")); + + } else { + + addInfoMessage(t("observe.content.tripLongline.message.not.open")); + + } + + return ContentMode.READ; + } + + @Override + protected GearUseFeaturesLonglineTableModel getTableModel() { + return (GearUseFeaturesLonglineTableModel) super.getTableModel(); + } + + protected void setTableModelEditable(Boolean newValue) { + + getModel().getMeasurementsTableModel().setEditable(newValue); + + } + + protected void onMeasurementsTableModelModified(Boolean newValue) { + + if (newValue) { + + // modify the validator, since this is the best way to prevent table edit form actions + // that something was modified on the form + getUi().getValidatorTable().setChanged(true); + + } + + // recompute table model valid state + getModel().getMeasurementsTableModel().validate(); + + } + + protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { + + Set<String> errorProperties = new HashSet<>(); + int rowCount = errorTableModel.getRowCount(); + for (int i = 0; i < rowCount; i++) { + + SwingValidatorMessage row = errorTableModel.getRow(i); + if (NuitonValidatorScope.ERROR.equals(row.getScope())) { + errorProperties.add(row.getField()); + } + } + + boolean generalTabValid = !errorProperties.removeAll(GearUseFeaturesLonglineUIModel.GENERAL_TAB_PROPERTIES); + + GearUseFeaturesLonglineUIModel model = getModel(); + + model.setGeneralTabValid(generalTabValid); + + } + + @Override + protected void doPersist(TripLonglineGearUseDto bean) { + + // On ne persiste pas les measurements qui sont vides + for (GearUseFeaturesLonglineDto gearUseFeatures : bean.getGearUseFeaturesLongline()) { + if (!gearUseFeatures.isGearUseFeaturesMeasurementEmpty()) { + Iterator<GearUseFeaturesMeasurementLonglineDto> iterator = gearUseFeatures.getGearUseFeaturesMeasurement().iterator(); + while (iterator.hasNext()) { + GearUseFeaturesMeasurementLonglineDto gearUseFeaturesMeasurement = iterator.next(); + if (gearUseFeaturesMeasurement.isEmpty()) { + iterator.remove(); + } + } + } + } + SaveResultDto saveResult = getTripLonglineGearUseService().save(bean); + saveResult.toDto(bean); + + } + + @Override + protected void loadEditBean(String beanId) { + Form<TripLonglineGearUseDto> form = getTripLonglineGearUseService().loadForm(beanId); + loadReferentialReferenceSetsInModel(form); + getModel().setForm(form); + TripLonglineGearUseDtos.copyTripLonglineGearUseDto(form.getObject(), getBean()); + } + + protected TripLonglineGearUseService getTripLonglineGearUseService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripLonglineGearUseService(); + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/GearUseFeaturesLonglineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/GearUseFeaturesLonglineUIModel.java new file mode 100644 index 0000000..8009d54 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/GearUseFeaturesLonglineUIModel.java @@ -0,0 +1,106 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import fr.ird.observe.services.dto.longline.GearUseFeaturesLonglineDto; +import fr.ird.observe.services.dto.longline.TripLonglineGearUseDto; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; + +import java.util.List; +import java.util.Set; + +/** + * Created on 3/24/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.16 + */ +public class GearUseFeaturesLonglineUIModel extends ContentTableUIModel<TripLonglineGearUseDto, GearUseFeaturesLonglineDto> { + + private static final long serialVersionUID = 1L; + + public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; + + public static final Set<String> GENERAL_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(GearUseFeaturesLonglineDto.PROPERTY_GEAR, + GearUseFeaturesLonglineDto.PROPERTY_NUMBER, + GearUseFeaturesLonglineDto.PROPERTY_USED_IN_TRIP, + GearUseFeaturesLonglineDto.PROPERTY_COMMENT).build(); + + protected boolean generalTabValid; + + private final GearUseFeaturesMeasurementLonglinesTableModel measurementsTableModel; + + public GearUseFeaturesLonglineUIModel(GearUseFeaturesLonglineUI ui) { + + super(TripLonglineGearUseDto.class, + GearUseFeaturesLonglineDto.class, + new String[]{ + TripLonglineGearUseDto.PROPERTY_ID, + TripLonglineGearUseDto.PROPERTY_GEAR_USE_FEATURES_LONGLINE, + TripLonglineGearUseDto.PROPERTY_LAST_UPDATE_DATE, + }, + new String[]{ + GearUseFeaturesLonglineDto.PROPERTY_ID, + GearUseFeaturesLonglineDto.PROPERTY_COMMENT, + GearUseFeaturesLonglineDto.PROPERTY_GEAR, + GearUseFeaturesLonglineDto.PROPERTY_NUMBER, + GearUseFeaturesLonglineDto.PROPERTY_USED_IN_TRIP}); + + this.measurementsTableModel = new GearUseFeaturesMeasurementLonglinesTableModel(); + + List<ContentTableMeta<GearUseFeaturesLonglineDto>> metas = Lists.newArrayList( + ContentTableModel.newTableMeta(GearUseFeaturesLonglineDto.class, GearUseFeaturesLonglineDto.PROPERTY_GEAR, false), + ContentTableModel.newTableMeta(GearUseFeaturesLonglineDto.class, GearUseFeaturesLonglineDto.PROPERTY_NUMBER, false), + ContentTableModel.newTableMeta(GearUseFeaturesLonglineDto.class, GearUseFeaturesLonglineDto.PROPERTY_USED_IN_TRIP, false), + ContentTableModel.newTableMeta(GearUseFeaturesLonglineDto.class, GearUseFeaturesLonglineDto.PROPERTY_COMMENT, false) + ); + + initModel(ui, metas); + + } + + @Override + protected GearUseFeaturesLonglineTableModel createTableModel(ObserveContentTableUI<TripLonglineGearUseDto, GearUseFeaturesLonglineDto> ui, List<ContentTableMeta<GearUseFeaturesLonglineDto>> contentTableMetas) { + return new GearUseFeaturesLonglineTableModel(ui, contentTableMetas); + } + + public GearUseFeaturesMeasurementLonglinesTableModel getMeasurementsTableModel() { + return measurementsTableModel; + } + + public boolean isGeneralTabValid() { + return generalTabValid; + } + + public void setGeneralTabValid(boolean generalTabValid) { + this.generalTabValid = generalTabValid; + firePropertyChange(PROPERTY_GENERAL_TAB_VALID, null, isGeneralTabValid()); + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/GearUseFeaturesMeasurementLonglinesTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/GearUseFeaturesMeasurementLonglinesTableModel.java new file mode 100644 index 0000000..ba865ed --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/GearUseFeaturesMeasurementLonglinesTableModel.java @@ -0,0 +1,136 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.longline.GearUseFeaturesMeasurementLonglineDto; +import fr.ird.observe.services.dto.referential.GearCaracteristicDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.util.table.EditableTableWithCacheTableModelSupport; + +/** + * Created on 4/7/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.16 + */ +public class GearUseFeaturesMeasurementLonglinesTableModel extends EditableTableWithCacheTableModelSupport<GearUseFeaturesMeasurementLonglineDto> { + + private static final long serialVersionUID = 1L; + + public GearUseFeaturesMeasurementLonglinesTableModel() { + super(); + } + + @Override + public boolean isRowNotEmpty(GearUseFeaturesMeasurementLonglineDto valid) { + return !(valid.getGearCaracteristic() == null && valid.getMeasurementValue() == null); + } + + @Override + protected boolean isRowValid(GearUseFeaturesMeasurementLonglineDto valid) { + String size = valid.getMeasurementValue(); + return !(valid.getGearCaracteristic() == null || size == null) && !size.isEmpty(); + } + + @Override + public int getColumnCount() { + return 2; + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + + GearUseFeaturesMeasurementLonglineDto measure = data.get(rowIndex); + Object result; + switch (columnIndex) { + case 0: + result = measure.getGearCaracteristic(); + break; + case 1: + result = measure.getMeasurementValue(); + break; + default: + throw new IllegalStateException("Can't come here"); + } + return result; + } + + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + + boolean result; + switch (columnIndex) { + case 0: + result = true; + break; + case 1: + GearUseFeaturesMeasurementLonglineDto measure = data.get(rowIndex); + result = measure != null && measure.getGearCaracteristic() != null; + break; + default: + throw new IllegalStateException("Can't come here"); + } + return result; + + } + + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + + GearUseFeaturesMeasurementLonglineDto measure = data.get(rowIndex); + switch (columnIndex) { + case 0: + + measure.setGearCaracteristic((ReferentialReference<GearCaracteristicDto>) aValue); + + break; + case 1: + + measure.setMeasurementValue(aValue == null ? null : String.valueOf(aValue)); + + break; + + default: + throw new IllegalStateException("Can't come here"); + } + + setModified(true); + + } + + @Override + public void removeSelectedRow() { + + super.removeSelectedRow(); + + // revalidate table model + validate(); + setModified(true); + + } + + @Override + protected GearUseFeaturesMeasurementLonglineDto createNewRow() { + return new GearUseFeaturesMeasurementLonglineDto(); + } +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/HooksCompositionUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/HooksCompositionUI.jaxx new file mode 100644 index 0000000..7805d84 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/HooksCompositionUI.jaxx @@ -0,0 +1,131 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.table.ContentTableUI + superGenericType='SetLonglineGlobalCompositionDto, HooksCompositionDto' + contentTitle='{n("observe.content.hooksComposition.title")}' + saveNewEntryText='{n("observe.content.hooksComposition.action.create")}' + saveNewEntryTip='{n("observe.content.hooksComposition.action.create.tip")}'> + + <style source="../../CommonTable.jcss"/> + + <import> + fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto + fr.ird.observe.services.dto.longline.HooksCompositionDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.longline.HookTypeDto + fr.ird.observe.services.dto.referential.longline.HookSizeDto + fr.ird.observe.application.swing.ui.content.table.* + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <HooksCompositionUIHandler id='handler'/> + + <!-- model --> + <HooksCompositionUIModel id='model'/> + + <!-- edit bean --> + <SetLonglineGlobalCompositionDto id='bean'/> + + <!-- table edit bean --> + <HooksCompositionDto id='tableEditBean'/> + + <!-- table model --> + <ContentTableModel id='tableModel'/> + + <!-- le validateur de l'écran --> + <BeanValidator id='validator' autoField='true' context='ui-update-hooksComposition' + beanClass='fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto' + errorTableModel='{getErrorTableModel()}'> + <field name="hooksComposition" component="editorPanel"/> + </BeanValidator> + + <!-- le validateur d'une entrée de tableau --> + <BeanValidator id='validatorTable' autoField='true' context='ui-update' + beanClass='fr.ird.observe.services.dto.longline.HooksCompositionDto' + errorTableModel='{getErrorTableModel()}'/> + + <Table id='editorPanel' fill='both' insets='1'> + + <!-- HookType --> + <row> + <cell> + <JLabel id='hookTypeLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='hookType' constructorParams='this' genericType='ReferentialReference<HookTypeDto>' _entityClass='HookTypeDto.class'/> + </cell> + </row> + + <!-- HookSize --> + <row> + <cell> + <JLabel id='hookSizeLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='hookSize' constructorParams='this' genericType='ReferentialReference<HookSizeDto>' _entityClass='HookSizeDto.class'/> + </cell> + </row> + + + <!-- hookOffset --> + <row> + <cell> + <JLabel id='hookOffsetLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='hookOffset' constructorParams='this'/> + </cell> + </row> + + <!-- proportion --> + <row> + <cell> + <JLabel id='proportionLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='proportion' constructorParams='this'/> + </cell> + </row> + + </Table> + + <Table id='extraZone' fill='both'> + + <!-- proportion sum --> + <row> + <cell> + <JLabel id='hooksCompositionProportionSumLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <JLabel id='hooksCompositionProportionSum'/> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/HooksCompositionUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/HooksCompositionUI.jcss new file mode 100644 index 0000000..e40fe95 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/HooksCompositionUI.jcss @@ -0,0 +1,79 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#hookTypeLabel { + text:"observe.content.hooksComposition.hookType"; + labelFor:{hookType}; +} + +#hookType { + property:{HooksCompositionDto.PROPERTY_HOOK_TYPE}; + selectedItem:{tableEditBean.getHookType()}; + _validatorLabel:{t("observe.content.hooksComposition.hookType")}; +} + +#hookSizeLabel { + text:"observe.content.hooksComposition.hookSize"; + labelFor:{hookSize}; +} + +#hookSize { + property:{HooksCompositionDto.PROPERTY_HOOK_SIZE}; + selectedItem:{tableEditBean.getHookSize()}; + _validatorLabel:{t("observe.content.hooksComposition.hookSize")}; +} + + +#hookOffsetLabel { + text:"observe.content.hooksComposition.hookOffset"; + labelFor:{hookOffset}; +} + +#hookOffset { + property:{HooksCompositionDto.PROPERTY_HOOK_OFFSET}; + model:{tableEditBean.getHookOffset()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.hooksComposition.hookOffset")}; +} + +#proportionLabel { + text:"observe.content.hooksComposition.proportion"; + labelFor:{proportion}; +} + +#proportion { + property:{HooksCompositionDto.PROPERTY_PROPORTION}; + model:{tableEditBean.getProportion()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; + _validatorLabel:{t("observe.content.hooksComposition.proportion")}; +} + +#hooksCompositionProportionSumLabel { + text:"observe.content.hooksComposition.proportionSum"; + labelFor:{hooksCompositionProportionSum}; +} + +#hooksCompositionProportionSum { + text:{getStringValue(bean.getHooksCompositionProportionSum())}; + _validatorLabel:{t("observe.content.hooksComposition.proportionSum")}; + font-weight:bold; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/HooksCompositionUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/HooksCompositionUIHandler.java new file mode 100644 index 0000000..53d75b9 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/HooksCompositionUIHandler.java @@ -0,0 +1,120 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.longline.HooksCompositionDto; +import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto; +import fr.ird.observe.services.dto.referential.longline.HookSizeDto; +import fr.ird.observe.services.dto.referential.longline.HookTypeDto; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; + +import static org.nuiton.i18n.I18n.n; + +/** + * Created on 12/6/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.9 + */ +public class HooksCompositionUIHandler extends ContentTableUIHandler<SetLonglineGlobalCompositionDto, HooksCompositionDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(HooksCompositionUIHandler.class); + + public HooksCompositionUIHandler(HooksCompositionUI ui) { + super(ui, DataContextType.SetLongline); + } + + @Override + public HooksCompositionUI getUi() { + return (HooksCompositionUI) super.getUi(); + } + + @Override + protected void onSelectedRowChanged(int editingRow, HooksCompositionDto bean, boolean create) { + + if (getTableModel().isEditable()) { + if (log.isDebugEnabled()) { + log.debug("Row has changed to " + editingRow); + } + getUi().getHookType().requestFocus(); + } + + } + + @Override + protected void initTableUI(DefaultTableCellRenderer renderer) { + + JTable table = getUi().getTable(); + + UIHelper.setI18nTableHeaderRenderer( + table, + n("observe.content.hooksComposition.table.hookType"), + n("observe.content.hooksComposition.table.hookType.tip"), + n("observe.content.hooksComposition.table.hookSize"), + n("observe.content.hooksComposition.table.hookSize.tip"), + n("observe.content.hooksComposition.table.hookOffset"), + n("observe.content.hooksComposition.table.hookOffset.tip"), + n("observe.content.hooksComposition.table.proportion"), + n("observe.content.hooksComposition.table.proportion.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, HookTypeDto.class)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, HookSizeDto.class)); + UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + + // when model change in table, let's recompute the proportion sum + table.getModel().addTableModelListener(e -> { + int proportionSum = getBean().getHooksCompositionProportionSum(); + getBean().setHooksCompositionProportionSum(proportionSum); + }); + + } + + @Override + protected String getEditBeanIdToLoad() { + return getDataContext().getSelectedSetId(); + } + + @Override + public void afterSave(boolean refresh) { + super.afterSave(refresh); + } + + @Override + protected void doPersist(SetLonglineGlobalCompositionDto bean) { + // fait par le doSave de LonglineGlobalCompositionUIHandler + } + + @Override + protected void loadEditBean(String beanId) { + // fait par le loadEditBean de LonglineGlobalCompositionUIHandler + } +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/HooksCompositionUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/HooksCompositionUIModel.java new file mode 100644 index 0000000..4bb0901 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/HooksCompositionUIModel.java @@ -0,0 +1,92 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import fr.ird.observe.services.dto.longline.HooksCompositionDto; +import fr.ird.observe.services.dto.longline.HooksCompositionDtos; +import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; + +import java.util.Collection; +import java.util.List; + +/** + * Created on 12/6/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.9 + */ +public class HooksCompositionUIModel extends ContentTableUIModel<SetLonglineGlobalCompositionDto, HooksCompositionDto> { + + private static final long serialVersionUID = 1L; + + public HooksCompositionUIModel(HooksCompositionUI ui) { + super(SetLonglineGlobalCompositionDto.class, + HooksCompositionDto.class, + new String[]{ + SetLonglineGlobalCompositionDto.PROPERTY_HOOKS_COMPOSITION + }, + new String[]{HooksCompositionDto.PROPERTY_HOOK_TYPE, + HooksCompositionDto.PROPERTY_HOOK_SIZE, + HooksCompositionDto.PROPERTY_HOOK_OFFSET, + HooksCompositionDto.PROPERTY_PROPORTION}); + + List<ContentTableMeta<HooksCompositionDto>> metas = Lists.newArrayList( + ContentTableModel.newTableMeta(HooksCompositionDto.class, HooksCompositionDto.PROPERTY_HOOK_TYPE, false), + ContentTableModel.newTableMeta(HooksCompositionDto.class, HooksCompositionDto.PROPERTY_HOOK_SIZE, false), + ContentTableModel.newTableMeta(HooksCompositionDto.class, HooksCompositionDto.PROPERTY_HOOK_OFFSET, false), + ContentTableModel.newTableMeta(HooksCompositionDto.class, HooksCompositionDto.PROPERTY_PROPORTION, false)); + + initModel(ui, metas); + + } + + + @Override + protected ContentTableModel<SetLonglineGlobalCompositionDto, HooksCompositionDto> createTableModel( + ObserveContentTableUI<SetLonglineGlobalCompositionDto, HooksCompositionDto> ui, + List<ContentTableMeta<HooksCompositionDto>> contentTableMetas) { + + return new ContentTableModel<SetLonglineGlobalCompositionDto, HooksCompositionDto>(ui, contentTableMetas) { + private static final long serialVersionUID = 1L; + @Override + protected Collection<HooksCompositionDto> getChilds(SetLonglineGlobalCompositionDto bean) { + return bean.getHooksComposition(); + } + + @Override + protected void load(HooksCompositionDto source, HooksCompositionDto target) { + HooksCompositionDtos.copyHooksCompositionDto(source, target); + } + + @Override + protected void setChilds(SetLonglineGlobalCompositionDto parent, List<HooksCompositionDto> childs) { + parent.setHooksComposition(childs); + } + }; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/LonglinePositionHelper.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/LonglinePositionHelper.java new file mode 100644 index 0000000..29235ee --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/LonglinePositionHelper.java @@ -0,0 +1,318 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.longline.BasketDto; +import fr.ird.observe.services.dto.longline.BranchlineDto; +import fr.ird.observe.services.dto.longline.CatchLonglineDto; +import fr.ird.observe.services.dto.longline.LonglinePositionAwareDto; +import fr.ird.observe.services.dto.longline.LonglinePositionSetDto; +import fr.ird.observe.services.dto.longline.SectionDto; +import jaxx.runtime.swing.editor.bean.BeanComboBox; + +import java.beans.PropertyChangeListener; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.stream.Collectors; + +/** + * Created on 1/6/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.11 + */ +public class LonglinePositionHelper<D extends LonglinePositionAwareDto> { + + protected final BeanComboBox<DataReference<SectionDto>> uiSection; + + protected final BeanComboBox<DataReference<BasketDto>> uiBasket; + + protected final BeanComboBox<DataReference<BranchlineDto>> uiBranchline; + + // To avoid any propagation when doing some works on locations + protected boolean locationIsAdjusting; + + protected Collection<DataReference<SectionDto>> sectionUniverse; + + protected Collection<DataReference<BasketDto>> basketUniverse; + + protected Collection<DataReference<BranchlineDto>> branchlineUniverse; + + public LonglinePositionHelper(BeanComboBox<DataReference<SectionDto>> uiSection, + BeanComboBox<DataReference<BasketDto>> uiBasket, + BeanComboBox<DataReference<BranchlineDto>> uiBranchline, + D tableEditBean) { + + this.uiSection = uiSection; + this.uiBasket = uiBasket; + this.uiBranchline = uiBranchline; + + PropertyChangeListener sectionChanged = evt -> onSectionChanged((DataReference<SectionDto>) evt.getNewValue(), (D) evt.getSource()); + tableEditBean.addPropertyChangeListener(CatchLonglineDto.PROPERTY_SECTION, sectionChanged); + + PropertyChangeListener basketChanged = evt -> onBasketChanged((DataReference<BasketDto>) evt.getNewValue(), (D) evt.getSource()); + tableEditBean.addPropertyChangeListener(CatchLonglineDto.PROPERTY_BASKET, basketChanged); + + } + + public void initSections(LonglinePositionSetDto positionSetDto, + Collection<D> dtos) { + + this.sectionUniverse = positionSetDto.getSections(); + this.basketUniverse = positionSetDto.getBaskets(); + this.branchlineUniverse = positionSetDto.getBranchlines(); + + for (D dto : dtos) { + + DataReference<BranchlineDto> branchline = dto.getBranchline(); + + if (branchline != null) { + + DataReference<BasketDto> basket = getBasket(branchline); + dto.setBasket(basket); + + } + + DataReference<BasketDto> basket = dto.getBasket(); + + if (basket != null) { + + DataReference<SectionDto> section = getSection(basket); + dto.setSection(section); + + } + } + } + + public void resetPosition(D dto) { + + DataReference<SectionDto> section = dto.getSection(); + DataReference<BasketDto> basket = dto.getBasket(); + DataReference<BranchlineDto> branchline = dto.getBranchline(); + + uiBranchline.setSelectedItem(null); + uiSection.setSelectedItem(null); + uiBasket.setSelectedItem(null); + + if (section != null) { + + // reload section (basket and branchlines universe will then changed) + uiSection.setSelectedItem(section); + + } + + if (basket != null) { + + // reload basket (branchlines universe will then changed) + uiBasket.setSelectedItem(basket); + + } + + if (branchline != null) { + + // reload branchline + uiBranchline.setSelectedItem(branchline); + + } + + } + + public void savePosition(List<D> dtos) { + + for (D dto : dtos) { + + if (dto.getBasket() != null) { + // remove section + dto.setSection(null); + } + + if (dto.getBranchline() != null) { + + // remove basket + dto.setBasket(null); + } + + } + + } + + public List<DataReference<SectionDto>> getSections() { + + List<DataReference<SectionDto>> sections = Lists.newArrayList(); + + if (sectionUniverse != null) { + + sections.addAll(sectionUniverse); + + } + + return sections; + } + + protected void onSectionChanged(DataReference<SectionDto> newValue, D dto) { + + locationIsAdjusting = true; + + try { + + DataReference<BasketDto> basket = dto.getBasket(); + DataReference<BranchlineDto> branchline = dto.getBranchline(); + + // on deselectionne le panier + dto.setBasket(null); + + // on deselectionne l'avançon + dto.setBranchline(null); + + // on vide l'ensemble des paniers + uiBasket.setData(Collections.emptyList()); + + // on vide l'ensemble des avançons + uiBranchline.setData(Collections.emptyList()); + + if (newValue != null) { + + // une section est sélectionnée + + // on remplit uniquement les paniers de cette section + List<DataReference<BasketDto>> baskets = getBaskets(newValue); + uiBasket.setData(Lists.newArrayList(baskets)); + + if (basket != null && baskets.contains(basket)) { + + // un panier est sélectionné + + // on repmlit uniquement les avançons du panier + List<DataReference<BranchlineDto>> branchlines = getBranchlines(basket); + uiBranchline.setData(Lists.newArrayList(branchlines)); + dto.setBasket(basket); + + if (branchline != null && branchlines.contains(branchline)) { + + // un avançon est sélectionné + dto.setBranchline(branchline); + + } + + } + + } + + } finally { + + locationIsAdjusting = false; + + } + + } + + protected void onBasketChanged(DataReference<BasketDto> newValue, D dto) { + + if (!locationIsAdjusting) { + + DataReference<BranchlineDto> branchline = dto.getBranchline(); + + // on deselectionne l'avançon + dto.setBranchline(null); + + // on vide l'ensemble des avançons + uiBranchline.setData(Collections.emptyList()); + + if (newValue != null) { + + // un panier est selectionne + + // on remplit uniquement les avançons des paniers + List<DataReference<BranchlineDto>> branchlines = getBranchlines(newValue); + uiBranchline.setData(branchlines); + + + if (branchline != null && branchlines.contains(branchline)) { + + // un avançon est sélectionné + dto.setBranchline(branchline); + + } + + } + + } + + } + + protected DataReference<SectionDto> getSection(DataReference<BasketDto> basket) { + + String sectionId = (String) basket.getPropertyValue(BasketDto.PROPERTY_SECTION); + + DataReference<SectionDto> section = sectionUniverse.stream() + // TODO sbavencoff 11/03/2016 utiliser le prédicat AbstractReference.newIdPredicate() + // A la migartion vers les prédicats JAVA8 + .filter(s -> sectionId.equals(s.getId())) + .findFirst() + .get(); + + return section; + + } + + protected DataReference<BasketDto> getBasket(DataReference<BranchlineDto> branchline) { + + String basketId = (String) branchline.getPropertyValue(BranchlineDto.PROPERTY_BASKET); + + DataReference<BasketDto> basket = basketUniverse.stream() + // TODO sbavencoff 11/03/2016 utiliser le prédicat DataReference.newLabelValuePredicate + // A la migartion vers les prédicats JAVA8 + .filter(b -> basketId.equals(b.getId())) + .findFirst() + .get(); + + return basket; + + } + + protected List<DataReference<BasketDto>> getBaskets(DataReference<SectionDto> section) { + + List<DataReference<BasketDto>> baskets = basketUniverse.stream() + // TODO sbavencoff 11/03/2016 utiliser le prédicat DataReference.newLabelValuePredicate + // A la migartion vers les prédicat JAVA8 + .filter(b -> section.getId().equals(b.getPropertyValue(BasketDto.PROPERTY_SECTION))) + .collect(Collectors.toList()); + + return baskets; + } + + protected List<DataReference<BranchlineDto>> getBranchlines(DataReference<BasketDto> basket) { + + List<DataReference<BranchlineDto>> branchlines = branchlineUniverse.stream() + // TODO sbavencoff 11/03/2016 utilise le prédicat DataReference.newLabelValuePredicate + // A la migartion vers les prédicat JAVA8 + .filter(b -> basket.getId().equals(b.getPropertyValue(BranchlineDto.PROPERTY_BASKET))) + .collect(Collectors.toList()); + + return branchlines; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/SensorUsedUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/SensorUsedUI.jaxx new file mode 100644 index 0000000..424abbe --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/SensorUsedUI.jaxx @@ -0,0 +1,163 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.table.ContentTableUI + superGenericType='ActivityLonglineSensorUsedDto, SensorUsedDto' + contentTitle='{n("observe.content.sensorUsed.title")}' + saveNewEntryText='{n("observe.content.sensorUsed.action.create")}' + saveNewEntryTip='{n("observe.content.sensorUsed.action.create.tip")}'> + + <style source="../../CommonTable.jcss"/> + + <import> + fr.ird.observe.services.dto.CommentableDto + fr.ird.observe.services.dto.longline.ActivityLonglineSensorUsedDto + fr.ird.observe.services.dto.longline.SensorUsedDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.longline.SensorTypeDto + fr.ird.observe.services.dto.referential.longline.SensorBrandDto + fr.ird.observe.services.dto.referential.longline.SensorDataFormatDto + fr.ird.observe.application.swing.ui.content.table.* + + jaxx.runtime.swing.editor.bean.BeanComboBox + + java.awt.Dimension + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <SensorUsedUIHandler id='handler'/> + + <!-- model --> + <SensorUsedUIModel id='model'/> + + <!-- edit bean --> + <ActivityLonglineSensorUsedDto id='bean'/> + + <!-- table edit bean --> + <SensorUsedDto id='tableEditBean'/> + + <!-- table model --> + <ContentTableModel id='tableModel'/> + + <!-- le validateur de l'écran --> + <BeanValidator id='validator' autoField='true' context='ui-update' + beanClass='fr.ird.observe.services.dto.longline.ActivityLonglineSensorUsedDto' + errorTableModel='{getErrorTableModel()}'/> + + <!-- le validateur d'une entrée de tableau --> + <BeanValidator id='validatorTable' autoField='true' context='ui-update' + beanClass='fr.ird.observe.services.dto.longline.SensorUsedDto' + errorTableModel='{getErrorTableModel()}'/> + + <Table id='editorPanel' fill='both' insets='1'> + + <!-- sensorType --> + <row> + <cell> + <JLabel id='sensorTypeLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='sensorType' constructorParams='this' genericType='ReferentialReference<SensorTypeDto>' _entityClass='SensorTypeDto.class'/> + </cell> + </row> + + <!-- sensorDataFormat --> + <row> + <cell> + <JLabel id='sensorDataFormatLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='sensorDataFormat' constructorParams='this' genericType='ReferentialReference<SensorDataFormatDto>' _entityClass='SensorDataFormatDto.class'/> + </cell> + </row> + + <!-- sensorBrand --> + <row> + <cell> + <JLabel id='sensorBrandLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='sensorBrand' constructorParams='this' genericType='ReferentialReference<SensorBrandDto>' _entityClass='SensorBrandDto.class'/> + </cell> + </row> + + <!-- sensorSerialNo --> + <row> + <cell> + <JLabel id='sensorSerialNoLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <JPanel layout='{new BorderLayout()}'> + <JToolBar id='sensorSerialNoToolbar' constraints='BorderLayout.WEST'> + <JButton id='resetSensorSerialNo' styleClass='resetButton'/> + </JToolBar> + <JTextField id='sensorSerialNo' constraints='BorderLayout.CENTER'/> + </JPanel> + </cell> + </row> + + <!-- dataLocation --> + <row> + <cell> + <JLabel id='dataLocationLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <JPanel layout='{new BorderLayout()}'> + <JToolBar id='dataLocationToolbar' constraints='BorderLayout.WEST'> + <JButton id='resetDataLocation' styleClass='resetButton'/> + </JToolBar> + <JTextField id='dataLocation' constraints='BorderLayout.CENTER'/> + </JPanel> + </cell> + </row> + + <!-- data --> + <row> + <cell> + <JLabel id='dataLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <JPanel layout='{new GridLayout()}'> + <JButton id="importDataButton" onActionPerformed="getHandler().importData()"/> + <JButton id="exportDataButton" onActionPerformed="getHandler().exportData()"/> + <JButton id="deleteDataButton" onActionPerformed="getHandler().deleteData()"/> + </JPanel> + </cell> + </row> + </Table> + + <Table id='extraZone' fill='both' weightx='1' insets='1'> + <row> + <cell weighty='1'> + <JScrollPane id='comment' + onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2' + onKeyReleased='getBean().setComment(comment2.getText())'/> + </JScrollPane> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/SensorUsedUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/SensorUsedUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/SensorUsedUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/SensorUsedUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/SensorUsedUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/SensorUsedUIHandler.java new file mode 100644 index 0000000..0a572ca --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/SensorUsedUIHandler.java @@ -0,0 +1,220 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.ObserveSwingTechnicalException; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.DataFileDto; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.longline.ActivityLonglineSensorUsedDto; +import fr.ird.observe.services.dto.longline.ActivityLonglineSensorUsedDtos; +import fr.ird.observe.services.dto.longline.SensorUsedDto; +import fr.ird.observe.services.dto.referential.longline.SensorBrandDto; +import fr.ird.observe.services.dto.referential.longline.SensorDataFormatDto; +import fr.ird.observe.services.dto.referential.longline.SensorTypeDto; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.service.longline.ActivityLongLineSensorUsedService; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.jaxx.runtime.JaxxFileChooser; + +import javax.swing.JOptionPane; +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; +import java.awt.Component; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 8/31/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.7 + */ +public class SensorUsedUIHandler extends ContentTableUIHandler<ActivityLonglineSensorUsedDto, SensorUsedDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(SensorUsedUIHandler.class); + + public SensorUsedUIHandler(SensorUsedUI ui) { + super(ui, DataContextType.ActivityLongline); + } + + @Override + public SensorUsedUI getUi() { + return (SensorUsedUI) super.getUi(); + } + + @Override + protected void onSelectedRowChanged(int editingRow, SensorUsedDto bean, boolean create) { + if (getTableModel().isEditable()) { + if (log.isDebugEnabled()) { + log.debug("Row has changed to " + editingRow); + } + getUi().getSensorType().requestFocus(); + } + } + + @Override + protected void initTableUI(DefaultTableCellRenderer renderer) { + JTable table = getUi().getTable(); + + UIHelper.setI18nTableHeaderRenderer(table, + n("observe.content.sensorUsed.table.sensorType"), + n("observe.content.sensorUsed.table.sensorType.tip"), + n("observe.content.sensorUsed.table.sensorBrand"), + n("observe.content.sensorUsed.table.sensorBrand.tip"), + n("observe.content.sensorUsed.table.sensorDataFormat"), + n("observe.content.sensorUsed.table.sensorDataFormat.tip"), + n("observe.content.sensorUsed.table.sensorSerialNo"), + n("observe.content.sensorUsed.table.sensorSerialNo.tip"), + n("observe.content.sensorUsed.table.data"), + n("observe.content.sensorUsed.table.data.tip"), + n("observe.content.sensorUsed.table.dataLocation"), + n("observe.content.sensorUsed.table.dataLocation.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SensorTypeDto.class)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SensorBrandDto.class)); + UIHelper.setTableColumnRenderer(table, 2, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SensorDataFormatDto.class)); + UIHelper.setTableColumnRenderer(table, 3, UIHelper.newStringTableCellRenderer(renderer, 10, true)); + UIHelper.setTableColumnRenderer(table, 4, UIHelper.newBooleanTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 5, UIHelper.newStringTableCellRenderer(renderer, 10, true)); + } + + @Override + protected String getEditBeanIdToLoad() { + return getDataContext().getSelectedActivityId(); + } + + public void importData() { + + File file = UIHelper.chooseFile((Component) ui, + t("observe.content.choose.sensorUsed.title.importData"), + t("observe.action.choose.sensorUsed.importData"), + null); + + if (file != null) { + + if (log.isInfoEnabled()) { + log.info("Set data from file: " + file); + } + + DataFileDto dataFileDto = UIHelper.fileToDataFileDto(file); + getTableEditBean().setData(dataFileDto); + getTableEditBean().setHasData(true); + + } + + } + + public void deleteData() { + + int response = UIHelper.askUser((Component) ui, + t("observe.title.delete"), + t("observe.content.sensorUsed.delete.data.message"), + JOptionPane.WARNING_MESSAGE, + new Object[]{t("observe.choice.confirm.delete"), + t("observe.choice.cancel")}, + 1); + + boolean doDelete = response == 0; + + if (doDelete) { + + if (log.isInfoEnabled()) { + log.info("Delete sensorUsed data " + getTableEditBean().getData()); + } + getTableEditBean().setData(null); + getTableEditBean().setHasData(false); + + } + + } + + public void exportData() { + + DataFileDto dataFile = getTableEditBean().getData(); + + if (dataFile == null) { + dataFile = getActivityLonglineSensorUsedService().getDataFile(getTableEditBean().getId()); + } + + + File file = JaxxFileChooser + .forSaving() + .setParent(getUi()) + .setTitle(t("observe.content.choose.sensorUsed.title.exportData")) + .setApprovalText(t("observe.action.choose.sensorUsed.exportData")) + .setFilename(dataFile.getName()) + .setUseAcceptAllFileFilter(true) + .choose(); + + if (file != null && UIHelper.confirmOverwriteFileIfExist(getUi(), file)) { + + if (log.isInfoEnabled()) { + log.info("save sensorUsed data to " + file); + } + + try { + + Files.write(file.toPath(), dataFile.getContent()); + + ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); + mainUI.getStatus().setStatus(t("observe.content.sensorUsed.message.data.exported", file)); + } catch (IOException e) { + throw new ObserveSwingTechnicalException("Could not save binary data to " + file, e); + } + + } + + } + + @Override + protected void doPersist(ActivityLonglineSensorUsedDto bean) { + + SaveResultDto saveResult= getActivityLonglineSensorUsedService().save(bean); + saveResult.toDto(bean); + + } + + @Override + protected void loadEditBean(String beanId) { + Form<ActivityLonglineSensorUsedDto> form = getActivityLonglineSensorUsedService().loadForm(beanId); + loadReferentialReferenceSetsInModel(form); + getModel().setForm(form); + ActivityLonglineSensorUsedDtos.copyActivityLonglineSensorUsedDto(form.getObject(), getBean()); + } + + protected ActivityLongLineSensorUsedService getActivityLonglineSensorUsedService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivityLongLineSensorUsedService(); + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/SensorUsedUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/SensorUsedUIModel.java new file mode 100644 index 0000000..2a25561 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/SensorUsedUIModel.java @@ -0,0 +1,96 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import fr.ird.observe.services.dto.longline.ActivityLonglineSensorUsedDto; +import fr.ird.observe.services.dto.longline.SensorUsedDto; +import fr.ird.observe.services.dto.longline.SensorUsedDtos; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; + +import java.util.Collection; +import java.util.List; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.7 + */ +public class SensorUsedUIModel extends ContentTableUIModel<ActivityLonglineSensorUsedDto, SensorUsedDto> { + + private static final long serialVersionUID = 1L; + + public SensorUsedUIModel(SensorUsedUI ui) { + + super(ActivityLonglineSensorUsedDto.class, + SensorUsedDto.class, + new String[]{ + ActivityLonglineSensorUsedDto.PROPERTY_SENSOR_USED, + ActivityLonglineSensorUsedDto.PROPERTY_COMMENT}, + new String[]{SensorUsedDto.PROPERTY_HAS_DATA, + SensorUsedDto.PROPERTY_DATA, + SensorUsedDto.PROPERTY_SENSOR_SERIAL_NO, + SensorUsedDto.PROPERTY_SENSOR_TYPE, + SensorUsedDto.PROPERTY_SENSOR_BRAND, + SensorUsedDto.PROPERTY_SENSOR_DATA_FORMAT}); + + List<ContentTableMeta<SensorUsedDto>> metas = Lists.newArrayList( + ContentTableModel.newTableMeta(SensorUsedDto.class, SensorUsedDto.PROPERTY_SENSOR_TYPE, false), + ContentTableModel.newTableMeta(SensorUsedDto.class, SensorUsedDto.PROPERTY_SENSOR_BRAND, false), + ContentTableModel.newTableMeta(SensorUsedDto.class, SensorUsedDto.PROPERTY_SENSOR_DATA_FORMAT, false), + ContentTableModel.newTableMeta(SensorUsedDto.class, SensorUsedDto.PROPERTY_SENSOR_SERIAL_NO, false), + ContentTableModel.newTableMeta(SensorUsedDto.class, SensorUsedDto.PROPERTY_HAS_DATA, false), + ContentTableModel.newTableMeta(SensorUsedDto.class, SensorUsedDto.PROPERTY_DATA_LOCATION, false)); + + initModel(ui, metas); + + } + + @Override + protected ContentTableModel<ActivityLonglineSensorUsedDto, SensorUsedDto> createTableModel( + ObserveContentTableUI<ActivityLonglineSensorUsedDto, SensorUsedDto> ui, + List<ContentTableMeta<SensorUsedDto>> contentTableMetas) { + + return new ContentTableModel<ActivityLonglineSensorUsedDto, SensorUsedDto>(ui, contentTableMetas) { + private static final long serialVersionUID = 1L; + @Override + protected Collection<SensorUsedDto> getChilds(ActivityLonglineSensorUsedDto bean) { + return bean.getSensorUsed(); + } + + @Override + protected void load(SensorUsedDto source, SensorUsedDto target) { + SensorUsedDtos.copySensorUsedDto(source, target); + } + + @Override + protected void setChilds(ActivityLonglineSensorUsedDto parent, List<SensorUsedDto> childs) { + parent.setSensorUsed(childs); + } + }; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/SizeMeasuresTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/SizeMeasuresTableModel.java new file mode 100644 index 0000000..2af7cf3 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/SizeMeasuresTableModel.java @@ -0,0 +1,104 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.longline.SizeMeasureDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.longline.SizeMeasureTypeDto; +import fr.ird.observe.application.swing.ui.util.table.EditableTableWithCacheTableModelSupport; + +/** + * Created on 12/3/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.8 + */ +public class SizeMeasuresTableModel extends EditableTableWithCacheTableModelSupport<SizeMeasureDto> { + + private static final long serialVersionUID = 1L; + + public SizeMeasuresTableModel() { + super(); + } + + @Override + public boolean isRowNotEmpty(SizeMeasureDto valid) { + return !(valid.getSizeMeasureType() == null && valid.getSize() == null); + } + + @Override + protected boolean isRowValid(SizeMeasureDto valid) { + Float size = valid.getSize(); + return !(valid.getSizeMeasureType() == null || size == null) && size > 0 && size < 1000; + } + + @Override + public int getColumnCount() { + return 2; + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + + SizeMeasureDto measure = data.get(rowIndex); + Object result; + switch (columnIndex) { + case 0: + result = measure.getSizeMeasureType(); + break; + case 1: + result = measure.getSize(); + break; + default: + throw new IllegalStateException("Can't come here"); + } + return result; + } + + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + + SizeMeasureDto measure = data.get(rowIndex); + switch (columnIndex) { + case 0: + measure.setSizeMeasureType((ReferentialReference<SizeMeasureTypeDto>) aValue); + break; + + case 1: + measure.setSize((Float) aValue); + break; + + default: + throw new IllegalStateException("Can't come here"); + } + + setModified(true); + + } + + @Override + protected SizeMeasureDto createNewRow() { + return new SizeMeasureDto(); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/TdrUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/TdrUI.jaxx new file mode 100644 index 0000000..f4b1097 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/TdrUI.jaxx @@ -0,0 +1,396 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2014 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.table.ContentTableUI superGenericType='SetLonglineTdrDto, TdrDto' + contentTitle='{n("observe.content.tdr.title")}' + saveNewEntryText='{n("observe.content.tdr.action.create")}' + saveNewEntryTip='{n("observe.content.tdr.action.create.tip")}'> + + <style source="../../CommonTable.jcss"/> + + <import> + fr.ird.observe.services.dto.DataReference + fr.ird.observe.services.dto.longline.BasketDto + fr.ird.observe.services.dto.longline.BranchlineDto + fr.ird.observe.services.dto.longline.TdrDto + fr.ird.observe.services.dto.longline.SectionDto + fr.ird.observe.services.dto.longline.SetLonglineTdrDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.SpeciesDto + fr.ird.observe.services.dto.referential.longline.ItemHorizontalPositionDto + fr.ird.observe.services.dto.referential.longline.ItemVerticalPositionDto + fr.ird.observe.services.dto.referential.longline.SensorBrandDto + fr.ird.observe.application.swing.ui.content.table.* + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + org.nuiton.jaxx.widgets.select.FilterableDoubleList + + org.nuiton.jaxx.widgets.datetime.DateTimeEditor + + java.util.Collection + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <TdrUIHandler id='handler'/> + + <!-- model --> + <TdrUIModel id='model'/> + + <!-- edit bean --> + <SetLonglineTdrDto id='bean'/> + + <!-- table edit bean --> + <TdrDto id='tableEditBean'/> + + <!-- table model --> + <ContentTableModel id='tableModel'/> + + <!-- le validateur de l'écran --> + <BeanValidator id='validator' context='ui-update-tdr' + beanClass='fr.ird.observe.services.dto.longline.SetLonglineTdrDto' + errorTableModel='{getErrorTableModel()}'> + </BeanValidator> + + <!-- le validateur d'une entrée de tableau --> + <BeanValidator id='validatorTable' autoField='true' context='ui-update' + beanClass='fr.ird.observe.services.dto.longline.TdrDto' + errorTableModel='{getErrorTableModel()}' + parentValidator='{validator}'/> + + <Table id='editorPanel' fill='both' insets='0'> + <row> + <cell weightx="1" weighty="1"> + <JTabbedPane id='editTabPane'> + + <tab id='caracteristicsTab'> + + <JPanel layout='{new BorderLayout()}'> + <Table fill='both' constraints='BorderLayout.NORTH' insets="0"> + + <!-- homeId --> + <row> + <cell anchor='west'> + <JLabel id='homeIdLabel'/> + </cell> + <cell fill='both' weightx='1'> + <JPanel layout='{new BorderLayout()}'> + <JToolBar id='homeIdToolbar' constraints='BorderLayout.WEST'> + <JButton id='resetHomeId' styleClass='resetButton'/> + </JToolBar> + <JTextField id='homeId' constraints='BorderLayout.CENTER'/> + </JPanel> + </cell> + </row> + + <!-- serialNo --> + <row> + <cell anchor='west'> + <JLabel id='serialNoLabel'/> + </cell> + <cell fill='both' weightx='1'> + <JPanel layout='{new BorderLayout()}'> + <JToolBar id='serialNoToolbar' constraints='BorderLayout.WEST'> + <JButton id='resetSerialNo' styleClass='resetButton'/> + </JToolBar> + <JTextField id='serialNo' constraints='BorderLayout.CENTER'/> + </JPanel> + </cell> + </row> + + <!-- sensorBrand --> + <row> + <cell> + <JLabel id='sensorBrandLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='sensorBrand' constructorParams='this' genericType='ReferentialReference<SensorBrandDto>' _entityClass='SensorBrandDto.class'/> + </cell> + </row> + + <!-- dataLocation --> + <row> + <cell> + <JLabel id='dataLocationLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <JPanel layout='{new BorderLayout()}'> + <JToolBar id='dataLocationToolbar' constraints='BorderLayout.WEST'> + <JButton id='resetDataLocation' styleClass='resetButton'/> + </JToolBar> + <JTextField id='dataLocation' constraints='BorderLayout.CENTER'/> + </JPanel> + </cell> + </row> + + <!-- data --> + <row> + <cell> + <JLabel id='dataLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <JPanel layout='{new GridLayout()}'> + <JButton id="importDataButton" onActionPerformed="getHandler().importData()"/> + <JButton id="exportDataButton" onActionPerformed="getHandler().exportData()"/> + <JButton id="deleteDataButton" onActionPerformed="getHandler().deleteData()"/> + </JPanel> + </cell> + </row> + + </Table> + </JPanel> + + </tab> + + <tab id='localisationTab'> + + <JPanel layout='{new BorderLayout()}'> + <Table fill='both' constraints='BorderLayout.NORTH' insets="0"> + + <!-- location on longline --> + <row> + <cell columns="2"> + <Table id="locationOnLonglinePanel"> + <row> + <cell anchor="west"> + <JLabel id='sectionLabel'/> + </cell> + <cell fill="both" weightx="1"> + <BeanComboBox id='section' genericType='DataReference<SectionDto>' _entityClass='SectionDto.class' constructorParams='this'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='basketLabel'/> + </cell> + <cell fill="both" weightx="1"> + <BeanComboBox id='basket' genericType='DataReference<BasketDto>' _entityClass='BasketDto.class' constructorParams='this'/> + </cell> + </row> + <row> + <cell anchor="west"> + <JLabel id='branchlineLabel'/> + </cell> + <cell fill="both" weightx="1"> + <BeanComboBox id='branchline' genericType='DataReference<BranchlineDto>' _entityClass='BranchlineDto.class' constructorParams='this'/> + </cell> + </row> + </Table> + </cell> + </row> + + <!-- itemHorizontalPosition --> + <row> + <cell> + <JLabel id='itemHorizontalPositionLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='itemHorizontalPosition' constructorParams='this' + genericType='ReferentialReference<ItemHorizontalPositionDto>' _entityClass='ItemHorizontalPositionDto.class'/> + </cell> + </row> + + <!-- itemVerticalPosition --> + <row> + <cell> + <JLabel id='itemVerticalPositionLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='itemVerticalPosition' constructorParams='this' + genericType='ReferentialReference<ItemVerticalPositionDto>' _entityClass='ItemVerticalPositionDto.class'/> + </cell> + </row> + + <!-- floatline1Length --> + <row> + <cell> + <JLabel id='floatline1LengthLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='floatline1Length' constructorParams='this' styleClass='float'/> + </cell> + </row> + + <!-- floatline2Length --> + <row> + <cell> + <JLabel id='floatline2LengthLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='floatline2Length' constructorParams='this' styleClass='float'/> + </cell> + </row> + + </Table> + </JPanel> + + </tab> + + <tab id='timestampTab'> + + <JPanel layout='{new BorderLayout()}'> + <JPanel layout='{new BorderLayout()}' constraints='BorderLayout.NORTH'> + + <JCheckBox id='enableTimestamp' constraints='BorderLayout.NORTH' + onMouseClicked='getHandler().changeEnableTimestamp(enableTimestamp.isSelected())'/> + + <Table id='timestampPanel' fill='both' constraints='BorderLayout.CENTER' insets="0"> + + <!-- deployementStart --> + <row> + <cell weightx="1" fill="both"> + <DateTimeEditor id='deployementStart' constructorParams='this'/> + </cell> + </row> + <!-- fishingStart --> + <row> + <cell> + <DateTimeEditor id='fishingStart' constructorParams='this'/> + </cell> + </row> + <!-- fishingEnd --> + <row> + <cell> + <DateTimeEditor id='fishingEnd' constructorParams='this'/> + </cell> + </row> + <!-- deployementEnd --> + <row> + <cell> + <DateTimeEditor id='deployementEnd' constructorParams='this'/> + </cell> + </row> + </Table> + </JPanel> + + </JPanel> + </tab> + + <tab id='keyDataTab'> + + <JPanel layout='{new BorderLayout()}'> + <Table fill='both' constraints='BorderLayout.NORTH'> + + <!-- fishingStartDepth --> + <row> + <cell> + <JLabel id='fishingStartDepthLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='fishingStartDepth' constructorParams='this' styleClass='float2'/> + </cell> + </row> + <!-- fishingEndDepth --> + <row> + <cell> + <JLabel id='fishingEndDepthLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='fishingEndDepth' constructorParams='this' styleClass='float2'/> + </cell> + </row> + <!-- minFishingDepth --> + <row> + <cell> + <JLabel id='minFishingDepthLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='minFishingDepth' constructorParams='this' styleClass='float2'/> + </cell> + </row> + <!-- maxFishingDepth --> + <row> + <cell> + <JLabel id='maxFishingDepthLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='maxFishingDepth' constructorParams='this' styleClass='float2'/> + </cell> + </row> + <!-- meanFishingDepth --> + <row> + <cell> + <JLabel id='meanFishingDepthLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='meanFishingDepth' constructorParams='this' styleClass='float2'/> + </cell> + </row> + <!-- medianFishingDepth --> + <row> + <cell> + <JLabel id='medianFishingDepthLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='medianFishingDepth' constructorParams='this' styleClass='float2'/> + </cell> + </row> + <!-- meanDeployementDepth --> + <row> + <cell> + <JLabel id='meanDeployementDepthLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='meanDeployementDepth' constructorParams='this' styleClass='float2'/> + </cell> + </row> + <!-- medianDeployementDepth --> + <row> + <cell> + <JLabel id='medianDeployementDepthLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='medianDeployementDepth' constructorParams='this' styleClass='float2'/> + </cell> + </row> + </Table> + + </JPanel> + + </tab> + + <tab id='speciesTab'> + + <!-- species --> + <JPanel layout='{new BorderLayout()}'> + <Table fill='both' constraints='BorderLayout.NORTH'> + <row> + <cell weighty="1" weightx="1"> + <FilterableDoubleList id='species' + genericType='ReferentialReference<SpeciesDto>' + _entityClass='SpeciesDto.class'/> + </cell> + </row> + </Table> + </JPanel> + + </tab> + + </JTabbedPane> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/TdrUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/TdrUI.jcss new file mode 100644 index 0000000..c5477b8 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/TdrUI.jcss @@ -0,0 +1,370 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +/* ***************************************************************************** */ +/* CARACTERISTICS TAB ********************************************************* */ +/* ***************************************************************************** */ + +#caracteristicsTab { + title:{t("observe.content.tdr.tab.caracteristics")}; + icon:{handler.getErrorIconIfFalse(model.isCaracteristicsTabValid())}; +} + +#homeIdLabel { + text:"observe.content.tdr.homeId"; + labelFor:{homeId}; +} + +#homeId { + text: {getStringValue(tableEditBean.getHomeId())}; + _tablePropertyName: {TdrDto.PROPERTY_HOME_ID}; +} + +#resetHomeId { + toolTipText:"observe.content.tdr.action.reset.homeId.tip"; + _resetTablePropertyName: {TdrDto.PROPERTY_HOME_ID}; +} + +#serialNoLabel { + text:"observe.content.tdr.serialNo"; + labelFor:{serialNo}; +} + +#serialNo { + text: {getStringValue(tableEditBean.getSerialNo())}; + _tablePropertyName: {TdrDto.PROPERTY_SERIAL_NO}; +} + +#resetSerialNo { + toolTipText:"observe.content.tdr.action.reset.serialNo.tip"; + _resetTablePropertyName: {TdrDto.PROPERTY_SERIAL_NO}; +} + + +#sensorBrandLabel { + text:"observe.content.tdr.sensorBrand"; + labelFor:{sensorBrand}; +} + +#sensorBrand { + property:{TdrDto.PROPERTY_SENSOR_BRAND}; + selectedItem:{tableEditBean.getSensorBrand()}; +} + +#dataLocationLabel { + text:"observe.content.tdr.dataLocation"; + toolTipText:"observe.content.tdr.dataLocation.tip"; + labelFor:{dataLocation}; +} + +#dataLocation { + _tablePropertyName:{TdrDto.PROPERTY_DATA_LOCATION}; + text:{tableEditBean.getDataLocation()}; +} + +#resetDataLocation { + toolTipText:"observe.content.tdr.action.reset.dataLocation.tip"; + _resetTablePropertyName: {TdrDto.PROPERTY_DATA_LOCATION}; + focusable:false; +} + +#dataLabel { + text:"observe.content.tdr.data"; +} + +#importDataButton { + actionIcon:data-import; + text:"observe.content.tdr.importData"; + toolTipText:"observe.content.tdr.importData.tip"; + enabled:{! tableEditBean.isHasData()}; +} + +#exportDataButton { + actionIcon:data-export; + text:"observe.content.tdr.exportData"; + toolTipText:"observe.content.tdr.exportData.tip"; + enabled:{tableEditBean.isHasData()}; +} + +#deleteDataButton { + actionIcon:delete; + text:"observe.content.tdr.deleteData"; + toolTipText:"observe.content.tdr.deleteData.tip"; + enabled:{tableEditBean.isHasData()}; +} + +/* ***************************************************************************** */ +/* LOCALISATION TAB *********************************************************** */ +/* ***************************************************************************** */ + +#localisationTab { + title:{t("observe.content.tdr.tab.localisation")}; + icon:{handler.getErrorIconIfFalse(model.isLocalisationTabValid())}; +} + +#locationOnLonglinePanel { + border:{new TitledBorder(t("observe.content.tdr.locationOnLongline"))}; +} + +#sectionLabel { + text:"observe.content.tdr.section"; + labelFor:{section}; +} + +#section { + property:{TdrDto.PROPERTY_SECTION}; + selectedItem:{tableEditBean.getSection()}; + _listNoLoad:{true}; + _validatorLabel: {t("observe.content.tdr.section")}; +} + +#basketLabel { + text:"observe.content.tdr.basket"; + labelFor:{basket}; +} + +#basket { + property:{TdrDto.PROPERTY_BASKET}; + selectedItem:{tableEditBean.getBasket()}; + _listNoLoad:{true}; + _validatorLabel: {t("observe.content.tdr.basket")}; +} + +#branchlineLabel { + text:"observe.content.tdr.branchline"; + labelFor:{branchline}; +} + +#branchline { + property:{TdrDto.PROPERTY_BRANCHLINE}; + selectedItem:{tableEditBean.getBranchline()}; + _listNoLoad:{true}; + _validatorLabel: {t("observe.content.tdr.branchline")}; +} + +#itemHorizontalPositionLabel { + text:"observe.content.tdr.itemHorizontalPosition"; + labelFor:{itemHorizontalPosition}; +} + +#itemHorizontalPosition { + property:{TdrDto.PROPERTY_ITEM_HORIZONTAL_POSITION}; + selectedItem:{tableEditBean.getItemHorizontalPosition()}; + _validatorLabel: {t("observe.content.tdr.itemHorizontalPosition")}; +} + +#itemVerticalPositionLabel { + text:"observe.content.tdr.itemVerticalPosition"; + labelFor:{itemVerticalPosition}; +} + +#itemVerticalPosition { + property:{TdrDto.PROPERTY_ITEM_VERTICAL_POSITION}; + selectedItem:{tableEditBean.getItemVerticalPosition()}; + _validatorLabel: {t("observe.content.tdr.itemVerticalPosition")}; +} + +#floatline1LengthLabel { + text:"observe.content.tdr.floatline1Length"; + labelFor:{floatline1Length}; +} + +#floatline1Length { + property:{TdrDto.PROPERTY_FLOATLINE1_LENGTH}; + model:{tableEditBean.getFloatline1Length()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL3_PATTERN}; + _validatorLabel: {t("observe.content.tdr.floatline1Length")}; +} + +#floatline2LengthLabel { + text:"observe.content.tdr.floatline2Length"; + labelFor:{floatline2Length}; +} + +#floatline2Length { + property:{TdrDto.PROPERTY_FLOATLINE2_LENGTH}; + model:{tableEditBean.getFloatline2Length()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL3_PATTERN}; + _validatorLabel: {t("observe.content.tdr.floatline2Length")}; +} + + +/* ***************************************************************************** */ +/* TIMESTAMP TAB ************************************************************** */ +/* ***************************************************************************** */ + +#timestampTab { + title:{t("observe.content.tdr.tab.timestamp")}; + icon:{handler.getErrorIconIfFalse(model.isTimestampTabValid())}; +} + +#enableTimestamp { + text:"observe.content.tdr.enableTimestamp"; + toolTipText:"observe.content.tdr.enableTimestamp.tip"; +} + +#timestampPanel { + visible:{enableTimestamp.isSelected()}; +} + +#deployementStart { + label:{t("observe.content.tdr.deployementStart")}; + date:{tableEditBean.getDeployementStart()}; + propertyDate: {TdrDto.PROPERTY_DEPLOYEMENT_START}; + _validatorLabel: {t("observe.content.tdr.deployementStart")}; +} + +#deployementEnd { + label:{t("observe.content.tdr.deployementEnd")}; + date:{tableEditBean.getDeployementEnd()}; + propertyDate: {TdrDto.PROPERTY_DEPLOYEMENT_END}; + _validatorLabel: {t("observe.content.tdr.deployementEnd")}; +} + +#fishingStart { + label:{t("observe.content.tdr.fishingStart")}; + date:{tableEditBean.getFishingStart()}; + propertyDate: {TdrDto.PROPERTY_FISHING_START}; + _validatorLabel: {t("observe.content.tdr.fishingStart")}; +} + +#fishingEnd { + label:{t("observe.content.tdr.fishingEnd")}; + date:{tableEditBean.getFishingEnd()}; + propertyDate: {TdrDto.PROPERTY_FISHING_END}; + _validatorLabel: {t("observe.content.tdr.fishingEnd")}; +} + +/* ***************************************************************************** */ +/* KEY DATA TAB *************************************************************** */ +/* ***************************************************************************** */ + +#keyDataTab { + title:{t("observe.content.tdr.tab.keyData")}; + icon:{handler.getErrorIconIfFalse(model.isKeyDataTabValid())}; +} + +#fishingStartDepthLabel { + text:"observe.content.tdr.fishingStartDepth"; + labelFor:{fishingStartDepth}; +} + +#fishingStartDepth { + property:{TdrDto.PROPERTY_FISHING_START_DEPTH}; + model:{tableEditBean.getFishingStartDepth()}; + _validatorLabel: {t("observe.content.tdr.fishingStartDepth")}; +} + +#fishingEndDepthLabel { + text:"observe.content.tdr.fishingEndDepth"; + labelFor:{fishingEndDepth}; +} + +#fishingEndDepth { + property:{TdrDto.PROPERTY_FISHING_END_DEPTH}; + model:{tableEditBean.getFishingEndDepth()}; + _validatorLabel: {t("observe.content.tdr.fishingEndDepth")}; +} + +#meanDeployementDepthLabel { + text:"observe.content.tdr.meanDeployementDepth"; + labelFor:{meanDeployementDepth}; +} + +#meanDeployementDepth { + property:{TdrDto.PROPERTY_MEAN_DEPLOYEMENT_DEPTH}; + model:{tableEditBean.getMeanDeployementDepth()}; + _validatorLabel: {t("observe.content.tdr.meanDeployementDepth")}; +} + +#medianDeployementDepthLabel { + text:"observe.content.tdr.medianDeployementDepth"; + labelFor:{medianDeployementDepth}; +} + +#medianDeployementDepth { + property:{TdrDto.PROPERTY_MEDIAN_DEPLOYEMENT_DEPTH}; + model:{tableEditBean.getMedianDeployementDepth()}; + _validatorLabel: {t("observe.content.tdr.medianDeployementDepth")}; +} + +#minFishingDepthLabel { + text:"observe.content.tdr.minFishingDepth"; + labelFor:{minFishingDepth}; +} + +#minFishingDepth { + property:{TdrDto.PROPERTY_MIN_FISHING_DEPTH}; + model:{tableEditBean.getMinFishingDepth()}; + _validatorLabel: {t("observe.content.tdr.minFishingDepth")}; +} + +#maxFishingDepthLabel { + text:"observe.content.tdr.maxFishingDepth"; + labelFor:{maxFishingDepth}; +} + +#maxFishingDepth { + property:{TdrDto.PROPERTY_MAX_FISHING_DEPTH}; + model:{tableEditBean.getMaxFishingDepth()}; + _validatorLabel: {t("observe.content.tdr.maxFishingDepth")}; +} + +#meanFishingDepthLabel { + text:"observe.content.tdr.meanFishingDepth"; + labelFor:{meanFishingDepth}; +} + +#meanFishingDepth { + property:{TdrDto.PROPERTY_MEAN_FISHING_DEPTH}; + model:{tableEditBean.getMeanFishingDepth()}; + _validatorLabel: {t("observe.content.tdr.meanFishingDepth")}; +} + +#medianFishingDepthLabel { + text:"observe.content.tdr.medianFishingDepth"; + labelFor:{medianFishingDepth}; +} + +#medianFishingDepth { + property:{TdrDto.PROPERTY_MEDIAN_FISHING_DEPTH}; + model:{tableEditBean.getMedianFishingDepth()}; + _validatorLabel: {t("observe.content.tdr.medianFishingDepth")}; +} + +/* ***************************************************************************** */ +/* SPECIES TAB **************************************************************** */ +/* ***************************************************************************** */ + +#speciesTab { + title:{t("observe.content.tdr.tab.species")}; + icon:{handler.getErrorIconIfFalse(model.isSpeciesTabValid())}; +} + +#species { + property: {TdrDto.PROPERTY_SPECIES}; + selected:{(java.util.Collection)tableEditBean.getSpecies()}; + _validatorLabel: {t("observe.content.tdr.species")}; + showListLabel: true; + universeLabel:{t("observe.content.tdr.availableSpecies")}; + selectedLabel:{t("observe.content.tdr.selectedSpecies")}; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/TdrUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/TdrUIHandler.java new file mode 100644 index 0000000..2bdef77 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/TdrUIHandler.java @@ -0,0 +1,485 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.ObserveSwingTechnicalException; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.DataFileDto; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.longline.SetLonglineTdrDto; +import fr.ird.observe.services.dto.longline.SetLonglineTdrDtos; +import fr.ird.observe.services.dto.longline.TdrDto; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.ReferentialReferences; +import fr.ird.observe.services.dto.referential.longline.SensorBrandDto; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.service.longline.TdrService; +import fr.ird.observe.services.service.longline.TripLonglineService; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIHandler; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIModel; +import jaxx.runtime.context.JAXXContextEntryDef; +import jaxx.runtime.swing.HidorButton; +import jaxx.runtime.validator.swing.SwingValidatorMessage; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.jaxx.runtime.JaxxFileChooser; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.JComponent; +import javax.swing.JOptionPane; +import javax.swing.JTable; +import javax.swing.event.TableModelListener; +import javax.swing.table.DefaultTableCellRenderer; +import java.awt.Component; +import java.beans.PropertyChangeListener; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Collection; +import java.util.Date; +import java.util.HashSet; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 9/30/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class TdrUIHandler extends ContentTableUIHandler<SetLonglineTdrDto, TdrDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(TdrUIHandler.class); + + // Compute valid state of tab from the error table + protected final TableModelListener computeTabValidStateListener; + + // Change toogle target visible on all TimeEditors + protected final PropertyChangeListener onToogleTimeEditorSliderChangedListener; + + protected boolean toogleTimeEditorSliderIsChanging; + + private static final JAXXContextEntryDef<LonglinePositionHelper<TdrDto>> POSITION_HELPER_ENTRY = + UIHelper.newContextEntryDef("TdrUI-positionHelper", LonglinePositionHelper.class); + + public TdrUIHandler(TdrUI ui) { + super(ui, DataContextType.SetLongline); + computeTabValidStateListener = e -> { + + SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); + computeTabValidState(source); + + }; + onToogleTimeEditorSliderChangedListener = evt -> { + Boolean newValue = (Boolean) evt.getNewValue(); + onToogleTimeEditorSliderChanged(newValue); + }; + } + + @Override + public TdrUI getUi() { + return (TdrUI) super.getUi(); + } + + @Override + protected void onSelectedRowChanged(int editingRow, TdrDto bean, boolean create) { + + ContentTableModel<SetLonglineTdrDto, TdrDto> model = getTableModel(); + + TdrUI ui = getUi(); + + boolean withTimestamp = bean.getFishingStart() != null; + ui.getEnableTimestamp().setSelected(withTimestamp); + + if (!model.isEditable()) { + return; + } + + String homeId = bean.getHomeId(); + + if (log.isDebugEnabled()) { + log.debug("selected tdr " + homeId); + } + JComponent requestFocus = ui.getHomeId(); + + if (create) { + + // set date - time + + SetLonglineTdrDto setLongline = getBean(); + + Date settingStartTimeStamp = setLongline.getSettingStartTimeStamp(); + setTimestamp(bean, settingStartTimeStamp); + + // go back to first tab + ui.getEditTabPane().setSelectedIndex(0); + + // enable timestamps + ui.getEnableTimestamp().setSelected(true); + + } else if (!withTimestamp) { + + // clean timestamps + setTimestamp(bean, null); + + } + + LonglinePositionHelper<TdrDto> positionHelper = POSITION_HELPER_ENTRY.getContextValue(ui); + positionHelper.resetPosition(bean); + + requestFocus.requestFocus(); + + } + + @Override + protected void initTableUI(DefaultTableCellRenderer renderer) { + + JTable table = getUi().getTable(); + + UIHelper.setI18nTableHeaderRenderer(table, + n("observe.content.tdr.table.homeId"), + n("observe.content.tdr.table.homeId.tip"), + n("observe.content.tdr.table.serialNo"), + n("observe.content.tdr.table.serialNo.tip"), + n("observe.content.tdr.table.sensorBrand"), + n("observe.content.tdr.table.sensorBrand.tip"), + n("observe.content.tdr.table.data"), + n("observe.content.sensorUsed.table.data.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newStringTableCellRenderer(renderer, 10, true)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newStringTableCellRenderer(renderer, 10, true)); + UIHelper.setTableColumnRenderer(table, 2, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SensorBrandDto.class)); + UIHelper.setTableColumnRenderer(table, 3, UIHelper.newBooleanTableCellRenderer(renderer)); + + } + + @Override + protected String getEditBeanIdToLoad() { + return getDataContext().getSelectedSetId(); + } + + @Override + public void initUI() { + + super.initUI(); + + LonglinePositionHelper<TdrDto> positionHelper = new LonglinePositionHelper<>( + getUi().getSection(), + getUi().getBasket(), + getUi().getBranchline(), + getTableEditBean()); + + POSITION_HELPER_ENTRY.setContextValue(getUi(), positionHelper); + + getUi().getDeployementStart().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); + getUi().getDeployementEnd().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); + getUi().getFishingStart().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); + getUi().getFishingEnd().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); + + } + + @Override + public void openUI() { + + if (log.isInfoEnabled()) { + log.info("OpenUI: " + getModel()); + } + super.openUI(); + + // Reset all sections + LonglinePositionHelper<TdrDto> positionHelper = POSITION_HELPER_ENTRY.getContextValue(getUi()); + getUi().getSection().setData(positionHelper.getSections()); + + // To be sure always remove listener (could prevent some leaks) + getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); + // listen messages to see if required to add + getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); + + SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); + computeTabValidState(errorTableModel); + + } + + @Override + protected void closeSafeUI() { + if (log.isInfoEnabled()) { + log.info("CloseUI: " + getModel()); + } + super.closeSafeUI(); + + // remove listener + getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); + + } + + @Override + protected void resetEditBean() { + + super.resetEditBean(); + TdrDto tableEditBean = getTableEditBean(); + + boolean withTimestamp = tableEditBean.getFishingStart() != null; + getUi().getEnableTimestamp().setSelected(withTimestamp); + + } + + public void changeEnableTimestamp(boolean enableTimestamp) { + + Date timeStamp; + + if (enableTimestamp) { + + SetLonglineTdrDto setLongline = getBean(); + timeStamp = setLongline.getSettingStartTimeStamp(); + + } else { + + timeStamp = null; + + } + + TdrDto bean = getTableEditBean(); + setTimestamp(bean, timeStamp); + + } + + public void importData() { + + File file = UIHelper.chooseFile((Component) ui, + t("observe.content.choose.tdr.title.importData"), + t("observe.action.choose.tdr.importData"), + null); + + if (file != null) { + + if (log.isInfoEnabled()) { + log.info("Set data from file: " + file); + } + + DataFileDto dataFileDto = UIHelper.fileToDataFileDto(file); + getTableEditBean().setData(dataFileDto); + getTableEditBean().setHasData(true); + + } + + } + + public void deleteData() { + + int response = UIHelper.askUser((Component) ui, + t("observe.title.delete"), + t("observe.content.tdr.delete.data.message"), + JOptionPane.WARNING_MESSAGE, + new Object[]{t("observe.choice.confirm.delete"), + t("observe.choice.cancel")}, + 1); + + boolean doDelete = response == 0; + + if (doDelete) { + + if (log.isInfoEnabled()) { + log.info("Delete tdr data " + getTableEditBean().getData()); + } + getTableEditBean().setData(null); + getTableEditBean().setHasData(false); + + } + + } + + public void exportData() { + + DataFileDto dataFile = getTableEditBean().getData(); + + if (dataFile == null) { + dataFile = getTdrService().getDataFile(getTableEditBean().getId()); + } + + File file = JaxxFileChooser + .forSaving() + .setParent(getUi()) + .setTitle(t("observe.content.choose.tdr.title.exportData")) + .setApprovalText(t("observe.action.choose.tdr.exportData")) + .setFilename(dataFile.getName()) + .setUseAcceptAllFileFilter(true) + .choose(); + + if (file != null && UIHelper.confirmOverwriteFileIfExist(getUi(), file)) { + + if (log.isInfoEnabled()) { + log.info("save tdr data to " + file); + } + + try { + + Files.write(file.toPath(), dataFile.getContent()); + + ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); + mainUI.getStatus().setStatus(t("observe.content.sensorUsed.message.data.exported", file)); + } catch (IOException e) { + throw new ObserveSwingTechnicalException("Could not save binary data to " + file, e); + } + + } + + } + + protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { + + Set<String> errorProperties = new HashSet<>(); + int rowCount = errorTableModel.getRowCount(); + for (int i = 0; i < rowCount; i++) { + + SwingValidatorMessage row = errorTableModel.getRow(i); + if (NuitonValidatorScope.ERROR.equals(row.getScope())) { + errorProperties.add(row.getField()); + } + } + + boolean caracteristicsTabValid = !errorProperties.removeAll(TdrUIModel.CARACTERISTIC_TAB_PROPERTIES); + boolean localisationTabValid = !errorProperties.removeAll(TdrUIModel.LOCALISATION_TAB_PROPERTIES); + boolean timestampTabValid = !errorProperties.removeAll(TdrUIModel.TIMESTAMP_TAB_PROPERTIES); + boolean keyDataTabValid = !errorProperties.removeAll(TdrUIModel.KEY_DATA_TAB_PROPERTIES); + boolean speciesTabValid = !errorProperties.removeAll(TdrUIModel.SPECIES_TAB_PROPERTIES); + + TdrUIModel model = (TdrUIModel) getModel(); + model.setCaracteristicsTabValid(caracteristicsTabValid); + model.setLocalisationTabValid(localisationTabValid); + model.setTimestampTabValid(timestampTabValid); + model.setKeyDataTabValid(keyDataTabValid); + model.setSpeciesTabValid(speciesTabValid); + + } + + protected void onToogleTimeEditorSliderChanged(boolean newValue) { + + if (!toogleTimeEditorSliderIsChanging) { + + toogleTimeEditorSliderIsChanging = true; + + try { + + boolean selected = !newValue; + + getUi().getDeployementStart().getSliderHidor().setSelected(selected); + getUi().getDeployementStart().getSliderHidor().setTargetVisible(newValue); + + getUi().getFishingStart().getSliderHidor().setSelected(selected); + getUi().getFishingStart().getSliderHidor().setTargetVisible(newValue); + + getUi().getFishingEnd().getSliderHidor().setSelected(selected); + getUi().getFishingEnd().getSliderHidor().setTargetVisible(newValue); + + getUi().getDeployementEnd().getSliderHidor().setSelected(selected); + getUi().getDeployementEnd().getSliderHidor().setTargetVisible(newValue); + + } finally { + + toogleTimeEditorSliderIsChanging = false; + + } + + } + + } + + protected void setTimestamp(TdrDto bean, Date timestamp) { + + bean.setDeployementStart(timestamp); + bean.setDeployementEnd(timestamp); + bean.setFishingStart(timestamp); + bean.setFishingEnd(timestamp); + + } + + @Override + protected void doPersist(SetLonglineTdrDto bean) { + + SaveResultDto saveResult = getTdrService().save(bean); + saveResult.toDto(bean); + + } + + @Override + protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { + + Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); + + switch (propertyName) { + + case TdrDto.PROPERTY_SPECIES: { + String speciesListId = ObserveSwingApplicationContext.get().getConfig().getSpeciesListLonglineCatchId(); + + String tripLonglineId = getDataContext().getSelectedTripLonglineId(); + + TripLonglineService tripLonglineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripLonglineService(); + result = (List) tripLonglineService.getSpeciesByListAndTrip(tripLonglineId, speciesListId); + + result = ReferentialReferences.filterEnabled(result); + + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + + break; + } + + } + + return result; + + } + + @Override + protected void loadEditBean(String beanId) { + + Form<SetLonglineTdrDto> form = getTdrService().loadForm(beanId); + + ContentTableUIModel<SetLonglineTdrDto, TdrDto> model = getModel(); + loadReferentialReferenceSetsInModel(form); + model.setForm(form); + + LonglinePositionHelper<TdrDto> positionHelper = POSITION_HELPER_ENTRY.getContextValue(getUi()); + positionHelper.initSections(form.getObject(), + form.getObject().getTdr()); + + SetLonglineTdrDtos.copySetLonglineTdrDto(form.getObject(), getBean()); + + } + + protected TdrService getTdrService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTdrService(); + } +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/TdrUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/TdrUIModel.java new file mode 100644 index 0000000..25d401b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/TdrUIModel.java @@ -0,0 +1,227 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import fr.ird.observe.services.dto.longline.SetLonglineTdrDto; +import fr.ird.observe.services.dto.longline.TdrDto; +import fr.ird.observe.services.dto.longline.TdrDtos; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; + +import java.util.Collection; +import java.util.List; +import java.util.Set; + +/** + * Created on 9/30/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.7 + */ +public class TdrUIModel extends ContentTableUIModel<SetLonglineTdrDto, TdrDto> { + + public static final Set<String> CARACTERISTIC_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(TdrDto.PROPERTY_HOME_ID, + TdrDto.PROPERTY_SERIAL_NO, + TdrDto.PROPERTY_SENSOR_BRAND, + TdrDto.PROPERTY_HAS_DATA, + TdrDto.PROPERTY_DATA).build(); + + public static final Set<String> LOCALISATION_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(TdrDto.PROPERTY_SECTION, + TdrDto.PROPERTY_BASKET, + TdrDto.PROPERTY_BRANCHLINE, + TdrDto.PROPERTY_ITEM_HORIZONTAL_POSITION, + TdrDto.PROPERTY_ITEM_VERTICAL_POSITION, + TdrDto.PROPERTY_FLOATLINE1_LENGTH, + TdrDto.PROPERTY_FLOATLINE2_LENGTH).build(); + + + public static final Set<String> TIMESTAMP_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(TdrDto.PROPERTY_DEPLOYEMENT_START, + TdrDto.PROPERTY_DEPLOYEMENT_END, + TdrDto.PROPERTY_FISHING_START, + TdrDto.PROPERTY_FISHING_END + ).build(); + + public static final Set<String> KEY_DATA_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(TdrDto.PROPERTY_FISHING_START_DEPTH, + TdrDto.PROPERTY_FISHING_END_DEPTH, + TdrDto.PROPERTY_MEAN_DEPLOYEMENT_DEPTH, + TdrDto.PROPERTY_MEDIAN_DEPLOYEMENT_DEPTH, + TdrDto.PROPERTY_MEAN_FISHING_DEPTH, + TdrDto.PROPERTY_MEDIAN_FISHING_DEPTH, + TdrDto.PROPERTY_MIN_FISHING_DEPTH, + TdrDto.PROPERTY_MAX_FISHING_DEPTH).build(); + + public static final Set<String> SPECIES_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(TdrDto.PROPERTY_SPECIES).build(); + + public static final String PROPERTY_CARACTERISTICS_TAB_VALID = "caracteristicsTabValid"; + + public static final String PROPERTY_LOCALISATION_TAB_VALID = "localisationTabValid"; + + public static final String PROPERTY_TIMESTAMP_TAB_VALID = "timestampTabValid"; + + public static final String PROPERTY_KEY_DATA_TAB_VALID = "keyDataTabValid"; + + public static final String PROPERTY_SPECIES_TAB_VALID = "speciesTabValid"; + + private static final long serialVersionUID = 1L; + + protected boolean caracteristicsTabValid; + + protected boolean localisationTabValid; + + protected boolean timestampTabValid; + + protected boolean keyDataTabValid; + + protected boolean speciesTabValid; + + public TdrUIModel(TdrUI ui) { + super(SetLonglineTdrDto.class, + TdrDto.class, + new String[]{ + SetLonglineTdrDto.PROPERTY_TDR, + SetLonglineTdrDto.PROPERTY_SETTING_START_TIME_STAMP + }, + new String[]{ + + // caracteristics tab + TdrDto.PROPERTY_HOME_ID, + TdrDto.PROPERTY_SERIAL_NO, + TdrDto.PROPERTY_SENSOR_BRAND, + TdrDto.PROPERTY_HAS_DATA, + TdrDto.PROPERTY_DATA, + + // localisation tab + TdrDto.PROPERTY_SECTION, + TdrDto.PROPERTY_BASKET, + TdrDto.PROPERTY_BRANCHLINE, + TdrDto.PROPERTY_ITEM_HORIZONTAL_POSITION, + TdrDto.PROPERTY_ITEM_VERTICAL_POSITION, + TdrDto.PROPERTY_FLOATLINE1_LENGTH, + TdrDto.PROPERTY_FLOATLINE2_LENGTH, + + // timestamp tab + TdrDto.PROPERTY_DEPLOYEMENT_START, + TdrDto.PROPERTY_DEPLOYEMENT_END, + TdrDto.PROPERTY_FISHING_START, + TdrDto.PROPERTY_FISHING_END, + + // key data tab + TdrDto.PROPERTY_FISHING_START_DEPTH, + TdrDto.PROPERTY_FISHING_END_DEPTH, + TdrDto.PROPERTY_MEAN_DEPLOYEMENT_DEPTH, + TdrDto.PROPERTY_MEDIAN_DEPLOYEMENT_DEPTH, + TdrDto.PROPERTY_MEAN_FISHING_DEPTH, + TdrDto.PROPERTY_MEDIAN_FISHING_DEPTH, + TdrDto.PROPERTY_MIN_FISHING_DEPTH, + TdrDto.PROPERTY_MAX_FISHING_DEPTH, + + // species tab + TdrDto.PROPERTY_SPECIES}); + + List<ContentTableMeta<TdrDto>> metas = Lists.newArrayList( + ContentTableModel.newTableMeta(TdrDto.class, TdrDto.PROPERTY_HOME_ID, false), + ContentTableModel.newTableMeta(TdrDto.class, TdrDto.PROPERTY_SERIAL_NO, false), + ContentTableModel.newTableMeta(TdrDto.class, TdrDto.PROPERTY_SENSOR_BRAND, false), + ContentTableModel.newTableMeta(TdrDto.class, TdrDto.PROPERTY_HAS_DATA, false)); + + initModel(ui, metas); + + } + + @Override + protected ContentTableModel<SetLonglineTdrDto, TdrDto> createTableModel( + ObserveContentTableUI<SetLonglineTdrDto, TdrDto> ui, + List<ContentTableMeta<TdrDto>> contentTableMetas) { + return new ContentTableModel<SetLonglineTdrDto, TdrDto>(ui, contentTableMetas) { + private static final long serialVersionUID = 1L; + @Override + protected Collection<TdrDto> getChilds(SetLonglineTdrDto bean) { + return bean.getTdr(); + } + + @Override + protected void load(TdrDto source, TdrDto target) { + TdrDtos.copyTdrDto(source, target); + } + + @Override + protected void setChilds(SetLonglineTdrDto parent, List<TdrDto> childs) { + parent.setTdr(childs); + } + }; + } + + public boolean isCaracteristicsTabValid() { + return caracteristicsTabValid; + } + + public void setCaracteristicsTabValid(boolean caracteristicsTabValid) { + this.caracteristicsTabValid = caracteristicsTabValid; + firePropertyChange(PROPERTY_CARACTERISTICS_TAB_VALID, null, caracteristicsTabValid); + } + + public boolean isLocalisationTabValid() { + return localisationTabValid; + } + + public void setLocalisationTabValid(boolean localisationTabValid) { + this.localisationTabValid = localisationTabValid; + firePropertyChange(PROPERTY_LOCALISATION_TAB_VALID, null, localisationTabValid); + } + + public boolean isKeyDataTabValid() { + return keyDataTabValid; + } + + public void setKeyDataTabValid(boolean keyDataTabValid) { + this.keyDataTabValid = keyDataTabValid; + firePropertyChange(PROPERTY_KEY_DATA_TAB_VALID, null, keyDataTabValid); + } + + public boolean isSpeciesTabValid() { + return speciesTabValid; + } + + public void setSpeciesTabValid(boolean speciesTabValid) { + this.speciesTabValid = speciesTabValid; + firePropertyChange(PROPERTY_SPECIES_TAB_VALID, null, speciesTabValid); + } + + public boolean isTimestampTabValid() { + return timestampTabValid; + } + + public void setTimestampTabValid(boolean timestampTabValid) { + this.timestampTabValid = timestampTabValid; + firePropertyChange(PROPERTY_TIMESTAMP_TAB_VALID, null, timestampTabValid); + } +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/WeightMeasuresTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/WeightMeasuresTableModel.java new file mode 100644 index 0000000..c2bcea1 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/longline/WeightMeasuresTableModel.java @@ -0,0 +1,105 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.longline.WeightMeasureDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.longline.WeightMeasureTypeDto; +import fr.ird.observe.application.swing.ui.util.table.EditableTableWithCacheTableModelSupport; + +/** + * Created on 12/3/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.8 + */ +public class WeightMeasuresTableModel extends EditableTableWithCacheTableModelSupport<WeightMeasureDto> { + + private static final long serialVersionUID = 1L; + + public WeightMeasuresTableModel() { + super(); + } + + @Override + public boolean isRowNotEmpty(WeightMeasureDto valid) { + return !(valid.getWeightMeasureType() == null && valid.getWeight() == null); + } + + @Override + public boolean isRowValid(WeightMeasureDto valid) { + Float weight = valid.getWeight(); + return !(valid.getWeightMeasureType() == null || weight == null) && weight > 0 && weight < 1000; + } + + @Override + protected WeightMeasureDto createNewRow() { + return new WeightMeasureDto(); + } + + @Override + public int getColumnCount() { + return 2; + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + + WeightMeasureDto measure = data.get(rowIndex); + Object result; + switch (columnIndex) { + case 0: + result = measure.getWeightMeasureType(); + break; + case 1: + result = measure.getWeight(); + break; + default: + throw new IllegalStateException("Can't come here"); + } + return result; + } + + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + + WeightMeasureDto measure = data.get(rowIndex); + switch (columnIndex) { + case 0: + + measure.setWeightMeasureType((ReferentialReference<WeightMeasureTypeDto>) aValue); + break; + case 1: + + measure.setWeight((Float) aValue); + break; + + default: + throw new IllegalStateException("Can't come here"); + } + + setModified(true); + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/AbstractSampleUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/AbstractSampleUI.jcss new file mode 100644 index 0000000..e23d202 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/AbstractSampleUI.jcss @@ -0,0 +1,90 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +NumberEditor { + bean:{tableEditBean}; + autoPopup:{config.isAutoPopupNumberEditor()}; + showPopupButton:{config.isShowNumberEditorButton()}; + showReset:true; +} + +JToolBar { + borderPainted:false; + floatable:false; + opaque:false; +} + +#speciesLabel { + labelFor:{species}; +} + +#species { + property:"species"; + bean:{tableEditBean}; + showReset:true; + selectedItem:{tableEditBean.getSpecies()}; +} + +#lengthLabel { + labelFor:{length}; +} + +#length { + property:"length"; + model:{tableEditBean.getLength()}; + useFloat:true; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL1_PATTERN}; +} + +#lengthSourceInformation { + disabledIcon: {iconDataObserve}; + icon: {iconDataCalcule}; + enabled: {tableEditBean.isLengthSource()}; + toolTipText:{getLengthDataTip(tableEditBean.isLengthSource())}; +} + +#weightLabel { + text:"observe.common.weight.ind"; + labelFor:{weight}; +} + +#weight { + property:"weight"; + model:{tableEditBean.getWeight()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL2_PATTERN}; + _validatorLabel:{"observe.common.weight.ind"}; +} + +#weightSourceInformation { + disabledIcon: {iconDataObserve}; + icon: {iconDataCalcule}; + enabled: {tableEditBean.isWeightSource()}; + toolTipText:{getWeightDataTip(tableEditBean.isWeightSource())}; +} + +#comment { + minimumSize:{new Dimension(10,80)}; +} + +#comment2 { + text:{getStringValue(bean.getComment())}; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/CodeMesureEnum.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/CodeMesureEnum.java new file mode 100644 index 0000000..9e30c44 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/CodeMesureEnum.java @@ -0,0 +1,51 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +import static org.nuiton.i18n.I18n.n; + +/** + * Définition des codes mesures utilisés pour saisir et afficher les + * échantillons thon. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.9.1 + */ +public enum CodeMesureEnum implements Comparable<CodeMesureEnum> { + + /** inconnue */ + unknown, + + /** mesure LD1 */ + ld1, + + /** mesure LF */ + lf; + + static { + + n("observe.codeMesureEnum.unknown"); + n("observe.codeMesureEnum.ld1"); + n("observe.codeMesureEnum.lf"); + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeatureMeasurementCellEditor.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeatureMeasurementCellEditor.java new file mode 100644 index 0000000..ae35f09 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeatureMeasurementCellEditor.java @@ -0,0 +1,173 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.GearCaracteristicDto; +import fr.ird.observe.services.dto.referential.GearCaracteristicTypeDtos; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import jaxx.runtime.swing.JAXXWidgetUtil; +import jaxx.runtime.swing.editor.cell.NumberCellEditor; + +import javax.swing.JTable; +import javax.swing.border.LineBorder; +import javax.swing.event.CellEditorListener; +import javax.swing.table.TableCellEditor; +import java.awt.Color; +import java.awt.Component; +import java.util.EventObject; +import java.util.Map; +import java.util.TreeMap; + +/** + * Created on 4/7/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.16 + */ +public class GearUseFeatureMeasurementCellEditor implements TableCellEditor { + + protected final int caracteristicColumn; + + protected TableCellEditor editor; + + protected Map<String, TableCellEditor> editorsByGearCaracteristicId; + + + public GearUseFeatureMeasurementCellEditor(int caracteristicColumn) { + super(); + this.caracteristicColumn = caracteristicColumn; + + } + + @Override + public Object getCellEditorValue() { + return editor.getCellEditorValue(); + } + + @Override + public boolean isCellEditable(EventObject anEvent) { + return true; + } + + @Override + public boolean shouldSelectCell(EventObject anEvent) { + return editor.shouldSelectCell(anEvent); + } + + @Override + public boolean stopCellEditing() { + return editor.stopCellEditing(); + } + + @Override + public void cancelCellEditing() { + editor.cancelCellEditing(); + } + + @Override + public void addCellEditorListener(CellEditorListener l) { + editor.addCellEditorListener(l); + } + + @Override + public void removeCellEditorListener(CellEditorListener l) { + editor.removeCellEditorListener(l); + } + + public Map<String, TableCellEditor> getEditorsByGearCaracteristicId(JTable table) { + if (editorsByGearCaracteristicId == null) { + editorsByGearCaracteristicId = new TreeMap<>(); + + { + // texte + TableCellEditor editor = table.getDefaultEditor(Object.class); + editorsByGearCaracteristicId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.1", editor); + } + { + // boolean + TableCellEditor editor = table.getDefaultEditor(Boolean.class); + editorsByGearCaracteristicId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.2", editor); + } + { + // entier signé + NumberCellEditor<Integer> editor = JAXXWidgetUtil.newNumberTableCellEditor(Integer.class, true); + editor.getNumberEditor().setSelectAllTextOnError(true); + editor.getNumberEditor().setNumberPattern("\\d{0,6}?"); + editor.getNumberEditor().getTextField().setBorder(new LineBorder(Color.GRAY, 2)); + editorsByGearCaracteristicId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.3", editor); + } + { + // décimal signé + NumberCellEditor<Float> editor = JAXXWidgetUtil.newNumberTableCellEditor(Float.class, true); + editor.getNumberEditor().setSelectAllTextOnError(true); + editor.getNumberEditor().setNumberPattern("\\d{0,6}(\\.\\d{0,4})?"); + editor.getNumberEditor().getTextField().setBorder(new LineBorder(Color.GRAY, 2)); + editorsByGearCaracteristicId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.4", editor); + } + { + // entier non signé + NumberCellEditor<Integer> editor = JAXXWidgetUtil.newNumberTableCellEditor(Integer.class, false); + editor.getNumberEditor().setSelectAllTextOnError(true); + editor.getNumberEditor().setNumberPattern("\\d{0,6}?"); + editor.getNumberEditor().getTextField().setBorder(new LineBorder(Color.GRAY, 2)); + editorsByGearCaracteristicId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.5", editor); + } + { + // décimal non signé + NumberCellEditor<Float> editor = JAXXWidgetUtil.newNumberTableCellEditor(Float.class, false); + editor.getNumberEditor().setSelectAllTextOnError(true); + editor.getNumberEditor().setNumberPattern("\\d{0,6}(\\.\\d{0,4})?"); + editor.getNumberEditor().getTextField().setBorder(new LineBorder(Color.GRAY, 2)); + editorsByGearCaracteristicId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.6", editor); + } + + } + return editorsByGearCaracteristicId; + } + + @Override + public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { + + ReferentialReference<GearCaracteristicDto> caracteristicRef = (ReferentialReference<GearCaracteristicDto>) table.getModel().getValueAt(row, caracteristicColumn); + if (caracteristicRef == null) { + + // can't edit a null value ? + editor = table.getDefaultEditor(Object.class); + + } else { + + String gearCaracteristicTypeId = (String) caracteristicRef.getPropertyValue(GearCaracteristicDto.PROPERTY_GEAR_CARACTERISTIC_TYPE); + + Map<String, TableCellEditor> editors = getEditorsByGearCaracteristicId(table); + editor = editors.get(gearCaracteristicTypeId); + + value = GearCaracteristicTypeDtos.getTypeValue(gearCaracteristicTypeId, value); + + } + + Component result = editor.getTableCellEditorComponent(table, value, isSelected, row, column); + return result; + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeatureMeasurementCellRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeatureMeasurementCellRenderer.java new file mode 100644 index 0000000..3f7488b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeatureMeasurementCellRenderer.java @@ -0,0 +1,111 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.GearCaracteristicDto; +import fr.ird.observe.services.dto.referential.GearCaracteristicTypeDtos; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.UIHelper; + +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; +import javax.swing.table.TableCellRenderer; +import java.awt.Component; +import java.util.Map; +import java.util.TreeMap; + +/** + * Created on 4/7/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.16 + */ +public class GearUseFeatureMeasurementCellRenderer implements TableCellRenderer { + + protected final int caracteristicColumn; + + protected final Map<String, TableCellRenderer> renderersByCaracteristicTypeId; + + + public GearUseFeatureMeasurementCellRenderer(int caracteristicColumn, DefaultTableCellRenderer renderer) { + + this.caracteristicColumn = caracteristicColumn; + renderersByCaracteristicTypeId = new TreeMap<>(); + + { + // texte + TableCellRenderer editor = UIHelper.newStringTableCellRenderer(renderer, 10, true); + renderersByCaracteristicTypeId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.1", editor); + } + { + // boolean + TableCellRenderer editor = UIHelper.newBooleanTableCellRenderer(renderer); + renderersByCaracteristicTypeId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.2", editor); + } + { + // entier signé + TableCellRenderer editor = UIHelper.newEmptyNumberTableCellRenderer(renderer); + renderersByCaracteristicTypeId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.3", editor); + } + { + // décimal signé + TableCellRenderer editor = UIHelper.newEmptyNumberTableCellRenderer(renderer); + renderersByCaracteristicTypeId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.4", editor); + } + { + // entier non signé + TableCellRenderer editor = UIHelper.newEmptyNumberTableCellRenderer(renderer); + renderersByCaracteristicTypeId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.5", editor); + } + { + // décimal non signé + TableCellRenderer editor = UIHelper.newEmptyNumberTableCellRenderer(renderer); + renderersByCaracteristicTypeId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.6", editor); + } + } + + @Override + public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + + TableCellRenderer tableCellRenderer; + + ReferentialReference<GearCaracteristicDto> caracteristicRef = (ReferentialReference<GearCaracteristicDto>) table.getModel().getValueAt(row, caracteristicColumn); + if (caracteristicRef == null) { + + tableCellRenderer = table.getDefaultRenderer(Object.class); + + } else { + String gearCaracteristicTypeId = (String) caracteristicRef.getPropertyValue(GearCaracteristicDto.PROPERTY_GEAR_CARACTERISTIC_TYPE); + + tableCellRenderer = renderersByCaracteristicTypeId.get(gearCaracteristicTypeId); + + value = GearCaracteristicTypeDtos.getTypeValue(gearCaracteristicTypeId, value); + + } + + Component result = tableCellRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); + return result; + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeaturesMeasurementSeinesTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeaturesMeasurementSeinesTableModel.java new file mode 100644 index 0000000..0f79597 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeaturesMeasurementSeinesTableModel.java @@ -0,0 +1,133 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.GearCaracteristicDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.seine.GearUseFeaturesMeasurementSeineDto; +import fr.ird.observe.application.swing.ui.util.table.EditableTableWithCacheTableModelSupport; + +/** + * Created on 4/7/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.16 + */ +public class GearUseFeaturesMeasurementSeinesTableModel extends EditableTableWithCacheTableModelSupport<GearUseFeaturesMeasurementSeineDto> { + + private static final long serialVersionUID = 1L; + + public GearUseFeaturesMeasurementSeinesTableModel() { + super(); + } + + @Override + public boolean isRowNotEmpty(GearUseFeaturesMeasurementSeineDto valid) { + return !(valid.getGearCaracteristic() == null && valid.getMeasurementValue() == null); + } + + @Override + protected boolean isRowValid(GearUseFeaturesMeasurementSeineDto valid) { + String size = valid.getMeasurementValue(); + return !(valid.getGearCaracteristic() == null || size == null) && !size.isEmpty(); + } + + @Override + public int getColumnCount() { + return 2; + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + + GearUseFeaturesMeasurementSeineDto measure = data.get(rowIndex); + Object result; + switch (columnIndex) { + case 0: + result = measure.getGearCaracteristic(); + break; + case 1: + result = measure.getMeasurementValue(); + break; + default: + throw new IllegalStateException("Can't come here"); + } + return result; + } + + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + + boolean result; + switch (columnIndex) { + case 0: + result = true; + break; + case 1: + GearUseFeaturesMeasurementSeineDto measure = data.get(rowIndex); + result = measure != null && measure.getGearCaracteristic() != null; + break; + default: + throw new IllegalStateException("Can't come here"); + } + return result; + + } + + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + + GearUseFeaturesMeasurementSeineDto measure = data.get(rowIndex); + switch (columnIndex) { + case 0: + measure.setGearCaracteristic((ReferentialReference<GearCaracteristicDto>) aValue); + break; + case 1: + + measure.setMeasurementValue(aValue == null ? null : String.valueOf(aValue)); + break; + + default: + throw new IllegalStateException("Can't come here"); + } + + setModified(true); + + } + + @Override + public void removeSelectedRow() { + + super.removeSelectedRow(); + + // revalidate table model + validate(); + setModified(true); + + } + + @Override + protected GearUseFeaturesMeasurementSeineDto createNewRow() { + return new GearUseFeaturesMeasurementSeineDto(); + } +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeaturesSeineTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeaturesSeineTableModel.java new file mode 100644 index 0000000..7cf3937 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeaturesSeineTableModel.java @@ -0,0 +1,177 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Sets; +import fr.ird.observe.services.dto.referential.GearDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.seine.GearUseFeaturesMeasurementSeineDto; +import fr.ird.observe.services.dto.seine.GearUseFeaturesSeineDto; +import fr.ird.observe.services.dto.seine.GearUseFeaturesSeineDtos; +import fr.ird.observe.services.dto.seine.TripSeineGearUseDto; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.Collection; +import java.util.List; + +/** + * Created on 4/7/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.16 + */ +public class GearUseFeaturesSeineTableModel extends ContentTableModel<TripSeineGearUseDto, GearUseFeaturesSeineDto> { + + /** Logger. */ + private static final Log log = LogFactory.getLog(GearUseFeaturesSeineTableModel.class); + + private static final long serialVersionUID = 1L; + + private transient GearUseFeaturesSeineUIHandler gearUseFeaturesSeineUIHandler; + + public GearUseFeaturesSeineTableModel(ObserveContentTableUI<TripSeineGearUseDto, GearUseFeaturesSeineDto> context, + List<ContentTableMeta<GearUseFeaturesSeineDto>> contentTableMetas) { + super(context, contentTableMetas); + } + + public void setGearUseFeaturesSeineUIHandler(GearUseFeaturesSeineUIHandler gearUseFeaturesSeineUIHandler) { + this.gearUseFeaturesSeineUIHandler = gearUseFeaturesSeineUIHandler; + } + + @Override + public void addNewEntry() { + + int editingRow = getSelectedRow(); + + if (editingRow > -1) { + + // store sizes and weights for the selected row + // before creating a new one ? + GearUseFeaturesSeineUIModel model = getModel(); + model.getMeasurementsTableModel().storeInCacheForRow(editingRow); + + } + + super.addNewEntry(); + } + + @Override + public void updateRowFromEditBean() { + + GearUseFeaturesSeineUIModel model = getModel(); + + int editingRow = getSelectedRow(); + GearUseFeaturesSeineDto rowBean = getRowBean(); + GearUseFeaturesMeasurementSeinesTableModel measurementsTableModel = model.getMeasurementsTableModel(); + + List<GearUseFeaturesMeasurementSeineDto> measurements; + + if (rowBean.getId() == null && CollectionUtils.isEmpty(measurementsTableModel.getCacheForRow(editingRow))) { + + // new gear usage, add default measurements + + ReferentialReference<GearDto> gear = rowBean.getGear(); + measurements = gearUseFeaturesSeineUIHandler.getDefaultGearUseFeaturesMeasurementSeine(gear.getId()); + if (log.isInfoEnabled()) { + log.info("Create mode, use default measurements: " + measurements.size()); + } + measurementsTableModel.removeCacheForRow(editingRow); + measurementsTableModel.initCacheForRow(editingRow, measurements); + + measurementsTableModel.setData(measurements); + measurementsTableModel.setModified(false); + + } else { + + // store current measurements for the selected row + measurementsTableModel.storeInCacheForRow(editingRow); + + measurements = measurementsTableModel.getData(); + } + + rowBean.setGearUseFeaturesMeasurement(Sets.newLinkedHashSet(measurements)); + + super.updateRowFromEditBean(); + + + } + + @Override + protected void removeRow(int row) { + super.removeRow(row); + + // remove sizes and weights for the deleted row + // also update rows to row - 1 (when after the deleted row) + GearUseFeaturesSeineUIModel model = getModel(); + model.getMeasurementsTableModel().removeCacheForRow(row); + + } + + @Override + protected void setChilds(TripSeineGearUseDto parent, List<GearUseFeaturesSeineDto> childs) { + parent.getGearUseFeaturesSeine().clear(); + parent.addAllGearUseFeaturesSeine(childs); + } + + @Override + public void resetEditBean() { + + int row = getSelectedRow(); + if (log.isInfoEnabled()) { + log.info("Reset edit bean at row: " + row); + } + GearUseFeaturesSeineUIModel model = getModel(); + model.getMeasurementsTableModel().resetCacheForRow(row); + + super.resetEditBean(); + + } + + @Override + protected Collection<GearUseFeaturesSeineDto> getChilds(TripSeineGearUseDto bean) { + return bean.getGearUseFeaturesSeine(); + } + + @Override + protected void load(GearUseFeaturesSeineDto source, GearUseFeaturesSeineDto target) { + GearUseFeaturesSeineDtos.copyGearUseFeaturesSeineDto(source, target); + } + + @Override + protected void resetRow(int row) { + super.resetRow(row); + + GearUseFeaturesSeineUIModel model = getModel(); + model.getMeasurementsTableModel().resetCacheForRow(row); + } + + @Override + protected GearUseFeaturesSeineUIModel getModel() { + return (GearUseFeaturesSeineUIModel) super.getModel(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeaturesSeineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeaturesSeineUI.jaxx new file mode 100644 index 0000000..60ef0c6 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeaturesSeineUI.jaxx @@ -0,0 +1,155 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.table.ContentTableUI + superGenericType='TripSeineGearUseDto, GearUseFeaturesSeineDto' + contentTitle='{n("observe.content.gearUseFeaturesSeine.title")}' + saveNewEntryText='{n("observe.content.action.create.gearUseFeaturesSeine")}' + saveNewEntryTip='{n("observe.content.action.create.gearUseFeaturesSeine.tip")}'> + + <style source="../../CommonTable.jcss"/> + + <import> + fr.ird.observe.services.dto.CommentableDto + fr.ird.observe.services.dto.seine.TripSeineGearUseDto + fr.ird.observe.services.dto.seine.GearUseFeaturesSeineDto + fr.ird.observe.services.dto.seine.GearUseFeaturesMeasurementSeineDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.GearDto + fr.ird.observe.application.swing.ui.content.table.* + fr.ird.observe.application.swing.ui.util.BooleanEditor + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + java.awt.Dimension + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <GearUseFeaturesSeineUIHandler id='handler' constructorParams='this'/> + + <!-- model --> + <GearUseFeaturesSeineUIModel id='model' constructorParams='this'/> + + <GearUseFeaturesMeasurementSeinesTableModel id='measurementsTableModel' + initializer="getModel().getMeasurementsTableModel()"/> + + <!-- edit bean --> + <TripSeineGearUseDto id='bean'/> + + <!-- table edit bean --> + <GearUseFeaturesSeineDto id='tableEditBean'/> + + <!-- table model --> + <ContentTableModel id='tableModel'/> + + <!-- le validateur de l'écran --> + <BeanValidator id='validator' + beanClass='fr.ird.observe.services.dto.seine.TripSeineGearUseDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update'/> + + <!-- le validateur d'une entrée de tableau --> + <BeanValidator id='validatorTable' + autoField='true' + beanClass='fr.ird.observe.services.dto.seine.GearUseFeaturesSeineDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update'/> + + <JPopupMenu id='measurementsTablePopup'> + <JMenuItem id='addMeasurement' onActionPerformed='getHandler().addMeasurement()'/> + <JMenuItem id='deleteSelectedMeasurement' onActionPerformed='getHandler().deleteSelectedMeasurement()'/> + </JPopupMenu> + + <Table id='editorPanel' fill='both' insets='0' weighty="1"> + <row> + <cell weightx="1" weighty="0.9"> + + <JTabbedPane id='gearUseFeaturesTabPane'> + + <tab id='generalTab'> + + <JPanel layout='{new BorderLayout()}'> + + <Table id='editForm' fill='both' insets='1' constraints="BorderLayout.NORTH"> + + <!-- gear --> + <row> + <cell> + <JLabel id='gearLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='gear' constructorParams='this' genericType='ReferentialReference<GearDto>' _entityClass='GearDto.class'/> + </cell> + </row> + + <!-- number --> + <row> + <cell> + <JLabel id='numberLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='number' constructorParams='this'/> + </cell> + </row> + + <!-- usedInTrip --> + <row> + <cell> + <JLabel id='usedInTripLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BooleanEditor id='usedInTrip'/> + </cell> + </row> + + </Table> + + </JPanel> + + + </tab> + + <tab id='measurementsFormTab'> + + <JScrollPane id='measurementsScrollPane'> + <JTable id='measurementsTable'/> + </JScrollPane> + + </tab> + </JTabbedPane> + + </cell> + </row> + <row> + <cell weighty='0.1'> + <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2'/> + </JScrollPane> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeaturesSeineUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeaturesSeineUI.jcss new file mode 100644 index 0000000..8e1af4e --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeaturesSeineUI.jcss @@ -0,0 +1,103 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#model { + valid:{validator.isValid() && validatorTable.isValid() && getMeasurementsTableModel().isValid()}; + canSaveRow:{validatorTable.isChanged() && validatorTable.isValid() && getMeasurementsTableModel().isValid()}; + canResetRow:{validatorTable.isChanged()}; +} + +/* ***************************************************************************** */ +/* GENERAL TAB **************************************************************** */ +/* ***************************************************************************** */ + +#generalTab { + title:{t("observe.content.gearUseFeaturesSeine.tab.general")}; + icon:{handler.getErrorIconIfFalse(model.isGeneralTabValid())}; +} + +#gearLabel { + text:"observe.content.gearUseFeaturesSeine.gear"; + labelFor:{gear}; +} + +#gear { + property:{GearUseFeaturesSeineDto.PROPERTY_GEAR}; + selectedItem:{tableEditBean.getGear()}; +} + +#numberLabel { + text:"observe.content.gearUseFeaturesSeine.number"; + labelFor:{number}; +} + +#number { + property:{GearUseFeaturesSeineDto.PROPERTY_NUMBER}; + model:{tableEditBean.getNumber()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; +} + +#usedInTripLabel { + text:"observe.content.gearUseFeaturesSeine.usedInTrip"; + labelFor:{usedInTrip}; +} + +#usedInTrip { + booleanValue:{tableEditBean.getUsedInTrip()}; + _tablePropertyName:{GearUseFeaturesSeineDto.PROPERTY_USED_IN_TRIP}; +} + +/* ***************************************************************************** */ +/* MEASUREMENTS TAB *********************************************************** */ +/* ***************************************************************************** */ + +#measurementsFormTab { + title:{t("observe.content.gearUseFeaturesSeine.tab.measurements")}; + icon:{handler.getErrorIconIfFalse(measurementsTableModel.isValid())}; + enabled:{!tableModel.isCreate()}; +} + +#measurementsTable { + model: {measurementsTableModel}; +} + +#comment { + columnHeaderView:{new JLabel(t("observe.content.gearUseFeaturesSeine.comment"))}; + minimumSize:{new Dimension(10,80)}; +} + +#comment2 { + _tablePropertyName: {GearUseFeaturesSeineDto.PROPERTY_COMMENT}; + text:{getStringValue(tableEditBean.getComment())}; +} + +#addMeasurement { + text: "observe.content.gearUseFeaturesSeine.action.addMeasurement"; + toolTipText: "observe.content.gearUseFeaturesSeine.action.addMeasurement.tip"; + actionIcon: add; +} + +#deleteSelectedMeasurement { + text: "observe.content.gearUseFeaturesSeine.action.deleteSelectedMeasurement"; + toolTipText: "observe.content.gearUseFeaturesSeine.action.deleteSelectedMeasurement.tip"; + actionIcon: delete; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeaturesSeineUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeaturesSeineUIHandler.java new file mode 100644 index 0000000..3b0ad45 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeaturesSeineUIHandler.java @@ -0,0 +1,506 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.referential.GearCaracteristicDto; +import fr.ird.observe.services.dto.referential.GearCaracteristicTypeDtos; +import fr.ird.observe.services.dto.referential.GearDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.dto.seine.GearUseFeaturesMeasurementSeineDto; +import fr.ird.observe.services.dto.seine.GearUseFeaturesSeineDto; +import fr.ird.observe.services.dto.seine.TripSeineGearUseDto; +import fr.ird.observe.services.dto.seine.TripSeineGearUseDtos; +import fr.ird.observe.services.service.ReferentialService; +import fr.ird.observe.services.service.seine.TripSeineGearUseService; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.ContentUIInitializer; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIHandler; +import jaxx.runtime.SwingUtil; +import jaxx.runtime.validator.swing.SwingValidatorMessage; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.JComponent; +import javax.swing.JOptionPane; +import javax.swing.JTable; +import javax.swing.event.TableModelListener; +import javax.swing.table.DefaultTableCellRenderer; +import java.awt.GridBagConstraints; +import java.awt.Insets; +import java.beans.PropertyChangeListener; +import java.util.Collections; +import java.util.HashSet; +import java.util.Iterator; +import java.util.List; +import java.util.Set; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 3/24/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.16 + */ +public class GearUseFeaturesSeineUIHandler extends ContentTableUIHandler<TripSeineGearUseDto, GearUseFeaturesSeineDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(GearUseFeaturesSeineUIHandler.class); + + // Compute valid state of tab from the error table + protected final TableModelListener computeTabValidStateListener; + + private final PropertyChangeListener measurementsTableModelModified; + + public GearUseFeaturesSeineUIHandler(GearUseFeaturesSeineUI ui) { + super(ui, DataContextType.TripSeine); + computeTabValidStateListener = e -> { + + SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); + computeTabValidState(source); + + }; + measurementsTableModelModified = evt -> onMeasurementsTableModelModified((Boolean) evt.getNewValue()); + } + + @Override + public GearUseFeaturesSeineUI getUi() { + return (GearUseFeaturesSeineUI) super.getUi(); + } + + @Override + public GearUseFeaturesSeineUIModel getModel() { + return (GearUseFeaturesSeineUIModel) super.getModel(); + } + + @Override + public void initUI() { + + super.initUI(); + + getModel().addPropertyChangeListener(GearUseFeaturesSeineUIModel.PROPERTY_EDITABLE, evt -> { + Boolean newValue = (Boolean) evt.getNewValue(); + setTableModelEditable(newValue); + }); + + setTableModelEditable(getModel().isEditable()); + + getTableModel().setGearUseFeaturesSeineUIHandler(this); + + } + + @Override + public void openUI() { + + if (log.isInfoEnabled()) { + log.info("OpenUI: " + getModel()); + } + + super.openUI(); + + // To be sure always remove listener (could prevent some leaks) + getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); + // listen messages to see if required to add + getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); + + SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); + computeTabValidState(errorTableModel); + + } + + @Override + public void startEditUI(String... binding) { + + getModel().getMeasurementsTableModel().setEditable(true); + + super.startEditUI(binding); + + } + + public void addMeasurement() { + + GearUseFeaturesMeasurementSeinesTableModel tableModel = getUi().getMeasurementsTableModel(); + tableModel.addNewRow(); + + } + + public void deleteSelectedMeasurement() { + + GearUseFeaturesMeasurementSeinesTableModel tableModel = getUi().getMeasurementsTableModel(); + + boolean selectionEmpty = tableModel.isSelectionEmpty(); + + if (!selectionEmpty) { + + GearUseFeaturesMeasurementSeineDto data = tableModel.getSelectedRow(); + + if (log.isInfoEnabled()) { + log.info("Delete: " + data); + } + + ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); + int response = UIHelper.askUser(mainUI, + t("observe.title.delete"), + t("observe.content.measurement.delete.message"), + JOptionPane.WARNING_MESSAGE, + new Object[]{t("observe.choice.confirm.delete"), + t("observe.choice.cancel")}, + 1); + + if (response != 0) { + + // user cancel + return; + } + + tableModel.removeSelectedRow(); + + } + + } + + public List<GearUseFeaturesMeasurementSeineDto> getDefaultGearUseFeaturesMeasurementSeine(String gearId) { + + ReferentialService referentialService = getDataSource().newReferentialService(); + + Form<GearDto> gearDtoForm = referentialService.loadForm(GearDto.class, gearId); + + GearDto gearDto = gearDtoForm.getObject(); + + List<GearUseFeaturesMeasurementSeineDto> measurements = Lists.newArrayList( + Iterables.transform(gearDto.getGearCaracteristic(), + input -> { + GearUseFeaturesMeasurementSeineDto measurementSeineDto = new GearUseFeaturesMeasurementSeineDto(); + String gearCaracterisiticTypeId = (String) input.getPropertyValue(GearCaracteristicDto.PROPERTY_GEAR_CARACTERISTIC_TYPE); + if (GearCaracteristicTypeDtos.isBoolean(gearCaracterisiticTypeId)) { + measurementSeineDto.setMeasurementValue(Boolean.FALSE.toString()); + } + measurementSeineDto.setGearCaracteristic(input); + return measurementSeineDto; + })); + + return measurements; + + } + + @Override + protected void onSelectedRowChanged(int editingRow, GearUseFeaturesSeineDto bean, boolean create) { + + if (log.isInfoEnabled()) { + log.info("Selected row changed: " + editingRow + ", create? " + create); + } + + GearUseFeaturesSeineUI ui = getUi(); + + UIHelper.stopEditing(ui.getMeasurementsTable()); + + GearUseFeaturesSeineTableModel tableModel = getTableModel(); + GearUseFeaturesSeineUIModel model = getModel(); + + boolean emptySelection = editingRow == -1; + + // load size measures + + GearUseFeaturesMeasurementSeinesTableModel measurementsTableModel = model.getMeasurementsTableModel(); + List<GearUseFeaturesMeasurementSeineDto> measurements = emptySelection ? Collections.emptyList() : measurementsTableModel.getCacheForRow(editingRow); + if (measurements == null) { + + if (log.isInfoEnabled()) { + log.info("init measurements for row " + editingRow); + } + + // first time coming on this row + + if (tableModel.isCreate()) { + + // create mode: just init with empty list + measurements = Collections.emptyList(); + + if (log.isInfoEnabled()) { + log.info("create mode, use an empty list"); + } + + } else { + measurements = Lists.newArrayList(bean.getGearUseFeaturesMeasurement()); + } + + // init measurements + measurementsTableModel.initCacheForRow(editingRow, measurements); + + } else { + + if (log.isInfoEnabled()) { + log.info("Using existing measurements for row " + editingRow + " : " + measurements.size()); + } + } + + measurementsTableModel.setData(measurements); + + measurementsTableModel.setModified(false); + measurementsTableModel.setEditable(tableModel.isEditable()); + + if (!tableModel.isEditable()) { + return; + } + + JComponent requestFocus; + + if (tableModel.isCreate()) { + + // go back to first pane + ui.getGearUseFeaturesTabPane().setSelectedIndex(0); + + requestFocus = ui.getGear(); + + } else { + + requestFocus = ui.getGear(); + + } + + requestFocus.requestFocus(); + + } + + @Override + protected void initTableUI(DefaultTableCellRenderer renderer) { + + { + JTable table = getUi().getTable(); + + UIHelper.setI18nTableHeaderRenderer(table, + n("observe.content.gearUseFeaturesSeine.table.gear"), + n("observe.content.gearUseFeaturesSeine.table.gear.tip"), + n("observe.content.gearUseFeaturesSeine.table.number"), + n("observe.content.gearUseFeaturesSeine.table.number.tip"), + n("observe.content.gearUseFeaturesSeine.table.usedInTrip"), + n("observe.content.gearUseFeaturesSeine.table.usedInTrip.tip"), + n("observe.content.gearUseFeaturesSeine.table.comment"), + n("observe.content.gearUseFeaturesSeine.table.comment.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, GearDto.class)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 2, UIHelper.newBooleanTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 3, UIHelper.newStringTableCellRenderer(renderer, 10, true)); + } + + { + // init measurements table + JTable table = getUi().getMeasurementsTable(); + + UIHelper.setI18nTableHeaderRenderer(table, + n("observe.content.gearUseFeaturesSeine.table.gearCaracteristic"), + n("observe.content.gearUseFeaturesSeine.table.gearCaracteristic.tip"), + n("observe.content.gearUseFeaturesSeine.table.value"), + n("observe.content.gearUseFeaturesSeine.table.value.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, GearCaracteristicDto.class)); + UIHelper.setTableColumnRenderer(table, 1, new GearUseFeatureMeasurementCellRenderer(0, renderer)); + + table.getTableHeader().setReorderingAllowed(false); + + ReferentialReferenceDecorator<GearCaracteristicDto> decorator = getReferentialReferenceDecorator(GearCaracteristicDto.class); + + List<ReferentialReference<GearCaracteristicDto>> caracteristics = Lists.newArrayList(getDataSource().getReferentialReferences(GearCaracteristicDto.class)); + + UIHelper.setTableColumnEditor(table, 0, ContentUIInitializer.newDataColumnEditor(caracteristics, decorator)); + UIHelper.setTableColumnEditor(table, 1, new GearUseFeatureMeasurementCellEditor(0)); + + initInlineTable(getUi().getMeasurementsScrollPane(), + table, + getModel().getMeasurementsTableModel(), + measurementsTableModelModified, + getUi().getMeasurementsTablePopup(), + getUi().getAddMeasurement(), + getUi().getDeleteSelectedMeasurement()); + + } + + // Adapt layout to let more place for the editor + + getUi().getShowForm().remove(1); + getUi().getShowForm().add(SwingUtil.boxComponentWithJxLayer(getUi().getEditor()), new GridBagConstraints(0, 1, 1, 1, 1.0, 0.3, 10, 1, new Insets(0, 0, 0, 0), 0, 0), 1); + getUi().getEditor().remove(0); + getUi().getEditor().add(SwingUtil.boxComponentWithJxLayer(getUi().getEditorPanel()), new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, 10, 1, new Insets(0, 0, 0, 0), 0, 0), 0); + + + } + + @Override + protected String getEditBeanIdToLoad() { + return getDataContext().getSelectedTripSeineId(); + } + + @Override + protected void closeSafeUI() { + + if (log.isInfoEnabled()) { + log.info("CloseUI: " + getModel()); + } + super.closeSafeUI(); + + // remove listener + getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); + + } + + @Override + protected void resetEditBean() { + + UIHelper.stopEditing(getUi().getMeasurementsTable()); + + super.resetEditBean(); + + } + + @Override + public void resetEditUI() { + + getModel().getMeasurementsTableModel().clear(); + + super.resetEditUI(); + + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + + // par defaut, on suppose qu'on peut afficher les données + getModel().setShowData(true); + + String selectedTripId = dataContext.getSelectedTripId(); + + if (getOpenDataManager().isOpenTripSeine(selectedTripId)) { + + // mode mise a jour + return ContentMode.UPDATE; + } + + // mode lecture + + if (dataContext.isSelectedTripLongline()) { + + addInfoMessage(t("observe.content.tripLongline.message.not.open")); + + } else { + + addInfoMessage(t("observe.content.tripSeine.message.not.open")); + + } + + return ContentMode.READ; + } + + @Override + protected GearUseFeaturesSeineTableModel getTableModel() { + return (GearUseFeaturesSeineTableModel) super.getTableModel(); + } + + protected void setTableModelEditable(Boolean newValue) { + + getModel().getMeasurementsTableModel().setEditable(newValue); + + } + + protected void onMeasurementsTableModelModified(Boolean newValue) { + + if (newValue) { + + // modify the validator, since this is the best way to prevent table edit form actions + // that something was modified on the form + getUi().getValidatorTable().setChanged(true); + + } + + // recompute table model valid state + getModel().getMeasurementsTableModel().validate(); + + } + + protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { + + Set<String> errorProperties = new HashSet<>(); + int rowCount = errorTableModel.getRowCount(); + for (int i = 0; i < rowCount; i++) { + + SwingValidatorMessage row = errorTableModel.getRow(i); + if (NuitonValidatorScope.ERROR.equals(row.getScope())) { + errorProperties.add(row.getField()); + } + } + + boolean generalTabValid = !errorProperties.removeAll(GearUseFeaturesSeineUIModel.GENERAL_TAB_PROPERTIES); + + GearUseFeaturesSeineUIModel model = getModel(); + + model.setGeneralTabValid(generalTabValid); + + } + + @Override + protected void doPersist(TripSeineGearUseDto bean) { + + // On ne persiste pas les measurements qui sont vides + for (GearUseFeaturesSeineDto gearUseFeatures : bean.getGearUseFeaturesSeine()) { + if (!gearUseFeatures.isGearUseFeaturesMeasurementEmpty()) { + Iterator<GearUseFeaturesMeasurementSeineDto> iterator = gearUseFeatures.getGearUseFeaturesMeasurement().iterator(); + while (iterator.hasNext()) { + GearUseFeaturesMeasurementSeineDto gearUseFeaturesMeasurement = iterator.next(); + if (gearUseFeaturesMeasurement.isEmpty()) { + iterator.remove(); + } + } + } + } + + SaveResultDto saveResult = getTripSeineGearUseService().save(bean); + saveResult.toDto(bean); + + } + + @Override + protected void loadEditBean(String beanId) { + Form<TripSeineGearUseDto> form = getTripSeineGearUseService().loadForm(beanId); + loadReferentialReferenceSetsInModel(form); + getModel().setForm(form); + TripSeineGearUseDtos.copyTripSeineGearUseDto(form.getObject(), getBean()); + } + + protected TripSeineGearUseService getTripSeineGearUseService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripSeineGearUseService(); + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeaturesSeineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeaturesSeineUIModel.java new file mode 100644 index 0000000..11cbcce --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/GearUseFeaturesSeineUIModel.java @@ -0,0 +1,109 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import fr.ird.observe.services.dto.seine.GearUseFeaturesSeineDto; +import fr.ird.observe.services.dto.seine.TripSeineGearUseDto; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; + +import java.util.List; +import java.util.Set; + +/** + * Created on 3/24/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.16 + */ +public class GearUseFeaturesSeineUIModel extends ContentTableUIModel<TripSeineGearUseDto, GearUseFeaturesSeineDto> { + + private static final long serialVersionUID = 1L; + + public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; + + public static final Set<String> GENERAL_TAB_PROPERTIES = + ImmutableSet.<String>builder().add(GearUseFeaturesSeineDto.PROPERTY_GEAR, + GearUseFeaturesSeineDto.PROPERTY_NUMBER, + GearUseFeaturesSeineDto.PROPERTY_USED_IN_TRIP, + GearUseFeaturesSeineDto.PROPERTY_COMMENT).build(); + + protected boolean generalTabValid; + + private final GearUseFeaturesMeasurementSeinesTableModel measurementsTableModel; + + public GearUseFeaturesSeineUIModel(GearUseFeaturesSeineUI ui) { + + super(TripSeineGearUseDto.class, + GearUseFeaturesSeineDto.class, + new String[]{ + TripSeineGearUseDto.PROPERTY_ID, + TripSeineGearUseDto.PROPERTY_GEAR_USE_FEATURES_SEINE, + TripSeineGearUseDto.PROPERTY_LAST_UPDATE_DATE, + }, + new String[]{ + GearUseFeaturesSeineDto.PROPERTY_ID, + GearUseFeaturesSeineDto.PROPERTY_NUMBER, + GearUseFeaturesSeineDto.PROPERTY_USED_IN_TRIP, + GearUseFeaturesSeineDto.PROPERTY_GEAR_USE_FEATURES_MEASUREMENT, + GearUseFeaturesSeineDto.PROPERTY_COMMENT + } + ); + + this.measurementsTableModel = new GearUseFeaturesMeasurementSeinesTableModel(); + + List<ContentTableMeta<GearUseFeaturesSeineDto>> metas = Lists.newArrayList( + ContentTableModel.newTableMeta(GearUseFeaturesSeineDto.class, GearUseFeaturesSeineDto.PROPERTY_GEAR, false), + ContentTableModel.newTableMeta(GearUseFeaturesSeineDto.class, GearUseFeaturesSeineDto.PROPERTY_NUMBER, false), + ContentTableModel.newTableMeta(GearUseFeaturesSeineDto.class, GearUseFeaturesSeineDto.PROPERTY_USED_IN_TRIP, false), + ContentTableModel.newTableMeta(GearUseFeaturesSeineDto.class, GearUseFeaturesSeineDto.PROPERTY_COMMENT, false)); + + initModel(ui, metas); + + } + + @Override + protected GearUseFeaturesSeineTableModel createTableModel( + ObserveContentTableUI<TripSeineGearUseDto, GearUseFeaturesSeineDto> ui, + List<ContentTableMeta<GearUseFeaturesSeineDto>> contentTableMetas) { + return new GearUseFeaturesSeineTableModel(ui, contentTableMetas); + } + + public GearUseFeaturesMeasurementSeinesTableModel getMeasurementsTableModel() { + return measurementsTableModel; + } + + public boolean isGeneralTabValid() { + return generalTabValid; + } + + public void setGeneralTabValid(boolean generalTabValid) { + this.generalTabValid = generalTabValid; + firePropertyChange(PROPERTY_GENERAL_TAB_VALID, null, isGeneralTabValid()); + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ModeSaisieEchantillonEnum.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ModeSaisieEchantillonEnum.java new file mode 100644 index 0000000..6c70c17 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ModeSaisieEchantillonEnum.java @@ -0,0 +1,76 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Pour définir le mode saisie d'un échantillon. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.8 + */ +public enum ModeSaisieEchantillonEnum { + /** + * Le mode de saisie par défaut. + * + * L'observateur entre un effectif et une classe de taille, il ne peut pas + * saisir le poids (celui sera déduit par calcul). + */ + byEffectif(n("observe.modeSaisieEchantillonEnum.byEffectif")), + + /** + * Le mode de saisie par individu. + * + * L'observateur saisie les poids individuel, il ne peut pas saisir + * d'effectif, l'effectif est de 1. + */ + byIndividu(n("observe.modeSaisieEchantillonEnum.byIndividu")); + + private final String i18nKey; + + ModeSaisieEchantillonEnum(String i18nKey) { + this.i18nKey = i18nKey; + } + + public static ModeSaisieEchantillonEnum valueOf(int ordinal) + throws IllegalArgumentException { + for (ModeSaisieEchantillonEnum o : values()) { + if (o.ordinal() == ordinal) { + return o; + } + } + throw new IllegalArgumentException( + "could not find a " + ModeSaisieEchantillonEnum.class.getSimpleName() + + " value for ordinal " + ordinal); + } + + public String getI18nKey() { + return i18nKey; + } + + @Override + public String toString() { + return t(i18nKey); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetCatchUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetCatchUI.jaxx new file mode 100644 index 0000000..0af177b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetCatchUI.jaxx @@ -0,0 +1,195 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + + +<fr.ird.observe.application.swing.ui.content.table.ContentTableUI + superGenericType='SetSeineNonTargetCatchDto, NonTargetCatchDto' + contentTitle='{n("observe.common.nonTargetCatch")}' + saveNewEntryText='{n("observe.content.action.create.nonTargetCatch")}' + saveNewEntryTip='{n("observe.content.action.create.nonTargetCatch.tip")}'> + + <style source="../../CommonTable.jcss"/> + + <import> + fr.ird.observe.services.dto.CommentableDto + fr.ird.observe.services.dto.seine.SetSeineNonTargetCatchDto + fr.ird.observe.services.dto.seine.NonTargetCatchDto + fr.ird.observe.services.dto.referential.seine.SpeciesFateDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.SpeciesDto + fr.ird.observe.services.dto.referential.seine.ReasonForDiscardDto + fr.ird.observe.application.swing.ui.content.table.* + fr.ird.observe.application.swing.validation.ObserveSwingValidator + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + java.awt.Dimension + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <NonTargetCatchUIHandler id='handler' constructorParams='this'/> + + <!-- model --> + <NonTargetCatchUIModel id='model' constructorParams='this'/> + + <!-- edit bean --> + <SetSeineNonTargetCatchDto id='bean'/> + + <!-- table edit bean --> + <NonTargetCatchDto id='tableEditBean'/> + + <!-- table model --> + <ContentTableModel id='tableModel'/> + + <!-- le validateur de l'écran --> + + <BeanValidator id='validator' + beanClass='fr.ird.observe.services.dto.seine.SetSeineNonTargetCatchDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update'> + <!-- clef unique --> + <field name="nonTargetCatch" component="editorPanel"/> + </BeanValidator> + + <!-- le validateur d'une entrée de tableau --> + <BeanValidator id='validatorTable' + autoField='true' + beanClass='fr.ird.observe.services.dto.seine.NonTargetCatchDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update'/> + + <Table id='editorPanel' fill='both' insets='1' + onFocusGained='species.requestFocus()'> + + <!-- species faune --> + <row> + <cell> + <JLabel id='speciesLabel'/> + </cell> + <cell weightx='1' anchor='east' columns="2"> + <BeanComboBox id='species' constructorParams='this' genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class'/> + </cell> + </row> + + <!-- objectFate faune --> + <row> + <cell> + <JLabel id='speciesFateLabel'/> + </cell> + <cell weightx='1' anchor='east' columns="2"> + <BeanComboBox id='speciesFate' constructorParams='this' genericType='ReferentialReference<SpeciesFateDto>' _entityClass='SpeciesFateDto.class'/> + </cell> + </row> + + <!-- raison rejet --> + <row> + <cell> + <JLabel id='reasonForDiscardLabel'/> + </cell> + <cell weightx='1' anchor='east' columns="2"> + <BeanComboBox id='reasonForDiscard' constructorParams='this' genericType='ReferentialReference<ReasonForDiscardDto>' _entityClass='ReasonForDiscardDto.class'/> + </cell> + </row> + + <!-- weight estime --> + <row> + <cell> + <JLabel id='catchWeightLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='catchWeight' constructorParams='this'/> + </cell> + <cell anchor='east'> + <JToolBar id='catchWeightComputedAction'> + <JButton id='catchWeightComputedInformation' + onActionPerformed='getHandler().resetCatchWeightComputed()'/> + </JToolBar> + </cell> + </row> + + <!-- count estime --> + <row> + <cell> + <JLabel id='totalCountLabel'/> + </cell> + <cell weightx='1'> + <NumberEditor id='totalCount' constructorParams='this'/> + + </cell> + <cell anchor='east'> + <JToolBar id='totalCountComputedAction'> + <JButton id='totalCountComputedInformation' + onActionPerformed='getHandler().resetTotalCountComputed()'/> + </JToolBar> + </cell> + </row> + + <!-- weight moyen --> + <row> + <cell> + <JLabel id='meanWeightLabel'/> + </cell> + <cell weightx='1'> + <NumberEditor id='meanWeight' constructorParams='this'/> + </cell> + <cell anchor='east'> + <JToolBar id='meanWeightComputedAction'> + <JButton id='meanWeightComputedInformation' + onActionPerformed='getHandler().resetMeanWeightComputed()'/> + </JToolBar> + </cell> + </row> + + <!-- taille moyenne --> + <row> + <cell> + <JLabel id='meanLengthLabel'/> + </cell> + <cell weightx='1'> + <NumberEditor id='meanLength' constructorParams='this'/> + </cell> + <cell anchor='east'> + <JToolBar id='meanLengthComputedAction'> + <JButton id='meanLengthComputedInformation' + onActionPerformed='getHandler().resetMeanLengthComputed()'/> + </JToolBar> + </cell> + </row> + + <!-- comment --> + <row> + <cell columns='3' weighty='1'> + <JScrollPane id='comment' + onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2' + onKeyReleased='getTableEditBean().setComment(((JTextArea) event.getSource()).getText())'/> + </JScrollPane> + </cell> + </row> + + </Table> + +</fr.ird.observe.application.swing.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetCatchUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetCatchUI.jcss new file mode 100644 index 0000000..b8485a8 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetCatchUI.jcss @@ -0,0 +1,139 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#tableModel{ + deleteExtraMessage:{t("observe.content.nonTargetCatch.table.deleteExtraMessage")}; +} + +#speciesLabel { + text:"observe.common.speciesFaune"; + labelFor:{species}; +} + +#species { + property:{NonTargetCatchDto.PROPERTY_SPECIES}; + selectedItem:{tableEditBean.getSpecies()}; +} + +#speciesFateLabel { + text:"observe.common.speciesFate"; + labelFor:{speciesFate}; +} + +#speciesFate { + property:{NonTargetCatchDto.PROPERTY_SPECIES_FATE}; + selectedItem:{tableEditBean.getSpeciesFate()}; +} + +#reasonForDiscardLabel { + text:"observe.common.reasonForDiscard"; + labelFor:{reasonForDiscard}; +} + +#reasonForDiscard { + property:{NonTargetCatchDto.PROPERTY_REASON_FOR_DISCARD}; + selectedItem:{tableEditBean.getReasonForDiscard()}; +} + +#catchWeightLabel { + text:"observe.common.catchWeight"; + labelFor:{catchWeight}; +} + +#catchWeight { + property:{NonTargetCatchDto.PROPERTY_CATCH_WEIGHT}; + useFloat:true; + model:{tableEditBean.getCatchWeight()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL3_PATTERN}; +} + +#catchWeightComputedInformation { + disabledIcon: {iconDataObserve}; + icon: {iconDataCalcule}; + enabled: {tableEditBean.getCatchWeightComputedSource() != null}; + toolTipText:{getHandler().getCatchWeightDataTip(tableEditBean.getCatchWeightComputedSource())}; +} + +#totalCountLabel { + text:"observe.common.totalCount"; + labelFor:{totalCount}; +} + +#totalCount { + property:{NonTargetCatchDto.PROPERTY_TOTAL_COUNT}; + model:{tableEditBean.getTotalCount()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; +} + +#totalCountComputedInformation { + disabledIcon: {iconDataObserve}; + icon: {iconDataCalcule}; + enabled: {tableEditBean.getTotalCountComputedSource() != null}; + toolTipText:{getHandler().getTotalCountDataTip(tableEditBean.getTotalCountComputedSource())}; +} + +#meanWeightLabel { + text:"observe.common.meanWeight"; + labelFor:{meanWeight}; +} + +#meanWeight { + property:{NonTargetCatchDto.PROPERTY_MEAN_WEIGHT}; + model:{tableEditBean.getMeanWeight()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL2_PATTERN}; +} + +#meanWeightComputedInformation { + disabledIcon: {iconDataObserve}; + icon: {iconDataCalcule}; + enabled: {tableEditBean.getMeanWeightComputedSource() != null}; + toolTipText:{getHandler().getMeanWeightDataTip(tableEditBean.getMeanWeightComputedSource())}; +} + +#meanLengthLabel { + text:"observe.common.meanLength"; + labelFor:{meanLength}; +} + +#meanLength { + property:{NonTargetCatchDto.PROPERTY_MEAN_LENGTH}; + model:{tableEditBean.getMeanLength()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; +} + +#meanLengthComputedInformation { + disabledIcon: {iconDataObserve}; + icon: {iconDataCalcule}; + enabled: {tableEditBean.getMeanLengthComputedSource() != null}; + /*icon:{getDataIcon(tableEditBean.getMeanLengthComputedSource() != null)};*/ + toolTipText:{getHandler().getMeanLengthDataTip(tableEditBean.getMeanLengthComputedSource())}; +} + +#comment { + columnHeaderView:{new JLabel(t("observe.common.comment.nonTargetCatch"))}; + minimumSize:{new Dimension(10,80)}; +} + +#comment2 { + text:{getStringValue(tableEditBean.getComment())}; +} + diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetCatchUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetCatchUIHandler.java new file mode 100644 index 0000000..7046510 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetCatchUIHandler.java @@ -0,0 +1,403 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.constants.seine.NonTargetCatchComputedValueSource; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.ReferentialReferences; +import fr.ird.observe.services.dto.referential.SpeciesDto; +import fr.ird.observe.services.dto.referential.seine.ReasonForDiscardDto; +import fr.ird.observe.services.dto.referential.seine.SpeciesFateDto; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.dto.seine.NonTargetCatchDto; +import fr.ird.observe.services.dto.seine.NonTargetCatchDtos; +import fr.ird.observe.services.dto.seine.SetSeineNonTargetCatchDto; +import fr.ird.observe.services.dto.seine.SetSeineNonTargetCatchDtos; +import fr.ird.observe.services.service.seine.NonTargetCatchService; +import fr.ird.observe.services.service.seine.TripSeineService; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JComponent; +import javax.swing.JOptionPane; +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; +import java.beans.PropertyChangeListener; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class NonTargetCatchUIHandler extends ContentTableUIHandler<SetSeineNonTargetCatchDto, NonTargetCatchDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(NonTargetCatchUIHandler.class); + + /** + * Ecoute les modifications de la propriété {@link NonTargetCatchDto#getTotalCount()}, + * et repasser alors le flag {@link NonTargetCatchDto#getTotalCountComputedSource()} à + * {@code null}. + * + * @since 3.0 + */ + protected final PropertyChangeListener totalCountChanged; + + /** + * Ecoute les modifications de la propriété {@link NonTargetCatchDto#getCatchWeight()}, + * et repasser alors le flag {@link NonTargetCatchDto#getCatchWeightComputedSource()} à + * {@code null}. + * + * @since 3.0 + */ + protected final PropertyChangeListener catchWeightChanged; + + /** + * Ecoute les modifications de la propriété {@link NonTargetCatchDto#getMeanWeight()}, + * et repasser alors le flag {@link NonTargetCatchDto#getMeanWeightComputedSource()} à + * {@code null}. + * + * @since 3.0 + */ + protected final PropertyChangeListener meanWeightChanged; + + /** + * Ecoute les modifications de la propriété {@link NonTargetCatchDto#getMeanLength()}, + * et repasser alors le flag {@link NonTargetCatchDto#getMeanLengthComputedSource()} à + * {@code null}. + * + * @since 3.0 + */ + protected final PropertyChangeListener meanLengthChanged; + + public NonTargetCatchUIHandler(NonTargetCatchUI ui) { + super(ui, DataContextType.SetSeine); + totalCountChanged = evt -> { + NonTargetCatchDto source = (NonTargetCatchDto) evt.getSource(); + source.setTotalCountComputedSource(null); + }; + catchWeightChanged = evt -> { + NonTargetCatchDto source = (NonTargetCatchDto) evt.getSource(); + source.setCatchWeightComputedSource(null); + }; + meanWeightChanged = evt -> { + NonTargetCatchDto source = (NonTargetCatchDto) evt.getSource(); + source.setMeanWeightComputedSource(null); + }; + meanLengthChanged = evt -> { + NonTargetCatchDto source = (NonTargetCatchDto) evt.getSource(); + source.setMeanLengthComputedSource(null); + }; + } + + @Override + public NonTargetCatchUI getUi() { + return (NonTargetCatchUI) super.getUi(); + } + + public String getCatchWeightDataTip(NonTargetCatchComputedValueSource computed) { + String result; + + if (computed == null) { + result = t("observe.common.catchWeightComputed.observed.tip"); + } else { + result = t("observe.common.catchWeightComputed.computed.tip", computed.toString()); + } + return result; + } + + public String getTotalCountDataTip(NonTargetCatchComputedValueSource computed) { + String result; + + if (computed == null) { + result = t("observe.common.totalCountComputed.observed.tip"); + } else { + result = t("observe.common.totalCountComputed.computed.tip", computed.toString()); + + } + return result; + } + + public String getMeanWeightDataTip(NonTargetCatchComputedValueSource computed) { + String result; + + if (computed == null) { + result = t("observe.common.meanWeightComputed.observed.tip"); + } else { + result = t("observe.common.meanWeightComputed.computed.tip", computed.toString()); + } + return result; + } + + public String getMeanLengthDataTip(NonTargetCatchComputedValueSource computed) { + String result; + + if (computed == null) { + result = t("observe.common.meanLengthComputed.observed.tip"); + } else { + result = t("observe.common.meanLengthComputed.computed.tip", computed.toString()); + } + return result; + } + + public void resetCatchWeightComputed() { + getTableEditBean().setCatchWeightComputedSource(null); + getUi().getCatchWeight().grabFocus(); + } + + public void resetTotalCountComputed() { + getTableEditBean().setTotalCountComputedSource(null); + getUi().getTotalCount().grabFocus(); + } + + public void resetMeanWeightComputed() { + getTableEditBean().setMeanWeightComputedSource(null); + getUi().getMeanWeight().grabFocus(); + } + + public void resetMeanLengthComputed() { + getTableEditBean().setMeanLengthComputedSource(null); + getUi().getMeanLength().grabFocus(); + } + + @Override + protected String getEditBeanIdToLoad() { + return getDataContext().getSelectedSetId(); + } + + @Override + protected void onSelectedRowChanged(int editingRow, NonTargetCatchDto bean, boolean create) { + NonTargetCatchUI ui = getUi(); + + ContentTableModel<SetSeineNonTargetCatchDto, NonTargetCatchDto> model = getTableModel(); + + if (!model.isEditable()) { + + // rien a faire + return; + } + + List<ReferentialReference<SpeciesDto>> availableEspeces; + JComponent requestFocus; + + if (create) { + Set<ReferentialReference<SpeciesDto>> speciesSet = getModel().getReferentialReferences(NonTargetCatchDto.PROPERTY_SPECIES); + availableEspeces = Lists.newArrayList(speciesSet); + + requestFocus = ui.getSpecies(); + } else { + ReferentialReference<SpeciesDto> species = bean.getSpecies(); + availableEspeces = new ArrayList<>(); + availableEspeces.add(species); + requestFocus = ui.getTable(); + } + + ui.getSpecies().setData(availableEspeces); + requestFocus.requestFocus(); + + NonTargetCatchDto tableEditBean = getTableEditBean(); + tableEditBean.removePropertyChangeListener(NonTargetCatchDto.PROPERTY_TOTAL_COUNT, totalCountChanged); + tableEditBean.addPropertyChangeListener(NonTargetCatchDto.PROPERTY_TOTAL_COUNT, totalCountChanged); + + tableEditBean.removePropertyChangeListener(NonTargetCatchDto.PROPERTY_CATCH_WEIGHT, catchWeightChanged); + tableEditBean.addPropertyChangeListener(NonTargetCatchDto.PROPERTY_CATCH_WEIGHT, catchWeightChanged); + + tableEditBean.removePropertyChangeListener(NonTargetCatchDto.PROPERTY_MEAN_WEIGHT, meanWeightChanged); + tableEditBean.addPropertyChangeListener(NonTargetCatchDto.PROPERTY_MEAN_WEIGHT, meanWeightChanged); + + tableEditBean.removePropertyChangeListener(NonTargetCatchDto.PROPERTY_MEAN_LENGTH, meanLengthChanged); + tableEditBean.addPropertyChangeListener(NonTargetCatchDto.PROPERTY_MEAN_LENGTH, meanLengthChanged); + } + + @Override + protected void initTableUI(DefaultTableCellRenderer renderer) { + + JTable table = getUi().getTable(); + + UIHelper.fixTableColumnWidth(table, 3, 55); + UIHelper.fixTableColumnWidth(table, 4, 65); + UIHelper.fixTableColumnWidth(table, 5, 75); + UIHelper.fixTableColumnWidth(table, 6, 55); + UIHelper.fixTableColumnWidth(table, 7, 50); + + UIHelper.setI18nTableHeaderRenderer( + table, + n("observe.content.nonTargetCatch.table.speciesFaune"), + n("observe.content.nonTargetCatch.table.speciesFaune.tip"), + n("observe.content.nonTargetCatch.table.speciesFate"), + n("observe.content.nonTargetCatch.table.speciesFate.tip"), + n("observe.content.nonTargetCatch.table.reasonForDiscard"), + n("observe.content.nonTargetCatch.table.reasonForDiscard.tip"), + n("observe.content.nonTargetCatch.table.catchWeight"), + n("observe.content.nonTargetCatch.table.catchWeight.tip"), + n("observe.content.nonTargetCatch.table.totalCount"), + n("observe.content.nonTargetCatch.table.totalCount.tip"), + n("observe.content.nonTargetCatch.table.meanWeight"), + n("observe.content.nonTargetCatch.table.meanWeight.tip"), + n("observe.content.nonTargetCatch.table.meanLength"), + n("observe.content.nonTargetCatch.table.meanLength.tip"), + n("observe.content.nonTargetCatch.table.comment"), + n("observe.content.nonTargetCatch.table.comment.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesDto.class)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesFateDto.class)); + UIHelper.setTableColumnRenderer(table, 2, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, ReasonForDiscardDto.class)); + UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 4, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 5, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 6, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 7, UIHelper.newStringTableCellRenderer(renderer, 10, true)); + } + + @SuppressWarnings("Duplicates") + @Override + protected boolean prepareSave(SetSeineNonTargetCatchDto editBean, List<NonTargetCatchDto> objets) throws Exception { + super.prepareSave(editBean, objets); + + //on cherche si parmis les captures supprimer certaines ont des échantillon + SetSeineNonTargetCatchDto originalSetSeineNonTargetCatchDto = getModel().getForm().getObject(); + + Set<ReferentialReference<SpeciesDto>> speciesToDelete = Sets.newHashSet(); + + for (NonTargetCatchDto nonTargetCatchDto : originalSetSeineNonTargetCatchDto.getNonTargetCatch()) { + + if (nonTargetCatchDto.isHasSample()) { + + ReferentialReference<SpeciesDto> species = nonTargetCatchDto.getSpecies(); + + Iterable<NonTargetCatchDto> currentTargetCatchSpecies = NonTargetCatchDtos.filterBySpecies(objets, species); + + if (Iterables.isEmpty(currentTargetCatchSpecies)) { + + speciesToDelete.add(species); + + } + } + + } + + if (!speciesToDelete.isEmpty()) { + + // il existe des echantillon faune a supprimer on demande une + // confirmation + StringBuilder sb = new StringBuilder(512); + ReferentialReferenceDecorator<SpeciesDto> decorator = + getDecoratorService().getReferentialReferenceDecorator(SpeciesDto.class); + + for (ReferentialReference<SpeciesDto> species : speciesToDelete) { + sb.append(" - ").append(decorator.toString(species)).append('\n'); + } + int reponse = UIHelper.askUser( + t("observe.title.need.confirm"), + t("observe.content.nonTargetCatch.message.table.will.delete.nonTargetSample", sb.toString()), + JOptionPane.ERROR_MESSAGE, + new Object[]{ + t("observe.choice.continue"), + t("observe.choice.cancel")}, + 0); + if (log.isDebugEnabled()) { + log.debug("response : " + reponse); + } + boolean canContinue = false; + switch (reponse) { + case 0: + // wil reset ui + canContinue = true; + break; + } + if (!canContinue) { + // l'utilisateur a choisi de ne pas continuer + return false; + } + } + + return true; + } + + @Override + protected void doPersist(SetSeineNonTargetCatchDto bean) { + + SaveResultDto saveResult = getNonTargetCatchService().save(bean); + saveResult.toDto(bean); + + } + + @Override + protected void loadEditBean(String beanId) { + Form<SetSeineNonTargetCatchDto> form = getNonTargetCatchService().loadForm(beanId); + loadReferentialReferenceSetsInModel(form); + getModel().setForm(form); + SetSeineNonTargetCatchDtos.copySetSeineNonTargetCatchDto(form.getObject(), getBean()); + } + + @Override + protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { + + Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); + + switch (propertyName) { + + case NonTargetCatchDto.PROPERTY_SPECIES: { + + String speciesListId = ObserveSwingApplicationContext.get().getConfig().getSpeciesListSeineNonTargetCatchId(); + String tripSeineId = getDataContext().getSelectedTripSeineId(); + + TripSeineService tripSeineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripSeineService(); + result = (List) tripSeineService.getSpeciesByListAndTrip(tripSeineId, speciesListId); + + result = ReferentialReferences.filterEnabled(result); + + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + } + + break; + + } + + return result; + + } + + protected NonTargetCatchService getNonTargetCatchService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newNonTargetCatchService(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetCatchUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetCatchUIModel.java new file mode 100644 index 0000000..59aebc7 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetCatchUIModel.java @@ -0,0 +1,105 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import fr.ird.observe.services.dto.seine.NonTargetCatchDto; +import fr.ird.observe.services.dto.seine.NonTargetCatchDtos; +import fr.ird.observe.services.dto.seine.SetSeineNonTargetCatchDto; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; + +import java.util.Collection; +import java.util.List; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class NonTargetCatchUIModel extends ContentTableUIModel<SetSeineNonTargetCatchDto, NonTargetCatchDto> { + + private static final long serialVersionUID = 1L; + + public NonTargetCatchUIModel(NonTargetCatchUI ui) { + super(SetSeineNonTargetCatchDto.class, + NonTargetCatchDto.class, + new String[]{ + SetSeineNonTargetCatchDto.PROPERTY_NON_TARGET_CATCH}, + new String[]{ + NonTargetCatchDto.PROPERTY_SPECIES, + NonTargetCatchDto.PROPERTY_CATCH_WEIGHT, + NonTargetCatchDto.PROPERTY_TOTAL_COUNT, + NonTargetCatchDto.PROPERTY_MEAN_WEIGHT, + NonTargetCatchDto.PROPERTY_MEAN_LENGTH, + NonTargetCatchDto.PROPERTY_REASON_FOR_DISCARD, + NonTargetCatchDto.PROPERTY_SPECIES_FATE, + NonTargetCatchDto.PROPERTY_TOTAL_COUNT_COMPUTED_SOURCE, + NonTargetCatchDto.PROPERTY_MEAN_WEIGHT_COMPUTED_SOURCE, + NonTargetCatchDto.PROPERTY_CATCH_WEIGHT_COMPUTED_SOURCE, + NonTargetCatchDto.PROPERTY_MEAN_LENGTH_COMPUTED_SOURCE, + NonTargetCatchDto.PROPERTY_COMMENT + }); + + List<ContentTableMeta<NonTargetCatchDto>> metas = Lists.newArrayList( + ContentTableModel.newTableMeta(NonTargetCatchDto.class, NonTargetCatchDto.PROPERTY_SPECIES, false), + ContentTableModel.newTableMeta(NonTargetCatchDto.class, NonTargetCatchDto.PROPERTY_SPECIES_FATE, false), + ContentTableModel.newTableMeta(NonTargetCatchDto.class, NonTargetCatchDto.PROPERTY_REASON_FOR_DISCARD, false), + ContentTableModel.newTableMeta(NonTargetCatchDto.class, NonTargetCatchDto.PROPERTY_CATCH_WEIGHT, false), + ContentTableModel.newTableMeta(NonTargetCatchDto.class, NonTargetCatchDto.PROPERTY_TOTAL_COUNT, false), + ContentTableModel.newTableMeta(NonTargetCatchDto.class, NonTargetCatchDto.PROPERTY_MEAN_WEIGHT, false), + ContentTableModel.newTableMeta(NonTargetCatchDto.class, NonTargetCatchDto.PROPERTY_MEAN_LENGTH, false), + ContentTableModel.newTableMeta(NonTargetCatchDto.class, NonTargetCatchDto.PROPERTY_COMMENT, false)); + + initModel(ui, metas); + + } + + @Override + protected ContentTableModel<SetSeineNonTargetCatchDto, NonTargetCatchDto> createTableModel( + ObserveContentTableUI<SetSeineNonTargetCatchDto, NonTargetCatchDto> ui, + List<ContentTableMeta<NonTargetCatchDto>> contentTableMetas) { + + return new ContentTableModel<SetSeineNonTargetCatchDto, NonTargetCatchDto>(ui, contentTableMetas) { + private static final long serialVersionUID = 1L; + + @Override + protected Collection<NonTargetCatchDto> getChilds(SetSeineNonTargetCatchDto bean) { + return bean.getNonTargetCatch(); + } + + @Override + protected void load(NonTargetCatchDto source, NonTargetCatchDto target) { + NonTargetCatchDtos.copyNonTargetCatchDto(source, target); + } + + @Override + protected void setChilds(SetSeineNonTargetCatchDto parent, List<NonTargetCatchDto> childs) { + bean.setNonTargetCatch(childs); + } + }; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetSampleUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetSampleUI.jaxx new file mode 100644 index 0000000..179bb09 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetSampleUI.jaxx @@ -0,0 +1,221 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.table.ContentTableUI + superGenericType='NonTargetSampleDto, NonTargetLengthDto' + contentTitle='{n("observe.common.nonTargetSample")}' + saveNewEntryText='{n("observe.content.action.create.nonTargetSample")}' + saveNewEntryTip='{n("observe.content.action.create.nonTargetSample.tip")}'> + + <style source="../../CommonTable.jcss"/> + <style source="AbstractSampleUI.jcss"/> + + <import> + fr.ird.observe.services.dto.CommentableDto + fr.ird.observe.services.dto.referential.SexDto + fr.ird.observe.services.dto.referential.SpeciesDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.seine.NonTargetLengthDto + fr.ird.observe.services.dto.seine.NonTargetSampleDto + fr.ird.observe.application.swing.ui.content.table.impl.seine.ModeSaisieEchantillonEnum + fr.ird.observe.application.swing.ui.content.table.* + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + java.awt.Dimension + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <NonTargetSampleUIHandler id='handler' constructorParams='this'/> + + <!-- model --> + <NonTargetSampleUIModel id='model' constructorParams='this'/> + + <!-- edit bean --> + <NonTargetSampleDto id='bean'/> + + <!-- table edit bean --> + <NonTargetLengthDto id='tableEditBean'/> + + <!-- table model --> + <ContentTableModel id='tableModel'/> + + <!-- le validateur de l'écran --> + <BeanValidator id='validator' + beanClass='fr.ird.observe.services.dto.seine.NonTargetSampleDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update'> + <field name='comment'/> + </BeanValidator> + + <!-- le validateur d'une entrée de tableau --> + <BeanValidator id='validatorTable' + autoField='true' + beanClass='fr.ird.observe.services.dto.seine.NonTargetLengthDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update'> + </BeanValidator> + + <ButtonGroup id='acquisitionModeGroup' + onStateChanged='getHandler().updateModeSaisie((ModeSaisieEchantillonEnum) acquisitionModeGroup.getSelectedValue())'/> + + <script><![CDATA[ + +public static final String POIDS_COMPUTED_TIP = n("observe.common.weight.computed.tip"); +public static final String POIDS_OBSERVED_TIP = n("observe.common.weight.observed.tip"); +public static final String LONGUEUR_COMPUTED_TIP = n("observe.common.length.computed.tip"); +public static final String LONGUEUR_OBSERVED_TIP = n("observe.common.length.observed.tip"); + +public String getWeightDataTip(boolean computed) { + return computed ? t(POIDS_COMPUTED_TIP) : t(POIDS_OBSERVED_TIP); +} + +public String getLengthDataTip(boolean computed) { + return computed ? t(LONGUEUR_COMPUTED_TIP) : t(LONGUEUR_OBSERVED_TIP); +} + +public String getSpeciesFauneTypeTaille(ReferentialReference<SpeciesDto> species) { + return species == null ? t("observe.message.no.species.selected") : (String) species.getPropertyValue(SpeciesDto.PROPERTY_LENGTH_MEASURE_TYPE); +} +]]> + </script> + + <JLabel id='hideFormInformation'/> + + <Table id='editorPanel' fill='both' insets='1'> + + <!-- mode de saisie --> + <row> + <cell columns="2"> + <JPanel id='acquisitionModePanel'> + <JRadioButton id='acquisitionModeEffectif'/> + <JRadioButton id='acquisitionModeIndividu'/> + </JPanel> + </cell> + </row> + + <!-- species faune --> + <row> + <cell> + <JLabel id='speciesLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='species' constructorParams='this' genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class'/> + </cell> + </row> + + <!-- species faune (type taille) --> + <row> + <cell> + <JLabel id='speciesTypeTailleLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <JLabel id='speciesTypeTaille'/> + </cell> + </row> + + <!-- length --> + <row> + <cell> + <JLabel id='lengthLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='length' constructorParams='this'/> + </cell> + <cell anchor='east'> + <JToolBar id='lengthSourceAction'> + <JButton id='lengthSourceInformation' + onActionPerformed='getHandler().resetLengthSource()'/> + </JToolBar> + </cell> + </row> + + <!-- weight individuel --> + <row> + <cell> + <JLabel id='weightLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='weight' constructorParams='this'/> + </cell> + <cell anchor='east'> + <JToolBar id='weightSourceAction'> + <JButton id='weightSourceInformation' + onActionPerformed='getHandler().resetWeightSource()'/> + </JToolBar> + </cell> + </row> + + <!-- count --> + <row> + <cell> + <JLabel id='countLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='count' constructorParams='this'/> + </cell> + </row> + + <!-- sex --> + <row> + <cell> + <JLabel id='sexLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='sex' genericType='ReferentialReference<SexDto>' _entityClass='SexDto.class' constructorParams='this'/> + </cell> + </row> + + <!-- reference pĥoto --> + <row> + <cell> + <JLabel id='picturesReferencesLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <JPanel layout='{new BorderLayout()}'> + <JToolBar id='picturesReferencesToolbar' constraints='BorderLayout.WEST'> + <JButton id='resetPicturesReferences' styleClass='resetButton'/> + </JToolBar> + <JTextField id='picturesReferences' constraints='BorderLayout.CENTER'/> + </JPanel> + </cell> + </row> + + </Table> + + <Table id='extraZone' fill='both' weightx='1' insets='0'> + <row> + <cell weighty='1'> + <JScrollPane id='comment' + onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2' + onKeyReleased='getBean().setComment(comment2.getText())'/> + </JScrollPane> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetSampleUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetSampleUI.jcss new file mode 100644 index 0000000..561888a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetSampleUI.jcss @@ -0,0 +1,113 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#speciesLabel { + text:"observe.common.speciesFaune"; +} + +#acquisitionModeGroup { + selectedValue:{ModeSaisieEchantillonEnum.valueOf(tableEditBean.getAcquisitionMode())}; +} + +#acquisitionModePanel { + border:{new TitledBorder(t("observe.common.acquisitionMode"))}; + layout:{new GridLayout(1,0)}; +} + +#acquisitionModeEffectif { + buttonGroup:"acquisitionModeGroup"; + value:{ModeSaisieEchantillonEnum.byEffectif}; + text:{ModeSaisieEchantillonEnum.byEffectif.getI18nKey()}; + selected:{tableEditBean.getAcquisitionMode() == 0}; + enabled:{!tableModel.isEditable() || tableModel.isCreate()}; +} + +#acquisitionModeIndividu { + buttonGroup:"acquisitionModeGroup"; + value:{ModeSaisieEchantillonEnum.byIndividu}; + text:{ModeSaisieEchantillonEnum.byIndividu.getI18nKey()}; + selected:{tableEditBean.getAcquisitionMode() == 1}; + enabled:{!tableModel.isEditable() || tableModel.isCreate()}; +} + +#lengthLabel { + text:"observe.common.taille"; +} + +#length { + _validatorLabel:{"observe.common.taille"}; +} + +#countLabel { + text:"observe.common.count"; + labelFor:{count}; +} + +#count { + property:{NonTargetLengthDto.PROPERTY_COUNT}; + model:{tableEditBean.getCount()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; +} + +#sexLabel { + text:"observe.common.sex"; + labelFor:{sex}; +} + +#sex { + property:{NonTargetLengthDto.PROPERTY_SEX}; + selectedItem:{tableEditBean.getSex()}; +} + +#picturesReferencesLabel { + text:"observe.common.picturesReferences"; + labelFor:{picturesReferences}; +} + +#picturesReferences { + text:{getStringValue(tableEditBean.getPicturesReferences())}; + _tablePropertyName:{NonTargetLengthDto.PROPERTY_PICTURES_REFERENCES}; +} + +#resetPicturesReferences{ + toolTipText:"observe.content.action.reset.picturesReferences.tip"; + _resetTablePropertyName:{NonTargetLengthDto.PROPERTY_PICTURES_REFERENCES}; +} + +#speciesTypeTailleLabel{ + actionIcon:"information"; + text:"observe.common.lengthMeasureType"; + labelFor:{speciesTypeTaille}; +} + +#speciesTypeTaille { + font-weight:"bold"; + text:{getSpeciesFauneTypeTaille(tableEditBean.getSpecies())}; +} + +#comment { + columnHeaderView:{new JLabel(t("observe.common.comment.nonTargetSample"))}; +} + +#hideFormInformation { + text:"observe.message.cant.add.nonTargetSample"; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetSampleUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetSampleUIHandler.java new file mode 100644 index 0000000..5c3ab76 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetSampleUIHandler.java @@ -0,0 +1,336 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +import com.google.common.collect.Lists; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.SexDto; +import fr.ird.observe.services.dto.referential.SpeciesDto; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.dto.seine.NonTargetLengthDto; +import fr.ird.observe.services.dto.seine.NonTargetSampleDto; +import fr.ird.observe.services.dto.seine.NonTargetSampleDtos; +import fr.ird.observe.services.dto.seine.SetSeineDto; +import fr.ird.observe.services.service.seine.NonTargetSampleService; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.JComponent; +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; +import java.beans.PropertyChangeListener; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class NonTargetSampleUIHandler extends ContentTableUIHandler<NonTargetSampleDto, NonTargetLengthDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(NonTargetSampleUIHandler.class); + + /** + * Ecoute les modifications de la propriété {@link NonTargetLengthDto#getWeight()}, + * et repasser alors le flag {@link NonTargetLengthDto#isWeightSource()} à + * {@code false}. + * + * @since 3.0 + */ + protected final PropertyChangeListener weightChanged; + + /** + * Ecoute les modifications de la propriété {@link NonTargetLengthDto#getLength()}, + * et repasser alors le flag {@link NonTargetLengthDto#isLengthSource()} à + * {@code false}. + * + * @since 3.0 + */ + protected final PropertyChangeListener lengthChanged; + + public NonTargetSampleUIHandler(NonTargetSampleUI ui) { + super(ui, DataContextType.SetSeine); + weightChanged = evt -> { + NonTargetLengthDto source = (NonTargetLengthDto) evt.getSource(); + source.setWeightSource(false); + }; + lengthChanged = evt -> { + NonTargetLengthDto source = (NonTargetLengthDto) evt.getSource(); + source.setLengthSource(false); + }; + } + + @Override + public NonTargetSampleUI getUi() { + return (NonTargetSampleUI) super.getUi(); + } + + public void resetWeightSource() { + getTableEditBean().setWeightSource(false); + getUi().getWeight().grabFocus(); + } + + public void resetLengthSource() { + getTableEditBean().setLengthSource(false); + getUi().getLength().grabFocus(); + } + + @Override + protected String getEditBeanIdToLoad() { + String id = getDataContext().getSelectedSetId(); + return id; + } + + @SuppressWarnings("unchecked") + @Override + protected void onSelectedRowChanged(int editingRow, + NonTargetLengthDto bean, + boolean create) { + ContentTableModel<NonTargetSampleDto, NonTargetLengthDto> model = getTableModel(); + + if (!model.isEditable()) { + return; + } + + ReferentialReference<SpeciesDto> species = bean.getSpecies(); + NonTargetSampleUI ui = getUi(); + if (log.isDebugEnabled()) { + log.debug("selected species " + species); + } + List<ReferentialReference<SpeciesDto>> availableEspeces; + JComponent requestFocus; + + if (create) { + + if (model.isCreate()) { + + // on passe le mode de saisie en count + ui.getAcquisitionModeGroup().setSelectedValue(null); + ui.getAcquisitionModeGroup().setSelectedValue(ModeSaisieEchantillonEnum.byEffectif); + } + + Set<ReferentialReference<SpeciesDto>> speciesReferences = getModel().getReferentialReferences(NonTargetLengthDto.PROPERTY_SPECIES); + + availableEspeces = Lists.newArrayList(speciesReferences); + requestFocus = ui.getSpecies(); + } else { + + requestFocus = ui.getCount(); + + // on passe le mode de saisie + int acquisitionMode = bean.getAcquisitionMode(); + ModeSaisieEchantillonEnum enumValue = + ModeSaisieEchantillonEnum.valueOf(acquisitionMode); + ui.getAcquisitionModeGroup().setSelectedValue(null); + ui.getAcquisitionModeGroup().setSelectedValue(enumValue); + + availableEspeces = Lists.newArrayList(species); + } + ui.getSpecies().setData(availableEspeces); + requestFocus.requestFocus(); + + NonTargetLengthDto tableEditBean = getTableEditBean(); + tableEditBean.removePropertyChangeListener(NonTargetLengthDto.PROPERTY_WEIGHT, weightChanged); + tableEditBean.addPropertyChangeListener(NonTargetLengthDto.PROPERTY_WEIGHT, weightChanged); + + tableEditBean.removePropertyChangeListener(NonTargetLengthDto.PROPERTY_LENGTH, lengthChanged); + tableEditBean.addPropertyChangeListener(NonTargetLengthDto.PROPERTY_LENGTH, lengthChanged); + } + + @Override + protected void initTableUI(DefaultTableCellRenderer renderer) { + JTable table = getUi().getTable(); + + UIHelper.fixTableColumnWidth(table, 1, 100); + UIHelper.fixTableColumnWidth(table, 2, 100); + + UIHelper.setI18nTableHeaderRenderer( + table, + n("observe.content.nonTargetSample.table.speciesFaune"), + n("observe.content.nonTargetSample.table.speciesFaune.tip"), + n("observe.content.nonTargetSample.table.length"), + n("observe.content.nonTargetSample.table.length.tip"), + n("observe.content.nonTargetSample.table.meanWeight"), + n("observe.content.nonTargetSample.table.meanWeight.tip"), + n("observe.content.nonTargetSample.table.count"), + n("observe.content.nonTargetSample.table.count.tip"), + n("observe.content.nonTargetSample.table.gender"), + n("observe.content.nonTargetSample.table.gender.tip"), + n("observe.content.nonTargetSample.table.picturesReferences"), + n("observe.content.nonTargetSample.table.picturesReferences.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesDto.class)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 4, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SexDto.class)); + UIHelper.setTableColumnRenderer(table, 5, renderer); + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + ContentMode mode = super.getContentMode(dataContext); + + String setId = getDataContext().getSelectedSetId(); + + boolean showData = getNonTargetSampleService().canUseNonTargetSample(setId); + + getUi().getModel().setShowData(showData); + + if (mode == ContentMode.UPDATE && !showData) { + + // on repasse en mode resteint car on ne peut pas éditer l'écran + mode = ContentMode.READ; + + addMessage(getUi(), + NuitonValidatorScope.INFO, + getEntityLabel(SetSeineDto.class), + t("observe.content.setSeine.message.no.nonTargetDiscarded")); + } + return mode; + } + + /** + * Le mode de saisie a été mis à jour. + * + * @param newMode le nouveau de mode de saisie à utiliser + * @since 3.0 + */ + public void updateModeSaisie(ModeSaisieEchantillonEnum newMode) { + + if (log.isDebugEnabled()) { + log.debug("Change mode saisie to " + newMode); + } + if (newMode == null) { + + // mode null (cela peut arriver avec les bindings) + return; + } + + NonTargetSampleUI ui = getUi(); + + boolean createMode = ui.getTableModel().isCreate(); + + NonTargetLengthDto editBean = ui.getTableEditBean(); + switch (newMode) { + + case byEffectif: + + // le weight n'est pas modifiable + ui.getWeight().setEnabled(false); + + // l'count est modifiable + ui.getCount().setEnabled(true); + + if (createMode) { + + // on supprime le weight (si il a été saisie) + editBean.setWeight(null); + // on supprime aussi l'count (pour forcer la saisie) + editBean.setCount(null); + } + break; + + case byIndividu: + + // le weight est pas modifiable + ui.getWeight().setEnabled(true); + + // l'count n'est pas modifiable et est toujours de 1 + ui.getCount().setEnabled(false); + + + if (createMode) { + + // on positionne l'count à 1 (seule valeur possible) + editBean.setCount(1); + } + break; + } + + if (createMode) { + + // on propage le mode de saisie dans le bean + editBean.setAcquisitionMode(newMode.ordinal()); + } + } + + @Override + protected void doPersist(NonTargetSampleDto bean) { + + SaveResultDto saveResult = getNonTargetSampleService().save(getSelectedParentId(), bean); + saveResult.toDto(bean); + + } + + @Override + protected void loadEditBean(String beanId) { + Form<NonTargetSampleDto> form = getNonTargetSampleService().loadForm(beanId); + loadReferentialReferenceSetsInModel(form); + getModel().setForm(form); + NonTargetSampleDtos.copyNonTargetSampleDto(form.getObject(), getBean()); + } + + @Override + protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { + + Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); + + switch (propertyName) { + + case NonTargetLengthDto.PROPERTY_SPECIES: { + + result = (Collection) getNonTargetSampleService().getSampleSpecies(getSelectedParentId()); + + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + } + + break; + + } + + return result; + + } + + protected NonTargetSampleService getNonTargetSampleService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newNonTargetSampleService(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetSampleUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetSampleUIModel.java new file mode 100644 index 0000000..805ae7e --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/NonTargetSampleUIModel.java @@ -0,0 +1,106 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import fr.ird.observe.services.dto.seine.NonTargetLengthDto; +import fr.ird.observe.services.dto.seine.NonTargetLengthDtos; +import fr.ird.observe.services.dto.seine.NonTargetSampleDto; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; + +import java.util.Collection; +import java.util.List; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class NonTargetSampleUIModel extends ContentTableUIModel<NonTargetSampleDto, NonTargetLengthDto> { + + private static final long serialVersionUID = 1L; + + public NonTargetSampleUIModel(NonTargetSampleUI ui) { + + super(NonTargetSampleDto.class, + NonTargetLengthDto.class, + new String[]{ + NonTargetSampleDto.PROPERTY_NON_TARGET_LENGTH, + NonTargetSampleDto.PROPERTY_COMMENT}, + new String[]{NonTargetLengthDto.PROPERTY_SPECIES, + NonTargetLengthDto.PROPERTY_LENGTH, + NonTargetLengthDto.PROPERTY_LENGTH_SOURCE, + NonTargetLengthDto.PROPERTY_WEIGHT, + NonTargetLengthDto.PROPERTY_WEIGHT_SOURCE, + NonTargetLengthDto.PROPERTY_SEX, + NonTargetLengthDto.PROPERTY_COUNT, + NonTargetLengthDto.PROPERTY_ACQUISITION_MODE, + NonTargetLengthDto.PROPERTY_PICTURES_REFERENCES + }); + + List<ContentTableMeta<NonTargetLengthDto>> metas = Lists.newArrayList( + ContentTableModel.newTableMeta(NonTargetLengthDto.class, NonTargetLengthDto.PROPERTY_SPECIES, false), + ContentTableModel.newTableMeta(NonTargetLengthDto.class, NonTargetLengthDto.PROPERTY_LENGTH, false), + ContentTableModel.newTableMeta(NonTargetLengthDto.class, NonTargetLengthDto.PROPERTY_WEIGHT, false), + ContentTableModel.newTableMeta(NonTargetLengthDto.class, NonTargetLengthDto.PROPERTY_COUNT, false), + new ContentTableMeta<NonTargetLengthDto>(NonTargetLengthDto.class, NonTargetLengthDto.PROPERTY_SEX, false) { + + private static final long serialVersionUID = 1L; + + @Override + public boolean isNullValue(ContentTableModel<?, ?> m, NonTargetLengthDto bean, int row) { + return bean.getSex() != null; + } + }, + ContentTableModel.newTableMeta(NonTargetLengthDto.class, NonTargetLengthDto.PROPERTY_PICTURES_REFERENCES, false)); + + initModel(ui, metas); + + } + + @Override + protected ContentTableModel<NonTargetSampleDto, NonTargetLengthDto> createTableModel(ObserveContentTableUI<NonTargetSampleDto, NonTargetLengthDto> ui, List<ContentTableMeta<NonTargetLengthDto>> contentTableMetas) { + return new ContentTableModel<NonTargetSampleDto, NonTargetLengthDto>(ui, contentTableMetas) { + private static final long serialVersionUID = 1L; + @Override + protected Collection<NonTargetLengthDto> getChilds(NonTargetSampleDto bean) { + return bean.getNonTargetLength(); + } + + @Override + protected void load(NonTargetLengthDto source, NonTargetLengthDto target) { + NonTargetLengthDtos.copyNonTargetLengthDto(source, target); + } + + @Override + protected void setChilds(NonTargetSampleDto parent, List<NonTargetLengthDto> childs) { + parent.setNonTargetLength(Sets.newLinkedHashSet(childs)); + } + }; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectObservedSpeciesUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectObservedSpeciesUI.jaxx new file mode 100644 index 0000000..a9052ea --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectObservedSpeciesUI.jaxx @@ -0,0 +1,125 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.table.ContentTableUI + superGenericType='FloatingObjectObservedSpeciesDto, ObjectObservedSpeciesDto' + contentTitle='{n("observe.common.objectObservedSpecies")}' + saveNewEntryText='{n("observe.content.action.create.objectObservedSpecies")}' + saveNewEntryTip='{n("observe.content.action.create.objectObservedSpecies.tip")}'> + + <style source="../../CommonTable.jcss"/> + + <import> + fr.ird.observe.services.dto.CommentableDto + fr.ird.observe.services.dto.seine.FloatingObjectObservedSpeciesDto + fr.ird.observe.services.dto.seine.ObjectObservedSpeciesDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.SpeciesDto + fr.ird.observe.services.dto.referential.seine.SpeciesStatusDto + fr.ird.observe.application.swing.ui.content.table.* + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + java.awt.Dimension + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <ObjectObservedSpeciesUIHandler id='handler' constructorParams='this'/> + + <!-- model --> + <ObjectObservedSpeciesUIModel id='model' constructorParams='this'/> + + <!-- edit bean --> + <FloatingObjectObservedSpeciesDto id='bean'/> + + <!-- table edit bean --> + <ObjectObservedSpeciesDto id='tableEditBean'/> + + <!-- table model --> + <ContentTableModel id='tableModel'/> + + <!-- le validateur de l'écran --> + <BeanValidator id='validator' + autoField='true' + beanClass='fr.ird.observe.services.dto.seine.FloatingObjectObservedSpeciesDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update'/> + + <!-- le validateur d'une entrée de tableau --> + <BeanValidator id='validatorTable' + autoField='true' + beanClass='fr.ird.observe.services.dto.seine.ObjectObservedSpeciesDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update'/> + + <Table id='editorPanel' fill='both' insets='1'> + + <!-- species faune --> + <row> + <cell> + <JLabel id='speciesLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='species' constructorParams='this' + genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class'/> + </cell> + </row> + + <!-- statut species --> + <row> + <cell> + <JLabel id='speciesStatusLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='speciesStatus' constructorParams='this' + genericType='ReferentialReference<SpeciesStatusDto>' _entityClass='SpeciesStatusDto.class'/> + </cell> + </row> + + <!-- count --> + <row> + <cell> + <JLabel id='countLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='count' constructorParams='this'/> + </cell> + </row> + </Table> + + <Table id='extraZone' fill='both' weightx='1' insets='0'> + <row> + <cell weighty='1'> + <JScrollPane id='comment' + onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2' + onKeyReleased='getBean().setComment(comment2.getText())'/> + </JScrollPane> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectObservedSpeciesUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectObservedSpeciesUI.jcss new file mode 100644 index 0000000..d2ef0ae --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectObservedSpeciesUI.jcss @@ -0,0 +1,61 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#speciesLabel { + text:"observe.common.speciesFaune"; + labelFor:{species}; +} + +#species { + property:{ObjectObservedSpeciesDto.PROPERTY_SPECIES}; + selectedItem:{tableEditBean.getSpecies()}; +} + +#speciesStatusLabel { + text:"observe.common.speciesStatus"; + labelFor:{speciesStatus}; +} + +#speciesStatus { + property:{ObjectObservedSpeciesDto.PROPERTY_SPECIES_STATUS}; + selectedItem:{tableEditBean.getSpeciesStatus()}; +} + +#countLabel { + text:"observe.common.count"; + labelFor:{count}; +} + +#count { + property:{ObjectObservedSpeciesDto.PROPERTY_COUNT}; + model:{tableEditBean.getCount()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; +} + +#comment { + columnHeaderView:{new JLabel(t("observe.common.comment.floatingObject"))}; + minimumSize:{new Dimension(10,80)}; +} + +#comment2 { + text:{getStringValue(bean.getComment())}; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectObservedSpeciesUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectObservedSpeciesUIHandler.java new file mode 100644 index 0000000..2818c30 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectObservedSpeciesUIHandler.java @@ -0,0 +1,153 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.ReferentialReferences; +import fr.ird.observe.services.dto.referential.SpeciesDto; +import fr.ird.observe.services.dto.referential.SpeciesListDto; +import fr.ird.observe.services.dto.referential.seine.SpeciesStatusDto; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.dto.seine.FloatingObjectObservedSpeciesDto; +import fr.ird.observe.services.dto.seine.FloatingObjectObservedSpeciesDtos; +import fr.ird.observe.services.dto.seine.ObjectObservedSpeciesDto; +import fr.ird.observe.services.dto.seine.ObjectSchoolEstimateDto; +import fr.ird.observe.services.service.ReferentialService; +import fr.ird.observe.services.service.seine.ObjectObservedSpeciesService; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; +import java.util.Collection; +import java.util.LinkedList; +import java.util.Set; + +import static org.nuiton.i18n.I18n.n; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class ObjectObservedSpeciesUIHandler extends ContentTableUIHandler<FloatingObjectObservedSpeciesDto, ObjectObservedSpeciesDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(ObjectObservedSpeciesUIHandler.class); + + public ObjectObservedSpeciesUIHandler(ObjectObservedSpeciesUI ui) { + super(ui, DataContextType.SetSeine); + } + + @Override + public ObjectObservedSpeciesUI getUi() { + return (ObjectObservedSpeciesUI) super.getUi(); + } + + @Override + protected String getEditBeanIdToLoad() { + return getDataContext().getSelectedFloatingObjectId(); + } + + @Override + protected void onSelectedRowChanged(int editingRow, ObjectObservedSpeciesDto bean, boolean create) { + if (log.isDebugEnabled()) { + log.debug("Row has changed to " + editingRow); + } + if (getTableModel().isEditable()) { + getUi().getSpecies().requestFocus(); + } + } + + @Override + protected void initTableUI(DefaultTableCellRenderer renderer) { + JTable table = getUi().getTable(); + + UIHelper.setI18nTableHeaderRenderer(table, + n("observe.content.objectObservedSpecies.table.speciesFaune"), + n("observe.content.objectObservedSpecies.table.speciesFaune.tip"), + n("observe.content.objectObservedSpecies.table.speciesStatus"), + n("observe.content.objectObservedSpecies.table.speciesStatus.tip"), + n("observe.content.objectObservedSpecies.table.count"), + n("observe.content.objectObservedSpecies.table.count.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesDto.class)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesStatusDto.class)); + UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + } + + @Override + protected void doPersist(FloatingObjectObservedSpeciesDto bean) { + + SaveResultDto saveResult = getObjectObservedSpeciesService().save(bean); + saveResult.toDto(bean); + + } + + @Override + protected void loadEditBean(String beanId) { + Form<FloatingObjectObservedSpeciesDto> form = getObjectObservedSpeciesService().loadForm(beanId); + loadReferentialReferenceSetsInModel(form); + getModel().setForm(form); + FloatingObjectObservedSpeciesDtos.copyFloatingObjectObservedSpeciesDto(form.getObject(), getBean()); + } + + @Override + protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { + + Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); + + switch (propertyName) { + + case ObjectSchoolEstimateDto.PROPERTY_SPECIES: { + String speciesListId = ObserveSwingApplicationContext.get().getConfig().getSpeciesListSeineObjectObservedSpeciesId(); + + ReferentialService referentialService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newReferentialService(); + Form<SpeciesListDto> speciesListDtoForm = referentialService.loadForm(SpeciesListDto.class, speciesListId); + SpeciesListDto speciesListDto = speciesListDtoForm.getObject(); + + Set<String> speciesIds = speciesListDto.getSpeciesIds(); + + result = ReferentialReferences.filterContains(result, speciesIds); + + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + } + + break; + + } + + return result; + + } + + protected ObjectObservedSpeciesService getObjectObservedSpeciesService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newObjectObservedSpeciesService(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectObservedSpeciesUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectObservedSpeciesUIModel.java new file mode 100644 index 0000000..07136fc --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectObservedSpeciesUIModel.java @@ -0,0 +1,92 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import fr.ird.observe.services.dto.seine.FloatingObjectObservedSpeciesDto; +import fr.ird.observe.services.dto.seine.ObjectObservedSpeciesDto; +import fr.ird.observe.services.dto.seine.ObjectObservedSpeciesDtos; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; + +import java.util.Collection; +import java.util.List; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ObjectObservedSpeciesUIModel extends ContentTableUIModel<FloatingObjectObservedSpeciesDto, ObjectObservedSpeciesDto> { + + private static final long serialVersionUID = 1L; + + public ObjectObservedSpeciesUIModel(ObjectObservedSpeciesUI ui) { + + super(FloatingObjectObservedSpeciesDto.class, + ObjectObservedSpeciesDto.class, + new String[]{ + FloatingObjectObservedSpeciesDto.PROPERTY_OBJECT_OBSERVED_SPECIES, + FloatingObjectObservedSpeciesDto.PROPERTY_COMMENT}, + new String[]{ + ObjectObservedSpeciesDto.PROPERTY_SPECIES, + ObjectObservedSpeciesDto.PROPERTY_SPECIES_STATUS, + ObjectObservedSpeciesDto.PROPERTY_COUNT} + ); + + List<ContentTableMeta<ObjectObservedSpeciesDto>> metas = Lists.newArrayList( + ContentTableModel.newTableMeta(ObjectObservedSpeciesDto.class, ObjectObservedSpeciesDto.PROPERTY_SPECIES, false), + ContentTableModel.newTableMeta(ObjectObservedSpeciesDto.class, ObjectObservedSpeciesDto.PROPERTY_SPECIES_STATUS, false), + ContentTableModel.newTableMeta(ObjectObservedSpeciesDto.class, ObjectObservedSpeciesDto.PROPERTY_COUNT, false)); + + initModel(ui, metas); + + } + + @Override + protected ContentTableModel<FloatingObjectObservedSpeciesDto, ObjectObservedSpeciesDto> createTableModel( + ObserveContentTableUI<FloatingObjectObservedSpeciesDto, ObjectObservedSpeciesDto> ui, + List<ContentTableMeta<ObjectObservedSpeciesDto>> contentTableMetas) { + + return new ContentTableModel<FloatingObjectObservedSpeciesDto, ObjectObservedSpeciesDto>(ui, contentTableMetas) { + private static final long serialVersionUID = 1L; + @Override + protected Collection<ObjectObservedSpeciesDto> getChilds(FloatingObjectObservedSpeciesDto bean) { + return bean.getObjectObservedSpecies(); + } + + @Override + protected void load(ObjectObservedSpeciesDto source, ObjectObservedSpeciesDto target) { + ObjectObservedSpeciesDtos.copyObjectObservedSpeciesDto(source, target); + } + + @Override + protected void setChilds(FloatingObjectObservedSpeciesDto parent, List<ObjectObservedSpeciesDto> childs) { + bean.setObjectObservedSpecies(childs); + } + }; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectSchoolEstimateUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectSchoolEstimateUI.jaxx new file mode 100644 index 0000000..1755a20 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectSchoolEstimateUI.jaxx @@ -0,0 +1,113 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.table.ContentTableUI + superGenericType='FloatingObjectSchoolEstimateDto, ObjectSchoolEstimateDto' + contentTitle='{n("observe.common.schoolEstimate")}' + saveNewEntryText='{n("observe.content.action.create.schoolEstimate")}' + saveNewEntryTip='{n("observe.content.action.create.schoolEstimate.tip")}'> + + <style source="../../CommonTable.jcss"/> + + <import> + fr.ird.observe.services.dto.CommentableDto + fr.ird.observe.services.dto.seine.FloatingObjectSchoolEstimateDto + fr.ird.observe.services.dto.seine.ObjectSchoolEstimateDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.SpeciesDto + fr.ird.observe.application.swing.ui.content.table.* + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + java.awt.Dimension + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <ObjectSchoolEstimateUIHandler id='handler' constructorParams='this'/> + + <!-- model --> + <ObjectSchoolEstimateUIModel id='model' constructorParams='this'/> + + <!-- edit bean --> + <FloatingObjectSchoolEstimateDto id='bean'/> + + <!-- table edit bean --> + <ObjectSchoolEstimateDto id='tableEditBean'/> + + <!-- table model --> + <ContentTableModel id='tableModel'/> + + <!-- le validateur de l'écran --> + <BeanValidator id='validator' + autoField='true' + beanClass='fr.ird.observe.services.dto.seine.FloatingObjectSchoolEstimateDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update'/> + + <!-- le validateur d'une entrée de tableau --> + <BeanValidator id='validatorTable' + autoField='true' + beanClass='fr.ird.observe.services.dto.seine.ObjectSchoolEstimateDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update'/> + + <Table id='editorPanel' fill='both' insets='1'> + + <!-- species --> + <row> + <cell> + <JLabel id='speciesLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='species' constructorParams='this' + genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class'/> + </cell> + </row> + + <!-- weight --> + <row> + <cell> + <JLabel id='totalWeightLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='totalWeight' constructorParams='this'/> + </cell> + </row> + </Table> + + <Table id='extraZone' fill='both' weightx='1' insets='1'> + <row> + <cell weighty='1'> + <JScrollPane id='comment' + onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2' + onKeyReleased='getBean().setComment(comment2.getText())'/> + </JScrollPane> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectSchoolEstimateUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectSchoolEstimateUI.jcss new file mode 100644 index 0000000..4175538 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectSchoolEstimateUI.jcss @@ -0,0 +1,51 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#speciesLabel { + text:"observe.common.speciesThon"; + labelFor:{species}; +} + +#species { + property:{ObjectSchoolEstimateDto.PROPERTY_SPECIES}; + selectedItem:{tableEditBean.getSpecies()}; +} + +#totalWeightLabel { + text:"observe.common.totalWeight"; + labelFor:{totalWeight}; +} + +#totalWeight { + property:{ObjectSchoolEstimateDto.PROPERTY_TOTAL_WEIGHT}; + model:{tableEditBean.getTotalWeight()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; +} + +#comment { + columnHeaderView:{new JLabel(t("observe.common.comment.floatingObject"))}; + minimumSize:{new Dimension(10,80)}; +} + +#comment2 { + text:{getStringValue(bean.getComment())}; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectSchoolEstimateUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectSchoolEstimateUIHandler.java new file mode 100644 index 0000000..bbf749f --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectSchoolEstimateUIHandler.java @@ -0,0 +1,148 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.ReferentialReferences; +import fr.ird.observe.services.dto.referential.SpeciesDto; +import fr.ird.observe.services.dto.referential.SpeciesListDto; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.dto.seine.FloatingObjectSchoolEstimateDto; +import fr.ird.observe.services.dto.seine.FloatingObjectSchoolEstimateDtos; +import fr.ird.observe.services.dto.seine.ObjectSchoolEstimateDto; +import fr.ird.observe.services.service.ReferentialService; +import fr.ird.observe.services.service.seine.ObjectSchoolEstimateService; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; +import java.util.Collection; +import java.util.LinkedList; +import java.util.Set; + +import static org.nuiton.i18n.I18n.n; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class ObjectSchoolEstimateUIHandler extends ContentTableUIHandler<FloatingObjectSchoolEstimateDto, ObjectSchoolEstimateDto> { + + + /** Logger */ + private static final Log log = LogFactory.getLog(ObjectSchoolEstimateUIHandler.class); + + public ObjectSchoolEstimateUIHandler(ObjectSchoolEstimateUI ui) { + super(ui, DataContextType.SetSeine); + } + + @Override + public ObjectSchoolEstimateUI getUi() { + return (ObjectSchoolEstimateUI) super.getUi(); + } + + @Override + protected void onSelectedRowChanged(int editingRow, ObjectSchoolEstimateDto bean, boolean create) { + if (getTableModel().isEditable()) { + if (log.isDebugEnabled()) { + log.debug("Row has changed to " + editingRow); + } + getUi().getSpecies().requestFocus(); + } + } + + @Override + protected String getEditBeanIdToLoad() { + return getDataContext().getSelectedFloatingObjectId(); + } + + @Override + protected void initTableUI(DefaultTableCellRenderer renderer) { + JTable table = getUi().getTable(); + + UIHelper.setI18nTableHeaderRenderer(table, + n("observe.content.schoolEstimate.table.speciesThon"), + n("observe.content.schoolEstimate.table.speciesThon.tip"), + n("observe.content.schoolEstimate.table.weight"), + n("observe.content.schoolEstimate.table.weight.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesDto.class)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + } + + @Override + protected void doPersist(FloatingObjectSchoolEstimateDto bean) { + + SaveResultDto saveResult = getObjectSchoolEstimateService().save(bean); + saveResult.toDto(bean); + + } + + @Override + protected void loadEditBean(String beanId) { + Form<FloatingObjectSchoolEstimateDto> form = getObjectSchoolEstimateService().loadForm(beanId); + loadReferentialReferenceSetsInModel(form); + getModel().setForm(form); + FloatingObjectSchoolEstimateDtos.copyFloatingObjectSchoolEstimateDto(form.getObject(), getBean()); + } + + @Override + protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { + + Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); + + switch (propertyName) { + + case ObjectSchoolEstimateDto.PROPERTY_SPECIES: { + String speciesListId = ObserveSwingApplicationContext.get().getConfig().getSpeciesListSeineObjectSchoolEstimateId(); + + ReferentialService referentialService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newReferentialService(); + Form<SpeciesListDto> speciesListDtoForm = referentialService.loadForm(SpeciesListDto.class, speciesListId); + SpeciesListDto speciesListDto = speciesListDtoForm.getObject(); + + Set<String> speciesIds = speciesListDto.getSpeciesIds(); + result = ReferentialReferences.filterContains(result, speciesIds); + + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + } + + break; + + } + + return result; + + } + + protected ObjectSchoolEstimateService getObjectSchoolEstimateService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newObjectSchoolEstimateService(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectSchoolEstimateUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectSchoolEstimateUIModel.java new file mode 100644 index 0000000..87cc14d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/ObjectSchoolEstimateUIModel.java @@ -0,0 +1,90 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import fr.ird.observe.services.dto.seine.FloatingObjectSchoolEstimateDto; +import fr.ird.observe.services.dto.seine.ObjectSchoolEstimateDto; +import fr.ird.observe.services.dto.seine.ObjectSchoolEstimateDtos; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; + +import java.util.Collection; +import java.util.List; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class ObjectSchoolEstimateUIModel extends ContentTableUIModel<FloatingObjectSchoolEstimateDto, ObjectSchoolEstimateDto> { + + private static final long serialVersionUID = 1L; + + public ObjectSchoolEstimateUIModel(ObjectSchoolEstimateUI ui) { + + super(FloatingObjectSchoolEstimateDto.class, + ObjectSchoolEstimateDto.class, + new String[]{ + FloatingObjectSchoolEstimateDto.PROPERTY_OBJECT_SCHOOL_ESTIMATE, + FloatingObjectSchoolEstimateDto.PROPERTY_COMMENT}, + new String[]{ + ObjectSchoolEstimateDto.PROPERTY_SPECIES, + ObjectSchoolEstimateDto.PROPERTY_TOTAL_WEIGHT} + ); + + List<ContentTableMeta<ObjectSchoolEstimateDto>> metas = Lists.newArrayList( + ContentTableModel.newTableMeta(ObjectSchoolEstimateDto.class, ObjectSchoolEstimateDto.PROPERTY_SPECIES, false), + ContentTableModel.newTableMeta(ObjectSchoolEstimateDto.class, ObjectSchoolEstimateDto.PROPERTY_TOTAL_WEIGHT, false)); + + initModel(ui, metas); + + } + + @Override + protected ContentTableModel<FloatingObjectSchoolEstimateDto, ObjectSchoolEstimateDto> createTableModel( + ObserveContentTableUI<FloatingObjectSchoolEstimateDto, ObjectSchoolEstimateDto> ui, + List<ContentTableMeta<ObjectSchoolEstimateDto>> contentTableMetas) { + + return new ContentTableModel<FloatingObjectSchoolEstimateDto, ObjectSchoolEstimateDto>(ui, contentTableMetas) { + private static final long serialVersionUID = 1L; + @Override + protected Collection<ObjectSchoolEstimateDto> getChilds(FloatingObjectSchoolEstimateDto bean) { + return bean.getObjectSchoolEstimate(); + } + + @Override + protected void load(ObjectSchoolEstimateDto source, ObjectSchoolEstimateDto target) { + ObjectSchoolEstimateDtos.copyObjectSchoolEstimateDto(source, target); + } + + @Override + protected void setChilds(FloatingObjectSchoolEstimateDto parent, List<ObjectSchoolEstimateDto> childs) { + parent.setObjectSchoolEstimate(childs); + } + }; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/SchoolEstimateUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/SchoolEstimateUI.jaxx new file mode 100644 index 0000000..d11fff0 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/SchoolEstimateUI.jaxx @@ -0,0 +1,129 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.table.ContentTableUI + superGenericType='SetSeineSchoolEstimateDto, SchoolEstimateDto' + + + contentTitle='{n("observe.common.schoolEstimate")}' + saveNewEntryText='{n("observe.content.action.create.schoolEstimate")}' + saveNewEntryTip='{n("observe.content.action.create.schoolEstimate.tip")}'> + + <style source="../../CommonTable.jcss"/> + + <import> + fr.ird.observe.services.dto.CommentableDto + fr.ird.observe.services.dto.seine.SetSeineSchoolEstimateDto + fr.ird.observe.services.dto.seine.SchoolEstimateDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.SpeciesDto + fr.ird.observe.application.swing.ui.content.table.* + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + java.awt.Dimension + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <SchoolEstimateUIHandler id='handler' constructorParams='this'/> + + <!-- model --> + <SchoolEstimateUIModel id='model' constructorParams='this'/> + + <!-- edit bean --> + <SetSeineSchoolEstimateDto id='bean'/> + + <!-- table edit bean --> + <SchoolEstimateDto id='tableEditBean'/> + + <!-- table model --> + <ContentTableModel id='tableModel'/> + + <!-- le validateur de l'écran --> + <BeanValidator id='validator' + autoField='true' + beanClass='fr.ird.observe.services.dto.seine.SetSeineSchoolEstimateDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update'> + <!-- clef unique --> + <field name="schoolEstimate" component="editorPanel"/> + </BeanValidator> + + <!-- le validateur d'une entrée de tableau --> + <BeanValidator id='validatorTable' + autoField='true' + beanClass='fr.ird.observe.services.dto.seine.SchoolEstimateDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update'/> + + <!-- formulaire --> + <Table id='editorPanel' fill='both' insets='1'> + + <!-- species --> + <row> + <cell> + <JLabel id='speciesLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='species' genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class' + constructorParams='this'/> + </cell> + </row> + + <!-- weight --> + <row> + <cell> + <JLabel id='totalWeightLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='totalWeight' constructorParams='this'/> + </cell> + </row> + + <!-- mean weight --> + <row> + <cell> + <JLabel id='meanWeightLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='meanWeight' constructorParams='this'/> + </cell> + </row> + </Table> + + <Table id='extraZone' fill='both' weightx='1' insets='1'> + <row> + <cell weighty='1'> + <JScrollPane id='comment' + onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2' + onKeyReleased='getBean().setComment(comment2.getText())'/> + </JScrollPane> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/SchoolEstimateUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/SchoolEstimateUI.jcss new file mode 100644 index 0000000..b9787a6 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/SchoolEstimateUI.jcss @@ -0,0 +1,64 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#speciesLabel { + text:"observe.common.speciesThon"; + labelFor:{species}; + toolTipText:"observe.content.schoolEstimate.table.speciesThon.tip"; +} + +#species { + property:{SchoolEstimateDto.PROPERTY_SPECIES}; + selectedItem:{tableEditBean.getSpecies()}; + enabled:{!tableModel.isEditable() || !model.isRowSaved()}; +} + +#totalWeightLabel { + text:"observe.common.weight"; + labelFor:{totalWeight}; +} + +#totalWeight { + property:{SchoolEstimateDto.PROPERTY_TOTAL_WEIGHT}; + model:{tableEditBean.getTotalWeight()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_7_DIGITS_PATTERN}; +} + +#meanWeightLabel { + text:"observe.common.meanWeight"; + labelFor:{meanWeight}; +} + +#meanWeight { + property:{SchoolEstimateDto.PROPERTY_MEAN_WEIGHT}; + model:{tableEditBean.getMeanWeight()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; +} + +#comment { + columnHeaderView:{new JLabel(t("observe.common.comment.set"))}; + minimumSize:{new Dimension(10,80)}; +} + +#comment2 { + text:{getStringValue(bean.getComment())}; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/SchoolEstimateUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/SchoolEstimateUIHandler.java new file mode 100644 index 0000000..701d906 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/SchoolEstimateUIHandler.java @@ -0,0 +1,179 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.ReferentialReferences; +import fr.ird.observe.services.dto.referential.SpeciesDto; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.dto.seine.ObjectSchoolEstimateDto; +import fr.ird.observe.services.dto.seine.SchoolEstimateDto; +import fr.ird.observe.services.dto.seine.SetSeineSchoolEstimateDto; +import fr.ird.observe.services.dto.seine.SetSeineSchoolEstimateDtos; +import fr.ird.observe.services.service.seine.SchoolEstimateService; +import fr.ird.observe.services.service.seine.TripSeineService; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JComponent; +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.nuiton.i18n.I18n.n; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class SchoolEstimateUIHandler extends ContentTableUIHandler<SetSeineSchoolEstimateDto, SchoolEstimateDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(SchoolEstimateUIHandler.class); + + public SchoolEstimateUIHandler(SchoolEstimateUI ui) { + super(ui, DataContextType.SetSeine); + } + + @Override + public SchoolEstimateUI getUi() { + return (SchoolEstimateUI) super.getUi(); + } + + @Override + protected String getEditBeanIdToLoad() { + return getDataContext().getSelectedSetId(); + } + + @Override + protected void onSelectedRowChanged(int editingRow, SchoolEstimateDto bean, boolean create) { + + ContentTableModel<SetSeineSchoolEstimateDto, SchoolEstimateDto> model = getTableModel(); + + if (!model.isEditable()) { + + // rien a faire + return; + } + + SchoolEstimateUI ui = getUi(); + List<ReferentialReference<SpeciesDto>> availableEspeces; + JComponent requestFocus; + + if (create) { + Set<ReferentialReference<SpeciesDto>> references = getModel().getReferentialReferences(SchoolEstimateDto.PROPERTY_SPECIES); + + List<ReferentialReference<SpeciesDto>> listSpeciesUsed = model.getColumnValues(0); + + Set<String> listSpeciesIdUsed = listSpeciesUsed.stream().map(ReferentialReference::getId).collect(Collectors.toSet()); + + availableEspeces = ReferentialReferences.filterNotContains(references,listSpeciesIdUsed); + + requestFocus = ui.getSpecies(); + } else { + ReferentialReference<SpeciesDto> species = bean.getSpecies(); + availableEspeces = Collections.singletonList(species); + requestFocus = ui.getTotalWeight(); + } + ui.getSpecies().setData(availableEspeces); + requestFocus.requestFocus(); + } + + @Override + protected void initTableUI(DefaultTableCellRenderer renderer) { + JTable table = getUi().getTable(); + + UIHelper.setI18nTableHeaderRenderer( + table, + n("observe.content.schoolEstimate.table.speciesThon"), + n("observe.content.schoolEstimate.table.speciesThon.tip"), + n("observe.content.schoolEstimate.table.weight"), + n("observe.content.schoolEstimate.table.weight.tip"), + n("observe.content.schoolEstimate.table.meanWeight"), + n("observe.content.schoolEstimate.table.meanWeight.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesDto.class)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + } + + @Override + protected void doPersist(SetSeineSchoolEstimateDto bean) { + + SaveResultDto saveResult = getSchoolEstimateService().save(bean); + saveResult.toDto(bean); + } + + @Override + protected void loadEditBean(String beanId) { + Form<SetSeineSchoolEstimateDto> form = getSchoolEstimateService().loadForm(beanId); + loadReferentialReferenceSetsInModel(form); + getModel().setForm(form); + SetSeineSchoolEstimateDtos.copySetSeineSchoolEstimateDto(form.getObject(), getBean()); + } + + @Override + protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { + + Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); + + switch (propertyName) { + + case ObjectSchoolEstimateDto.PROPERTY_SPECIES: { + + String speciesListId = ObserveSwingApplicationContext.get().getConfig().getSpeciesListSeineSchoolEstimateId(); + String tripSeineId = getDataContext().getSelectedTripSeineId(); + + TripSeineService tripSeineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripSeineService(); + result = (List) tripSeineService.getSpeciesByListAndTrip(tripSeineId, speciesListId); + + result = ReferentialReferences.filterEnabled(result); + + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + } + + break; + + } + + return result; + + } + + protected SchoolEstimateService getSchoolEstimateService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newSchoolEstimateService(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/SchoolEstimateUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/SchoolEstimateUIModel.java new file mode 100644 index 0000000..5fbc7f1 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/SchoolEstimateUIModel.java @@ -0,0 +1,92 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import fr.ird.observe.services.dto.seine.SchoolEstimateDto; +import fr.ird.observe.services.dto.seine.SchoolEstimateDtos; +import fr.ird.observe.services.dto.seine.SetSeineSchoolEstimateDto; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; + +import java.util.Collection; +import java.util.List; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class SchoolEstimateUIModel extends ContentTableUIModel<SetSeineSchoolEstimateDto, SchoolEstimateDto> { + + private static final long serialVersionUID = 1L; + + public SchoolEstimateUIModel(SchoolEstimateUI ui) { + + super(SetSeineSchoolEstimateDto.class, + SchoolEstimateDto.class, + new String[]{ + SetSeineSchoolEstimateDto.PROPERTY_SCHOOL_ESTIMATE, + SetSeineSchoolEstimateDto.PROPERTY_COMMENT}, + new String[]{ + SchoolEstimateDto.PROPERTY_SPECIES, + SchoolEstimateDto.PROPERTY_TOTAL_WEIGHT, + SchoolEstimateDto.PROPERTY_MEAN_WEIGHT} + ); + + List<ContentTableMeta<SchoolEstimateDto>> metas = Lists.newArrayList( + ContentTableModel.newTableMeta(SchoolEstimateDto.class, SchoolEstimateDto.PROPERTY_SPECIES, false), + ContentTableModel.newTableMeta(SchoolEstimateDto.class, SchoolEstimateDto.PROPERTY_TOTAL_WEIGHT, false), + ContentTableModel.newTableMeta(SchoolEstimateDto.class, SchoolEstimateDto.PROPERTY_MEAN_WEIGHT, false)); + + initModel(ui, metas); + + } + + @Override + protected ContentTableModel<SetSeineSchoolEstimateDto, SchoolEstimateDto> createTableModel( + ObserveContentTableUI<SetSeineSchoolEstimateDto, SchoolEstimateDto> ui, + List<ContentTableMeta<SchoolEstimateDto>> contentTableMetas) { + + return new ContentTableModel<SetSeineSchoolEstimateDto, SchoolEstimateDto>(ui, contentTableMetas) { + private static final long serialVersionUID = 1L; + @Override + protected Collection<SchoolEstimateDto> getChilds(SetSeineSchoolEstimateDto bean) { + return bean.getSchoolEstimate(); + } + + @Override + protected void load(SchoolEstimateDto source, SchoolEstimateDto target) { + SchoolEstimateDtos.copySchoolEstimateDto(source, target); + } + + @Override + protected void setChilds(SetSeineSchoolEstimateDto parent, List<SchoolEstimateDto> childs) { + bean.setSchoolEstimate(childs); + } + }; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetCatchUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetCatchUI.jaxx new file mode 100644 index 0000000..57f65ce --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetCatchUI.jaxx @@ -0,0 +1,141 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.table.ContentTableUI + superGenericType='SetSeineTargetCatchDto, TargetCatchDto' + contentTitle='{n("observe.common.targetCatch")}' + saveNewEntryText='{n("observe.content.action.create.targetCatch")}' + saveNewEntryTip='{n("observe.content.action.create.targetCatch.tip")}'> + + <style source="../../CommonTable.jcss"/> + + <import> + fr.ird.observe.services.dto.CommentableDto + fr.ird.observe.services.dto.seine.SetSeineTargetCatchDto + fr.ird.observe.services.dto.seine.TargetCatchDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.SpeciesDto + fr.ird.observe.services.dto.referential.seine.WeightCategoryDto + fr.ird.observe.application.swing.ui.content.table.* + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + java.awt.Dimension + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <TargetCatchUIHandler id='handler' constructorParams='this'/> + + <!-- model --> + <TargetCatchUIModel id='model' constructorParams='this'/> + + <!-- edit bean --> + <SetSeineTargetCatchDto id='bean'/> + + <!-- table edit bean --> + <TargetCatchDto id='tableEditBean'/> + + <!-- table model --> + <ContentTableModel id='tableModel'/> + + <!-- le validateur de l'écran --> + <BeanValidator id='validator' + beanClass='fr.ird.observe.services.dto.seine.SetSeineTargetCatchDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update-targetCatch'> + <!-- clef unique --> + <field name="targetCatch" component="editorPanel"/> + </BeanValidator> + + <!-- le validateur d'une entrée de tableau --> + <BeanValidator id='validatorTable' + autoField='true' + beanClass='fr.ird.observe.services.dto.seine.TargetCatchDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update-targetCatch'/> + + <Table id='editorPanel' fill='both' insets='1' + onFocusGained='species.requestFocus()'> + + <!-- species --> + <row> + <cell> + <JLabel id='speciesLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='species' genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class' constructorParams='this'/> + + </cell> + </row> + + <!-- categorie species thon --> + <row> + <cell> + <JLabel id='weightCategoryLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='weightCategory' genericType='ReferentialReference<WeightCategoryDto>' _entityClass='WeightCategoryDto.class' constructorParams='this'/> + </cell> + </row> + + <!-- weight --> + <row> + <cell> + <JLabel id='catchWeightLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='catchWeight' constructorParams='this'/> + </cell> + </row> + + <!-- well --> + <row> + <cell> + <JLabel id='wellLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <JPanel layout='{new BorderLayout()}'> + <JToolBar id='wellToolbar' constraints='BorderLayout.WEST'> + <JButton id='resetWell' constraints='BorderLayout.WEST' styleClass='resetButton'/> + </JToolBar> + <JTextField id='well' constraints='BorderLayout.CENTER'/> + </JPanel> + </cell> + </row> + + <!-- comment --> + <row> + <cell columns='2' weighty='1'> + <JScrollPane id='comment' + onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2' + onKeyReleased='getTableEditBean().setComment(((JTextArea) event.getSource()).getText())'/> + </JScrollPane> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetCatchUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetCatchUI.jcss new file mode 100644 index 0000000..7416750 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetCatchUI.jcss @@ -0,0 +1,88 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#tableModel { + deleteExtraMessage:{t("observe.content.targetCatch.table.deleteExtraMessage")}; +} + +#speciesLabel { + text:"observe.content.targetCatch.table.speciesThon"; + toolTipText:"observe.content.targetCatch.table.speciesThon.tip"; + labelFor:{species}; +} + +#species { + property:"species"; + selectedItem:{tableEditBean.getSpecies()}; + enabled:{!tableModel.isEditable() || !model.isRowSaved()}; +} + +#weightCategoryLabel { + text:"observe.common.weightCategory"; + toolTipText:"observe.content.targetCatch.table.weightCategory.tip"; + labelFor:{weightCategory}; +} + +#weightCategory { + property:{TargetCatchDto.PROPERTY_WEIGHT_CATEGORY}; + selectedItem:{tableEditBean.getWeightCategory()}; + enabled:{!tableModel.isEditable() || !model.isRowSaved()}; +} + +#catchWeightLabel { + text:"observe.common.catchWeight"; + labelFor:{catchWeight}; +} + +#catchWeight { + property:{TargetCatchDto.PROPERTY_CATCH_WEIGHT}; + model:{tableEditBean.getCatchWeight()}; + useFloat:true; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL3_PATTERN}; +} + +#wellLabel { + text:"observe.common.well"; + toolTipText:"observe.content.targetCatch.table.well.tip"; + labelFor:{well}; +} + +#resetWell { + toolTipText:"observe.content.action.reset.well.tip"; + enabled:{!tableModel.isEditable() || !model.isRowSaved()}; + _resetTablePropertyName:{TargetCatchDto.PROPERTY_WELL}; +} + +#well { + text:{getStringValue(tableEditBean.getWell())}; + enabled:{!tableModel.isEditable() || !model.isRowSaved()}; + _tablePropertyName:{TargetCatchDto.PROPERTY_WELL}; +} + +#comment { + columnHeaderView:{new JLabel(t("observe.common.comment.targetCatch"))}; + minimumSize:{new Dimension(10,80)}; +} + +#comment2 { + text:{getStringValue(tableEditBean.getComment())}; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetCatchUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetCatchUIHandler.java new file mode 100644 index 0000000..959e09a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetCatchUIHandler.java @@ -0,0 +1,329 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +import com.google.common.collect.Iterables; +import com.google.common.collect.Sets; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.ReferentialReferences; +import fr.ird.observe.services.dto.referential.SpeciesDto; +import fr.ird.observe.services.dto.referential.seine.WeightCategoryDto; +import fr.ird.observe.services.dto.referential.seine.WeightCategoryDtos; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.dto.seine.ObjectSchoolEstimateDto; +import fr.ird.observe.services.dto.seine.SetSeineTargetCatchDto; +import fr.ird.observe.services.dto.seine.SetSeineTargetCatchDtos; +import fr.ird.observe.services.dto.seine.TargetCatchDto; +import fr.ird.observe.services.dto.seine.TargetCatchDtos; +import fr.ird.observe.services.service.seine.TargetCatchService; +import fr.ird.observe.services.service.seine.TripSeineService; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIHandler; +import jaxx.runtime.swing.editor.bean.BeanComboBox; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.decorator.Decorator; + +import javax.swing.JComponent; +import javax.swing.JOptionPane; +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Set; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class TargetCatchUIHandler extends ContentTableUIHandler<SetSeineTargetCatchDto, TargetCatchDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(TargetCatchUIHandler.class); + + public TargetCatchUIHandler(TargetCatchUI ui) { + super(ui, DataContextType.SetSeine); + } + + @Override + public TargetCatchUI getUi() { + return (TargetCatchUI) super.getUi(); + } + + @Override + public void initUI() { + super.initUI(); + + // lors de la modification d'une species (sur une entree non sauvee) + // - on recalcule la liste des categories pour cette species. + // - on reinitialiser la categorie selectionnee + + getUi().getSpecies().addPropertyChangeListener( + BeanComboBox.PROPERTY_SELECTED_ITEM, + evt -> { + + ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto> model = getTableModel(); + if (model.isNewRow()) { + + // en mode creation , on doit recalculer la liste des categories + ReferentialReference<SpeciesDto> species = (ReferentialReference<SpeciesDto>) evt.getNewValue(); + onSpeciesChanged(species); + + } + } + ); + } + + @Override + protected String getEditBeanIdToLoad() { + return getDataContext().getSelectedSetId(); + } + + @SuppressWarnings("Duplicates") + @Override + protected boolean prepareSave(SetSeineTargetCatchDto bean, List<TargetCatchDto> objets) { + + // on cherche si parmis les captures supprimer certaines ont des échantillons + SetSeineTargetCatchDto originalSetSeineTargetCatchDto = getModel().getForm().getObject(); + SetSeineTargetCatchDto currentSetSeineTargetCatch = getModel().getBean(); + + Set<ReferentialReference<SpeciesDto>> speciesToDelete = Sets.newHashSet(); + + for (TargetCatchDto targetCatchDto : originalSetSeineTargetCatchDto.getTargetCatch()) { + + if (targetCatchDto.isHasSample()) { + + ReferentialReference<SpeciesDto> species = targetCatchDto.getSpecies(); + + Iterable<TargetCatchDto> currentTargetCatchSpecies = TargetCatchDtos.filterBySpecies(currentSetSeineTargetCatch.getTargetCatch(), species); + + if (Iterables.isEmpty(currentTargetCatchSpecies)) { + + speciesToDelete.add(species); + + } + } + + } + + if (!speciesToDelete.isEmpty()) { + + // il existe des echantillons thon a supprimer on demande une confirmation + StringBuilder sb = new StringBuilder(512); + Decorator<ReferentialReference<SpeciesDto>> decorator = getReferentialReferenceDecorator(SpeciesDto.class); + + for (ReferentialReference<SpeciesDto> species : speciesToDelete) { + sb.append(" - ").append(decorator.toString(species)).append('\n'); + } + int reponse = UIHelper.askUser( + t("observe.title.need.confirm"), + t("observe.content.targetDiscarded.message.table.will.delete.targetLength", sb.toString()), + JOptionPane.ERROR_MESSAGE, + new Object[]{ + t("observe.choice.continue"), + t("observe.choice.cancel")}, + 0); + if (log.isDebugEnabled()) { + log.debug("response : " + reponse); + } + boolean canContinue = false; + switch (reponse) { + case 0: + // wil reset ui + canContinue = true; + break; + } + + if (!canContinue) { + + // l'utilisateur a choisi de ne pas continuer + return false; + } + } + return true; + } + + @Override + protected void onSelectedRowChanged(int editingRow, TargetCatchDto bean, boolean create) { + + TargetCatchUI ui = getUi(); + + ReferentialReference<WeightCategoryDto> weightCategory = bean.getWeightCategory(); + + ReferentialReference<SpeciesDto> species = null; + if (weightCategory != null) { + species = getWeightCategorySpecies(weightCategory).orElse(null); + } + + JComponent requestFocus; + if (create) { + + // on reinitilise toujours l'espèce (pour reinitialiser la liste des categories) + ui.getSpecies().setSelectedItem(null); + + if (!getTableModel().isCreate()) { + // on repositionne l'espèce (cela reconstruira la liste des categories) + ui.getSpecies().setSelectedItem(species); + // on repositionne la categorie + ui.getWeightCategory().setSelectedItem(weightCategory); + } + + requestFocus = ui.getSpecies(); + + } else { + + // en mode mise a jour, on restreint la liste des categories + // au singleton de sa valeur correspondante dans le bean + // puisque dans ce mode, pas possibilite de modifier de cette + // valeur (clef metier) + ui.getSpecies().setSelectedItem(species); + ui.getWeightCategory().setData(Collections.singletonList(weightCategory)); + ui.getWeightCategory().setSelectedItem(weightCategory); + + requestFocus = ui.getCatchWeight(); + } + + if (log.isDebugEnabled()) { + log.debug("selected weightcategory " + weightCategory); + log.debug("selected species " + species); + } + requestFocus.requestFocus(); + } + + @Override + protected void initTableUI(DefaultTableCellRenderer renderer) { + + JTable table = getUi().getTable(); + + UIHelper.fixTableColumnWidth(table, 2, 100); + UIHelper.fixTableColumnWidth(table, 3, 50); + UIHelper.fixTableColumnWidth(table, 4, 50); + + UIHelper.setI18nTableHeaderRenderer( + table, + n("observe.content.targetCatch.table.speciesThon"), + n("observe.content.targetCatch.table.speciesThon.tip"), + n("observe.content.targetCatch.table.weightCategory"), + n("observe.content.targetCatch.table.weightCategory.tip"), + n("observe.content.targetCatch.table.well"), + n("observe.content.targetCatch.table.well.tip"), + n("observe.content.targetCatch.table.weight"), + n("observe.content.targetCatch.table.weight.tip"), + n("observe.content.targetCatch.table.comment"), + n("observe.content.targetCatch.table.comment.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesDto.class)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, WeightCategoryDto.class)); + UIHelper.setTableColumnRenderer(table, 2, renderer); + UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 4, UIHelper.newStringTableCellRenderer(renderer, 10, true)); + } + + protected void onSpeciesChanged(ReferentialReference<SpeciesDto> species) { + + List<ReferentialReference<WeightCategoryDto>> availableCategories; + + if (species == null) { + + // aucune espèce selectionnee, on vide simplement la liste des categories + // car il faut d'abord choisir une espèce puis une categorie + availableCategories = Collections.emptyList(); + + } else { + + // un espèce est selectionnee, on calcule les categories pour cette espèce + // on ne conserve que les categories de l'espèce + Set<ReferentialReference<WeightCategoryDto>> allCategories = getModel().getReferentialReferences(TargetCatchDto.PROPERTY_WEIGHT_CATEGORY); + availableCategories = WeightCategoryDtos.filterSpeciesWeightCategories(allCategories, species.getId()); + + } + + // on met a jour la liste des categories disponibles + BeanComboBox<ReferentialReference<WeightCategoryDto>> combo = getUi().getWeightCategory(); + combo.setData(availableCategories); + + // on reinitialise toujours la categorie selectionnee + combo.setSelectedItem(null); + + } + + @Override + protected void doPersist(SetSeineTargetCatchDto bean) { + + SaveResultDto saveResult = getTargetCatchService().save(bean); + saveResult.toDto(bean); + + } + + @Override + protected void loadEditBean(String beanId) { + Form<SetSeineTargetCatchDto> form = getTargetCatchService().loadForm(beanId, false); + loadReferentialReferenceSetsInModel(form); + getModel().setForm(form); + SetSeineTargetCatchDtos.copySetSeineTargetCatchDto(form.getObject(), getBean()); + } + + @Override + protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { + + Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); + + switch (propertyName) { + + case ObjectSchoolEstimateDto.PROPERTY_SPECIES: { + + String speciesListId = ObserveSwingApplicationContext.get().getConfig().getSpeciesListSeineTargetCatchId(); + String tripSeineId = getDataContext().getSelectedTripSeineId(); + + TripSeineService tripSeineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripSeineService(); + result = (List) tripSeineService.getSpeciesByListAndTrip(tripSeineId, speciesListId); + + result = ReferentialReferences.filterEnabled(result); + + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + } + + break; + + } + + return result; + + } + + protected TargetCatchService getTargetCatchService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTargetCatchService(); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetCatchUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetCatchUIModel.java new file mode 100644 index 0000000..8418aa1 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetCatchUIModel.java @@ -0,0 +1,98 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import fr.ird.observe.services.dto.referential.seine.WeightCategoryDto; +import fr.ird.observe.services.dto.seine.SetSeineTargetCatchDto; +import fr.ird.observe.services.dto.seine.TargetCatchDto; +import fr.ird.observe.services.dto.seine.TargetCatchDtos; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; + +import java.util.Collection; +import java.util.List; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class TargetCatchUIModel extends ContentTableUIModel<SetSeineTargetCatchDto, TargetCatchDto> { + + private static final long serialVersionUID = 1L; + + public TargetCatchUIModel(TargetCatchUI ui) { + + super(SetSeineTargetCatchDto.class, + TargetCatchDto.class, + new String[]{ + SetSeineTargetCatchDto.PROPERTY_DISCARDED, + SetSeineTargetCatchDto.PROPERTY_TARGET_CATCH + }, + new String[]{ + TargetCatchDto.PROPERTY_WEIGHT_CATEGORY, + TargetCatchDto.PROPERTY_CATCH_WEIGHT, + TargetCatchDto.PROPERTY_WELL, + TargetCatchDto.PROPERTY_BROUGHT_ON_DECK, + TargetCatchDto.PROPERTY_DISCARDED, + TargetCatchDto.PROPERTY_COMMENT} + ); + + List<ContentTableMeta<TargetCatchDto>> metas = Lists.newArrayList( + ContentTableModel.newTableMeta(TargetCatchDto.class, WeightCategoryDto.PROPERTY_SPECIES, true), + ContentTableModel.newTableMeta(TargetCatchDto.class, TargetCatchDto.PROPERTY_WEIGHT_CATEGORY, true), + ContentTableModel.newTableMeta(TargetCatchDto.class, TargetCatchDto.PROPERTY_WELL, false), + ContentTableModel.newTableMeta(TargetCatchDto.class, TargetCatchDto.PROPERTY_CATCH_WEIGHT, false), + ContentTableModel.newTableMeta(TargetCatchDto.class, TargetCatchDto.PROPERTY_COMMENT, false)); + + initModel(ui, metas); + + } + + @Override + protected ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto> createTableModel( + ObserveContentTableUI<SetSeineTargetCatchDto, TargetCatchDto> ui, + List<ContentTableMeta<TargetCatchDto>> contentTableMetas) { + return new ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto>(ui, contentTableMetas) { + private static final long serialVersionUID = 1L; + @Override + protected Collection<TargetCatchDto> getChilds(SetSeineTargetCatchDto bean) { + return bean.getTargetCatch(); + } + + @Override + protected void load(TargetCatchDto source, TargetCatchDto target) { + TargetCatchDtos.copyTargetCatchDto(source, target); + } + + @Override + protected void setChilds(SetSeineTargetCatchDto parent, List<TargetCatchDto> childs) { + parent.setTargetCatch(childs); + } + }; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetDiscardCatchUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetDiscardCatchUI.jaxx new file mode 100644 index 0000000..7b4ed0a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetDiscardCatchUI.jaxx @@ -0,0 +1,151 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.table.ContentTableUI + superGenericType='SetSeineTargetCatchDto, TargetCatchDto' + contentTitle='{n("observe.common.targetDiscarded")}' + saveNewEntryText='{n("observe.content.action.create.targetDiscarded")}' + saveNewEntryTip='{n("observe.content.action.create.targetDiscarded.tip")}'> + + <style source="../../CommonTable.jcss"/> + + <import> + fr.ird.observe.services.dto.CommentableDto + fr.ird.observe.services.dto.seine.SetSeineTargetCatchDto + fr.ird.observe.services.dto.seine.TargetCatchDto + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.SpeciesDto + fr.ird.observe.services.dto.referential.seine.ReasonForDiscardDto + fr.ird.observe.services.dto.referential.seine.WeightCategoryDto + fr.ird.observe.application.swing.ui.content.table.* + fr.ird.observe.application.swing.ui.util.BooleanEditor + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + java.awt.Dimension + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <TargetDiscardCatchUIHandler id='handler' constructorParams='this'/> + + <!-- model --> + <TargetDiscardCatchUIModel id='model' constructorParams='this'/> + + <!-- edit bean --> + <SetSeineTargetCatchDto id='bean'/> + + <!-- table edit bean --> + <TargetCatchDto id='tableEditBean'/> + + <!-- table model --> + <ContentTableModel id='tableModel'/> + + <!-- le validateur de l'écran --> + <BeanValidator id='validator' + beanClass='fr.ird.observe.services.dto.seine.SetSeineTargetCatchDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update-targetDiscarded'> + <!-- clef unique --> + <field name="targetCatch" component="editorPanel"/> + </BeanValidator> + + <!-- le validateur d'une entrée de tableau --> + <BeanValidator id='validatorTable' + autoField='true' + beanClass='fr.ird.observe.services.dto.seine.TargetCatchDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update-targetDiscarded'/> + + <Table id='editorPanel' fill='both' insets='1'> + + <!-- species --> + <row> + <cell> + <JLabel id='speciesLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='species' constructorParams='this' genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class'/> + </cell> + </row> + + <!-- categorie weight --> + <row> + <cell> + <JLabel id='weightCategoryLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='weightCategory' constructorParams='this' genericType='ReferentialReference<WeightCategoryDto>' _entityClass='WeightCategoryDto.class'/> + </cell> + </row> + + <!-- raison rejet --> + <row> + <cell> + <JLabel id='reasonForDiscardLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='reasonForDiscard' constructorParams='this' genericType='ReferentialReference<ReasonForDiscardDto>' _entityClass='ReasonForDiscardDto.class'/> + </cell> + </row> + + <!-- weight --> + <row> + <cell> + <JLabel id='catchWeightLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='catchWeight' constructorParams='this'/> + </cell> + </row> + + <!-- sur le pont --> + <row> + <cell columns='2'> + <JLabel id='broughtOnDeckInformation'/> + </cell> + </row> + <row> + <cell> + <JLabel id='broughtOnDeckLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BooleanEditor id='broughtOnDeck'/> + </cell> + </row> + <!-- comment --> + <row> + <cell columns='2' weighty='1'> + <JScrollPane id='comment' + onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2' + onKeyReleased='getTableEditBean().setComment(((JTextArea) event.getSource()).getText())'/> + </JScrollPane> + </cell> + </row> + + </Table> + +</fr.ird.observe.application.swing.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetDiscardCatchUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetDiscardCatchUI.jcss new file mode 100644 index 0000000..8a04f03 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetDiscardCatchUI.jcss @@ -0,0 +1,100 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#tableModel { + deleteExtraMessage:{t("observe.content.targetDiscarded.table.deleteExtraMessage")}; +} + +#speciesLabel { + text:"observe.common.speciesThon"; + toolTipText:"observe.content.targetDiscarded.table.speciesThon.tip"; + labelFor:{species}; +} + +#species { + property:"species"; + selectedItem:{tableEditBean.getSpecies()}; + enabled:{!tableModel.isEditable() || !model.isRowSaved()}; +} + +#weightCategoryLabel { + text:"observe.common.weightCategory"; + toolTipText:"observe.content.targetDiscarded.table.weightCategory.tip"; + labelFor:{weightCategory}; +} + +#weightCategory { + property:{TargetCatchDto.PROPERTY_WEIGHT_CATEGORY}; + selectedItem:{tableEditBean.getWeightCategory()}; + enabled:{!tableModel.isEditable() || !model.isRowSaved()}; +} + +#reasonForDiscardLabel { + text:"observe.common.reasonForDiscard"; + toolTipText:"observe.content.targetDiscarded.table.reasonForDiscard.tip"; + labelFor:{reasonForDiscard}; +} + +#reasonForDiscard { + property:{TargetCatchDto.PROPERTY_REASON_FOR_DISCARD}; + selectedItem:{tableEditBean.getReasonForDiscard()}; + enabled:{!tableModel.isEditable() || !model.isRowSaved()}; +} + +#catchWeightLabel { + text:"observe.common.catchWeight"; + labelFor:{catchWeight}; +} + +#catchWeight { + property:{TargetCatchDto.PROPERTY_CATCH_WEIGHT}; + model:{tableEditBean.getCatchWeight()}; + useFloat:true; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.DECIMAL3_PATTERN}; +} + +#broughtOnDeckInformation { + text:"observe.content.broughtOnDeck.comment"; + toolTipText:"observe.content.broughtOnDeck.comment"; + actionIcon:"information"; + font-size:11; + verticalAlignment:"center"; +} + +#broughtOnDeckLabel { + text:"observe.common.broughtOnDeck"; + labelFor:{broughtOnDeck}; +} + +#broughtOnDeck { + booleanValue:{tableEditBean.getBroughtOnDeck()}; + _tablePropertyName:{TargetCatchDto.PROPERTY_BROUGHT_ON_DECK}; +} + +#comment { + columnHeaderView:{new JLabel(t("observe.common.comment.targetDiscarded"))}; + minimumSize:{new Dimension(10,80)}; +} + +#comment2 { + text:{getStringValue(tableEditBean.getComment())}; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetDiscardCatchUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetDiscardCatchUIHandler.java new file mode 100644 index 0000000..a3b4026 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetDiscardCatchUIHandler.java @@ -0,0 +1,541 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +import com.google.common.collect.Iterables; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.ReferentialReferences; +import fr.ird.observe.services.dto.referential.SpeciesDto; +import fr.ird.observe.services.dto.referential.seine.ReasonForDiscardDto; +import fr.ird.observe.services.dto.referential.seine.WeightCategoryDto; +import fr.ird.observe.services.dto.referential.seine.WeightCategoryDtos; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.dto.seine.ObjectSchoolEstimateDto; +import fr.ird.observe.services.dto.seine.SetSeineTargetCatchDto; +import fr.ird.observe.services.dto.seine.SetSeineTargetCatchDtos; +import fr.ird.observe.services.dto.seine.TargetCatchDto; +import fr.ird.observe.services.dto.seine.TargetCatchDtos; +import fr.ird.observe.services.service.seine.TargetCatchService; +import fr.ird.observe.services.service.seine.TripSeineService; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIHandler; +import jaxx.runtime.swing.editor.bean.BeanComboBox; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.decorator.Decorator; + +import javax.swing.JComponent; +import javax.swing.JOptionPane; +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedList; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class TargetDiscardCatchUIHandler extends ContentTableUIHandler<SetSeineTargetCatchDto, TargetCatchDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(TargetDiscardCatchUIHandler.class); + + public TargetDiscardCatchUIHandler(TargetDiscardCatchUI ui) { + super(ui, DataContextType.SetSeine); + } + + protected static Collection<ReferentialReference<WeightCategoryDto>> getWeightCategoryUsed( + ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto> model) { + + List<ReferentialReference<WeightCategoryDto>> list = model.getColumnValues(1); + Collection<ReferentialReference<WeightCategoryDto>> set = Sets.newHashSet(list); + list.clear(); + return set; + } + + protected static Collection<ReferentialReference<ReasonForDiscardDto>> getReasonForDiscardUsed( + ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto> model, + ReferentialReference<WeightCategoryDto> weightCategory) { + + Collection<ReferentialReference<ReasonForDiscardDto>> set = Sets.newHashSet(); + if (weightCategory != null) { + for (int i = 0; i < model.getRowCount(); i++) { + TargetCatchDto c = model.getValueAt(i); + if (c != null && weightCategory.equals(c.getWeightCategory()) && c.getReasonForDiscard() != null) { + set.add(c.getReasonForDiscard()); + } + } + } + return set; + } + + @Override + public TargetDiscardCatchUI getUi() { + return (TargetDiscardCatchUI) super.getUi(); + } + + @Override + public void initUI() { + + super.initUI(); + + TargetDiscardCatchUI ui = getUi(); + + // lors de la modification d'une species (sur une entree non sauvee) + // - on recalcule la liste des categories pour cette species. + // - on reinitialiser la categorie selectionnee + + ui.getSpecies().addPropertyChangeListener( + BeanComboBox.PROPERTY_SELECTED_ITEM, + evt -> { + + ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto> model = getTableModel(); + + if (model.isNewRow()) { + + // en mode creation , on doit recalculer la liste des categories + ReferentialReference<SpeciesDto> species = (ReferentialReference<SpeciesDto>) evt.getNewValue(); + onSpeciesChanged(model.getRowBean(), species); + + } + + } + ); + + // lors de la modification d'une catégorie (sur une entree non sauvee) + // - on recalcule la liste des raison rejets. + // - on reinitialiser la raison rejet selectionnee + + ui.getWeightCategory().addPropertyChangeListener( + BeanComboBox.PROPERTY_SELECTED_ITEM, + evt -> { + + ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto> model = getTableModel(); + if (model.isNewRow()) { + + // en mode creation , on doit recalculer la liste des raison rejet + ReferentialReference<WeightCategoryDto> weightCategory = + (ReferentialReference<WeightCategoryDto>) evt.getNewValue(); + onWeightCategoryChanged(model.getRowBean(), weightCategory); + + } + + } + ); + + } + + @Override + protected String getEditBeanIdToLoad() { + return getDataContext().getSelectedSetId(); + } + + @SuppressWarnings("Duplicates") + @Override + protected boolean prepareSave(SetSeineTargetCatchDto bean, List<TargetCatchDto> objets) { + + //on cherche si parmis les captures supprimer certaines ont des échantillons + SetSeineTargetCatchDto originalSetSeineTargetCatchDto = getModel().getForm().getObject(); + SetSeineTargetCatchDto currentSetSeineTargetCatch = getModel().getBean(); + + Set<ReferentialReference<SpeciesDto>> speciesToDelete = Sets.newHashSet(); + + for (TargetCatchDto targetCatchDto : originalSetSeineTargetCatchDto.getTargetCatch()) { + + if (targetCatchDto.isHasSample()) { + + ReferentialReference<SpeciesDto> species = targetCatchDto.getSpecies(); + + Iterable<TargetCatchDto> currentTargetCatchSpecies = TargetCatchDtos.filterBySpecies(currentSetSeineTargetCatch.getTargetCatch(), species); + + if (Iterables.isEmpty(currentTargetCatchSpecies)) { + + speciesToDelete.add(species); + + } + } + + } + + if (!speciesToDelete.isEmpty()) { + // il existe des echantillon thon a supprimer on demande une confirmation + StringBuilder sb = new StringBuilder(512); + Decorator<ReferentialReference<SpeciesDto>> decorator = + getReferentialReferenceDecorator(SpeciesDto.class); + + for (ReferentialReference<SpeciesDto> species : speciesToDelete) { + sb.append(" - ").append(decorator.toString(species)).append('\n'); + } + int reponse = UIHelper.askUser( + t("observe.title.need.confirm"), + t("observe.content.targetDiscarded.message.table.will.delete.targetLength", sb.toString()), + JOptionPane.ERROR_MESSAGE, + new Object[]{ + t("observe.choice.continue"), + t("observe.choice.cancel")}, + 0); + if (log.isDebugEnabled()) { + log.debug("response : " + reponse); + } + boolean canContinue = false; + switch (reponse) { + case 0: + // wil reset ui + canContinue = true; + break; + } + + if (!canContinue) { + + // l'utilisateur a choisi de ne pas continuer + return false; + } + } + + return true; + } + + @SuppressWarnings("Duplicates") + @Override + protected void onSelectedRowChanged(int editingRow, TargetCatchDto bean, boolean create) { + TargetDiscardCatchUI ui = getUi(); + + ReferentialReference<WeightCategoryDto> weightCategory = bean.getWeightCategory(); + + ReferentialReference<SpeciesDto> species = null; + if (weightCategory != null) { + species = getWeightCategorySpecies(weightCategory).orElse(null); + } + + ReferentialReference<ReasonForDiscardDto> reasonForDiscard = bean.getReasonForDiscard(); + if (log.isDebugEnabled()) { + log.debug("selected categoriePoid " + weightCategory); + log.debug("selected species " + species); + log.debug("selected reasonForDiscard " + reasonForDiscard); + } + + JComponent requestFocus; + if (create) { + ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto> model = getTableModel(); + + if (model.isCreate()) { + // par défaut, on considère que l'espèce a été montée sur le pont + // c'est le cas le plus fréquent. + bean.setBroughtOnDeck(true); + } + + // on recalcule la liste des speciess disponibles + List<ReferentialReference<SpeciesDto>> availableSpecies = buildSpeciesList(species, weightCategory); + ui.getSpecies().setData(availableSpecies); + + // on reinitilise toujours l'species (pour reinitialiser la liste des categories) + ui.getSpecies().setSelectedItem(null); + + if (!model.isCreate()) { + // on repositionne l'espèce (cela reconstruira la liste des categories) + ui.getSpecies().setSelectedItem(species); + // on repositionne la categorie + ui.getWeightCategory().setSelectedItem(weightCategory); + ui.getReasonForDiscard().setSelectedItem(reasonForDiscard); + } + + requestFocus = ui.getSpecies(); + } else { + // en mode mise a jour, on restreint la liste des categories + // au singleton de sa valeur correspondante dans le bean + // puisque dans ce mode, pas possibilite de modifier de cette + // valeur (clef metier) + ui.getSpecies().setSelectedItem(species); + ui.getWeightCategory().setData(Collections.singletonList(weightCategory)); + ui.getWeightCategory().setSelectedItem(weightCategory); + ui.getReasonForDiscard().setData(Collections.singletonList(reasonForDiscard)); + ui.getReasonForDiscard().setSelectedItem(reasonForDiscard); + + requestFocus = ui.getCatchWeight(); + } + + requestFocus.requestFocus(); + } + + @Override + protected void initTableUI(DefaultTableCellRenderer renderer) { + JTable table = getUi().getTable(); + UIHelper.fixTableColumnWidth(table, 3, 75); + UIHelper.fixTableColumnWidth(table, 4, 20); + UIHelper.fixTableColumnWidth(table, 5, 50); + + UIHelper.setI18nTableHeaderRenderer( + table, + n("observe.content.targetDiscarded.table.speciesThon"), + n("observe.content.targetDiscarded.table.speciesThon.tip"), + n("observe.content.targetDiscarded.table.weightCategory"), + n("observe.content.targetDiscarded.table.weightCategory.tip"), + n("observe.content.targetDiscarded.table.reasonForDiscard"), + n("observe.content.targetDiscarded.table.reasonForDiscard.tip"), + n("observe.content.targetDiscarded.table.weight"), + n("observe.content.targetDiscarded.table.weight.tip"), + n("observe.content.targetDiscarded.table.broughtOnDeck"), + n("observe.content.targetDiscarded.table.broughtOnDeck.tip"), + n("observe.content.targetDiscarded.table.comment"), + n("observe.content.targetDiscarded.table.comment.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesDto.class)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, WeightCategoryDto.class)); + UIHelper.setTableColumnRenderer(table, 2, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, ReasonForDiscardDto.class)); + UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 4, UIHelper.newStringTableCellRenderer(renderer, 20, false)); + UIHelper.setTableColumnRenderer(table, 5, UIHelper.newStringTableCellRenderer(renderer, 10, true)); + } + + protected void onSpeciesChanged(TargetCatchDto bean, ReferentialReference<SpeciesDto> species) { + + ReferentialReference<WeightCategoryDto> weightCategory = null; + + List<ReferentialReference<WeightCategoryDto>> data; + + if (species == null) { + + // aucune espèce selectionnee, on vide simplement la liste des categories + // car il faut d'abord choisir une espèce puis une categorie + data = Collections.emptyList(); + + } else { + + // un espèce est selectionnee, on met a jour la liste des categories disponibles pour cette espèce + List<ReferentialReference<WeightCategoryDto>> availableCategories = buildWeightCategoryList(species); + + data = availableCategories; + + weightCategory = bean.getWeightCategory(); + + if (weightCategory != null && !availableCategories.contains(weightCategory)) { + weightCategory = null; + } + } + + // on met a jour le model de la liste des categories + BeanComboBox<ReferentialReference<WeightCategoryDto>> combo = getUi().getWeightCategory(); + combo.setData(data); + + // on selectionne la categorie retenue + combo.setSelectedItem(weightCategory); + } + + protected void onWeightCategoryChanged(TargetCatchDto bean, ReferentialReference<WeightCategoryDto> weightCategory) { + TargetDiscardCatchUI ui = getUi(); + + ReferentialReference<ReasonForDiscardDto> reasonForDiscard = null; + List<ReferentialReference<ReasonForDiscardDto>> data; + + if (weightCategory == null) { + // aucune categorie selectionnee, on vide simplement + // la liste des raison rejets car il faut d'abord choisir une + // espèce puis une categorie, puis une raison rejet + data = Collections.emptyList(); + + } else { + + // un categorie est selectionne, on met a jour la liste des raisons + // rejet disponible pour cette categorie + + reasonForDiscard = bean.getReasonForDiscard(); + + List<ReferentialReference<ReasonForDiscardDto>> reasonForDiscardList = buildReasonFordiscardList(weightCategory, reasonForDiscard); + + if (log.isDebugEnabled()) { + log.debug("new reasonForDiscard list " + reasonForDiscardList); + } + + data = reasonForDiscardList; + + if (reasonForDiscard != null && !reasonForDiscardList.contains(reasonForDiscard)) { + // on sélectionne la première raison rejet disponible + reasonForDiscard = null; + } + } + + BeanComboBox<ReferentialReference<ReasonForDiscardDto>> combo = ui.getReasonForDiscard(); + + // on met a jour le model de la liste des raison rejets + combo.setData(data); + + // on selectionne la raison rejet retenue + combo.setSelectedItem(reasonForDiscard); + } + + protected List<ReferentialReference<SpeciesDto>> buildSpeciesList(ReferentialReference<SpeciesDto> species, + ReferentialReference<WeightCategoryDto> weightCategory) { + + List<ReferentialReference<WeightCategoryDto>> weightCategoryList = getAllWeightCategories(); + + removeFullyUsedWeightCategories(weightCategoryList); + + if (weightCategory != null) { + weightCategoryList.add(weightCategory); + } + + Collection<ReferentialReference<SpeciesDto>> usedSpecies = Sets.newHashSet(); + for (ReferentialReference<WeightCategoryDto> cat : weightCategoryList) { + + Optional<ReferentialReference<SpeciesDto>> optionalSpecies = getWeightCategorySpecies(cat); + + if (optionalSpecies.isPresent()) { + usedSpecies.add(optionalSpecies.get()); + } + + } + + List<ReferentialReference<SpeciesDto>> result = Lists.newArrayList(usedSpecies); + weightCategoryList.clear(); + usedSpecies.clear(); + return result; + + } + + protected List<ReferentialReference<WeightCategoryDto>> buildWeightCategoryList(ReferentialReference<SpeciesDto> species) { + + Set<ReferentialReference<WeightCategoryDto>> allCategories = getModel().getReferentialReferences(TargetCatchDto.PROPERTY_WEIGHT_CATEGORY); + List<ReferentialReference<WeightCategoryDto>> weightCategoryList = WeightCategoryDtos.filterSpeciesWeightCategories(allCategories, species.getId()); + + // on filtre toutes les categories qui ont deja references sur toutes les raisons de rejet + removeFullyUsedWeightCategories(weightCategoryList); + + return weightCategoryList; + } + + @SuppressWarnings("unchecked") + protected List<ReferentialReference<ReasonForDiscardDto>> buildReasonFordiscardList(ReferentialReference<WeightCategoryDto> weightCategory, + ReferentialReference<ReasonForDiscardDto> reasonForDiscard) { + + ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto> model = getTableModel(); + Set<ReferentialReference<ReasonForDiscardDto>> reasonForDiscardSet = getModel().getReferentialReferences(TargetCatchDto.PROPERTY_REASON_FOR_DISCARD); + + List<ReferentialReference<ReasonForDiscardDto>> reasonForDiscardList = Lists.newArrayList(reasonForDiscardSet); + + // on filtre les raison rejet sur la categorie + for (int i = 0; i < model.getRowCount(); i++) { + TargetCatchDto c = model.getValueAt(i); + + if (model.getSelectedRow() != i + && c != null + && c.getReasonForDiscard() != null + && (reasonForDiscard == null || !reasonForDiscard.equals(c.getReasonForDiscard())) + && weightCategory.equals(c.getWeightCategory())) { + reasonForDiscardList.remove(c.getReasonForDiscard()); + } + } + + return reasonForDiscardList; + } + + protected List<ReferentialReference<WeightCategoryDto>> getAllWeightCategories() { + + Set<ReferentialReference<WeightCategoryDto>> weightCategorySet = getModel().getReferentialReferences(TargetCatchDto.PROPERTY_WEIGHT_CATEGORY); + List<ReferentialReference<WeightCategoryDto>> weightCategoryList = Lists.newArrayList(weightCategorySet); + return weightCategoryList; + + } + + protected void removeFullyUsedWeightCategories(List<ReferentialReference<WeightCategoryDto>> weightCategoryAvaillables) { + + ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto> model = getTableModel(); + + Set<ReferentialReference<ReasonForDiscardDto>> reasonForDiscardSet = getModel().getReferentialReferences(TargetCatchDto.PROPERTY_REASON_FOR_DISCARD); + + int nbReasonForDiscard = reasonForDiscardSet.size(); + + // on filtre toutes les weightCategory qui ont deja references toutes les raisons rejets + for (ReferentialReference<WeightCategoryDto> c : getWeightCategoryUsed(model)) { + Collection<ReferentialReference<ReasonForDiscardDto>> raisonUsed = getReasonForDiscardUsed(model, c); + if (raisonUsed.size() == nbReasonForDiscard) { + // toutes les raison de rejet epuisé pour cette categorie + weightCategoryAvaillables.remove(c); + } + } + } + + @Override + protected void doPersist(SetSeineTargetCatchDto bean) { + + SaveResultDto saveResult = getTargetCatchService().save(bean); + saveResult.toDto(bean); + + } + + + @Override + protected void loadEditBean(String beanId) { + Form<SetSeineTargetCatchDto> form = getTargetCatchService().loadForm(beanId, true); + loadReferentialReferenceSetsInModel(form); + getModel().setForm(form); + SetSeineTargetCatchDtos.copySetSeineTargetCatchDto(form.getObject(), getBean()); + } + + + @Override + protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { + + Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); + + switch (propertyName) { + + case ObjectSchoolEstimateDto.PROPERTY_SPECIES: { + + String speciesListId = ObserveSwingApplicationContext.get().getConfig().getSpeciesListSeineTargetCatchId(); + String tripSeineId = getDataContext().getSelectedTripSeineId(); + + TripSeineService tripSeineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripSeineService(); + result = (List) tripSeineService.getSpeciesByListAndTrip(tripSeineId, speciesListId); + + result = ReferentialReferences.filterEnabled(result); + + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + } + + break; + + } + + return result; + + } + + protected TargetCatchService getTargetCatchService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTargetCatchService(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetDiscardCatchUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetDiscardCatchUIModel.java new file mode 100644 index 0000000..9f950fc --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetDiscardCatchUIModel.java @@ -0,0 +1,98 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import fr.ird.observe.services.dto.referential.seine.WeightCategoryDto; +import fr.ird.observe.services.dto.seine.SetSeineTargetCatchDto; +import fr.ird.observe.services.dto.seine.TargetCatchDto; +import fr.ird.observe.services.dto.seine.TargetCatchDtos; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; + +import java.util.Collection; +import java.util.List; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class TargetDiscardCatchUIModel extends ContentTableUIModel<SetSeineTargetCatchDto, TargetCatchDto> { + + private static final long serialVersionUID = 1L; + + public TargetDiscardCatchUIModel(TargetDiscardCatchUI ui) { + + super(SetSeineTargetCatchDto.class, + TargetCatchDto.class, + new String[]{ + SetSeineTargetCatchDto.PROPERTY_DISCARDED, + SetSeineTargetCatchDto.PROPERTY_TARGET_CATCH}, + new String[]{ + TargetCatchDto.PROPERTY_WEIGHT_CATEGORY, + TargetCatchDto.PROPERTY_CATCH_WEIGHT, + TargetCatchDto.PROPERTY_REASON_FOR_DISCARD, + TargetCatchDto.PROPERTY_DISCARDED, + TargetCatchDto.PROPERTY_BROUGHT_ON_DECK, + TargetCatchDto.PROPERTY_COMMENT}); + + List<ContentTableMeta<TargetCatchDto>> metas = Lists.newArrayList( + ContentTableModel.newTableMeta(TargetCatchDto.class, WeightCategoryDto.PROPERTY_SPECIES, true), + ContentTableModel.newTableMeta(TargetCatchDto.class, TargetCatchDto.PROPERTY_WEIGHT_CATEGORY, true), + ContentTableModel.newTableMeta(TargetCatchDto.class, TargetCatchDto.PROPERTY_REASON_FOR_DISCARD, true), + ContentTableModel.newTableMeta(TargetCatchDto.class, TargetCatchDto.PROPERTY_CATCH_WEIGHT, false), + ContentTableModel.newTableMeta(TargetCatchDto.class, TargetCatchDto.PROPERTY_BROUGHT_ON_DECK, false), + ContentTableModel.newTableMeta(TargetCatchDto.class, TargetCatchDto.PROPERTY_COMMENT, false)); + + initModel(ui, metas); + + } + + @Override + protected ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto> createTableModel( + ObserveContentTableUI<SetSeineTargetCatchDto, TargetCatchDto> ui, + List<ContentTableMeta<TargetCatchDto>> contentTableMetas) { + + return new ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto>(ui, contentTableMetas) { + private static final long serialVersionUID = 1L; + @Override + protected Collection<TargetCatchDto> getChilds(SetSeineTargetCatchDto bean) { + return bean.getTargetCatch(); + } + + @Override + protected void load(TargetCatchDto source, TargetCatchDto target) { + TargetCatchDtos.copyTargetCatchDto(source, target); + } + + @Override + protected void setChilds(SetSeineTargetCatchDto parent, List<TargetCatchDto> childs) { + bean.setTargetCatch(childs); + } + }; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetSampleCaptureUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetSampleCaptureUI.jaxx similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetSampleCaptureUI.jaxx rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetSampleCaptureUI.jaxx diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetSampleCaptureUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetSampleCaptureUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetSampleCaptureUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetSampleCaptureUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetSampleRejeteUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetSampleRejeteUI.jaxx similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetSampleRejeteUI.jaxx rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetSampleRejeteUI.jaxx diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetSampleRejeteUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetSampleRejeteUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetSampleRejeteUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetSampleRejeteUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetSampleUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetSampleUI.jaxx new file mode 100644 index 0000000..9361e11 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetSampleUI.jaxx @@ -0,0 +1,185 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<fr.ird.observe.application.swing.ui.content.table.ContentTableUI + superGenericType='TargetSampleDto, TargetLengthDto' + abstract="true"> + + <style source="AbstractSampleUI.jcss"/> + + <import> + fr.ird.observe.services.dto.seine.TargetSampleDto + fr.ird.observe.services.dto.seine.TargetLengthDto + fr.ird.observe.application.swing.ui.content.table.impl.seine.CodeMesureEnum + fr.ird.observe.application.swing.ui.content.table.impl.seine.ModeSaisieEchantillonEnum + fr.ird.observe.services.dto.referential.ReferentialReference + fr.ird.observe.services.dto.referential.SpeciesDto + fr.ird.observe.application.swing.ui.content.table.* + + jaxx.runtime.swing.editor.NumberEditor + jaxx.runtime.swing.editor.bean.BeanComboBox + + java.awt.Dimension + + static fr.ird.observe.application.swing.ui.UIHelper.getStringValue + static org.nuiton.i18n.I18n.n + </import> + + <!-- handler --> + <TargetSampleUIHandler id='handler' initializer='null'/> + + <!-- model --> + <TargetSampleUIModel id='model' constructorParams='this'/> + + <!-- edit bean --> + <TargetSampleDto id='bean'/> + + <!-- table edit bean --> + <TargetLengthDto id='tableEditBean'/> + + <!-- table model --> + <ContentTableModel id='tableModel'/> + + <!-- le validateur de l'écran --> + <BeanValidator id='validator' + beanClass='fr.ird.observe.services.dto.seine.TargetSampleDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update'> + <!-- clef unique --> + <field name="targetLength" component="editorPanel"/> + <field name='comment'/> + </BeanValidator> + + <!-- le validateur d'une entrée de tableau --> + <BeanValidator id='validatorTable' + autoField='true' + beanClass='fr.ird.observe.services.dto.seine.TargetLengthDto' + errorTableModel='{getErrorTableModel()}' + context='ui-update' + parentValidator='{validator}'/> + + <ButtonGroup id='acquisitionModeGroup' + onStateChanged='getHandler().updateModeSaisie((ModeSaisieEchantillonEnum) acquisitionModeGroup.getSelectedValue())'/> + + <script><![CDATA[ + +public static final String POIDS_COMPUTED_TIP = n("observe.common.weight.computed.tip"); +public static final String POIDS_OBSERVED_TIP = n("observe.common.weight.observed.tip"); +public static final String LONGUEUR_COMPUTED_TIP = n("observe.common.length.computed.tip"); +public static final String LONGUEUR_OBSERVED_TIP = n("observe.common.length.observed.tip"); + +public String getWeightDataTip(boolean computed) { + return computed ? t(POIDS_COMPUTED_TIP) : t(POIDS_OBSERVED_TIP); +} + +public String getLengthDataTip(boolean computed) { + return computed ? t(LONGUEUR_COMPUTED_TIP) : t(LONGUEUR_OBSERVED_TIP); +} +]]> + </script> + <Table id='editorPanel' fill='both' insets='1'> + + <!-- mode de saisie --> + <row> + <cell columns="3"> + <JPanel id="modeAndCodePanel"> + <JPanel id='acquisitionModePanel' constraints="BorderLayout.CENTER"> + <JRadioButton id='acquisitionModeEffectif'/> + <JRadioButton id='acquisitionModeIndividu'/> + </JPanel> + <JPanel id='measureTypePanel' layout='{new BorderLayout()}'> + <EnumEditor id='measureType' + constraints="BorderLayout.CENTER" + constructorParams='CodeMesureEnum.class' + genericType='CodeMesureEnum' + onItemStateChanged='getTableEditBean().setMeasureType(measureType.getSelectedIndex())'/> + </JPanel> + </JPanel> + </cell> + </row> + + <!-- species thon --> + <row> + <cell> + <JLabel id='speciesLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <BeanComboBox id='species' genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class' constructorParams='this'/> + </cell> + </row> + + <!-- length --> + <row> + <cell> + <JLabel id='lengthLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='length' constructorParams='this'/> + </cell> + <cell anchor='east'> + <JToolBar id='lengthSourceAction'> + <JButton id='lengthSourceInformation' + onActionPerformed='getHandler().resetLengthSource()'/> + </JToolBar> + </cell> + </row> + + <!-- weight individuel --> + <row> + <cell> + <JLabel id='weightLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='weight' constructorParams='this'/> + </cell> + <cell anchor='east'> + <JToolBar id='weightSourceAction'> + <JButton id='weightSourceInformation' + onActionPerformed='getHandler().resetWeightSource()'/> + </JToolBar> + </cell> + </row> + + <!-- count --> + <row> + <cell> + <JLabel id='countLabel'/> + </cell> + <cell weightx='1' anchor='east'> + <NumberEditor id='count' constructorParams='this'/> + </cell> + </row> + </Table> + + <Table id='extraZone' fill='both' weightx='1' insets='0'> + <row> + <cell weighty='1'> + <JScrollPane id='comment' + onFocusGained='comment2.requestFocus()'> + <JTextArea id='comment2' + onKeyReleased='getBean().setComment(comment2.getText())'/> + </JScrollPane> + </cell> + </row> + </Table> + +</fr.ird.observe.application.swing.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetSampleUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetSampleUI.jcss new file mode 100644 index 0000000..ccd5f18 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetSampleUI.jcss @@ -0,0 +1,87 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +#speciesLabel { + text:"observe.common.speciesThon"; +} + +#modeAndCodePanel { + layout:{new GridLayout(1,0)}; +} + +#acquisitionModeGroup { + selectedValue:{ModeSaisieEchantillonEnum.valueOf(tableEditBean.getAcquisitionMode())}; +} + +#acquisitionModePanel { + border:{new TitledBorder(t("observe.common.acquisitionMode"))}; + layout:{new GridLayout(0,1)}; +} + +#measureTypePanel { + border:{new TitledBorder(t("observe.common.measureType"))}; +} + +#measureType { + selectedIndex:{tableEditBean.getMeasureType()}; +} + +#acquisitionModeEffectif { + buttonGroup:"acquisitionModeGroup"; + value:{ModeSaisieEchantillonEnum.byEffectif}; + text:{ModeSaisieEchantillonEnum.byEffectif.getI18nKey()}; + selected:{tableEditBean.getAcquisitionMode() == 0}; + enabled:{!tableModel.isEditable() || tableModel.isCreate()}; + /*enabled:{!tableModel.isEditable() || !model.isRowSaved()};*/ +} + +#acquisitionModeIndividu { + buttonGroup:"acquisitionModeGroup"; + value:{ModeSaisieEchantillonEnum.byIndividu}; + text:{ModeSaisieEchantillonEnum.byIndividu.getI18nKey()}; + selected:{tableEditBean.getAcquisitionMode() == 1}; + enabled:{!tableModel.isEditable() || tableModel.isCreate()}; + /*enabled:{!tableModel.isEditable() || !model.isRowSaved()};*/ +} + +#lengthLabel { + text:"observe.common.length.inf"; +} + +#length { + _validatorLabel:{"observe.common.length.inf"}; +} + +#countLabel { + text:"observe.common.count"; + labelFor:{count}; +} + +#count { + property:"count"; + model:{tableEditBean.getCount()}; + numberPattern:{fr.ird.observe.application.swing.ui.UIHelper.INT_6_DIGITS_PATTERN}; +} + +#comment { + columnHeaderView:{new JLabel(t("observe.common.comment.targetSample"))}; +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetSampleUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetSampleUIHandler.java new file mode 100644 index 0000000..b70a0b1 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetSampleUIHandler.java @@ -0,0 +1,354 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.constants.DataContextType; +import fr.ird.observe.services.dto.Form; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.referential.SpeciesDto; +import fr.ird.observe.services.dto.result.SaveResultDto; +import fr.ird.observe.services.dto.seine.SetSeineDto; +import fr.ird.observe.services.dto.seine.TargetLengthDto; +import fr.ird.observe.services.dto.seine.TargetSampleDto; +import fr.ird.observe.services.dto.seine.TargetSampleDtos; +import fr.ird.observe.services.service.seine.TargetSampleService; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.content.ContentMode; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUI; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIHandler; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.JComponent; +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; +import java.beans.PropertyChangeListener; +import java.util.Collection; +import java.util.LinkedList; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class TargetSampleUIHandler extends ContentTableUIHandler<TargetSampleDto, TargetLengthDto> { + + /** Logger */ + private static final Log log = LogFactory.getLog(TargetSampleUIHandler.class); + + /** + * Pour différencier positionner l'invariant de l'écran + * {@link TargetSampleDto#getDiscarded()}. + * + * @since 1.5 + */ + protected final boolean discarded; + + /** + * Ecoute les modifications de la propriété {@link TargetLengthDto#getWeight()}, + * et repasser alors le flag {@link TargetLengthDto#isWeightSource()} à + * {@code false}. + * + * @since 3.0 + */ + protected final PropertyChangeListener weightChanged; + + /** + * Ecoute les modifications de la propriété {@link TargetLengthDto#getLength()}, + * et repasser alors le flag {@link TargetLengthDto#isLengthSource()} à + * {@code false}. + * + * @since 3.0 + */ + protected final PropertyChangeListener lengthChanged; + + public TargetSampleUIHandler(ContentTableUI<TargetSampleDto, TargetLengthDto> ui, + boolean discarded) { + super(ui, DataContextType.SetSeine); + this.discarded = discarded; + weightChanged = evt -> { + TargetLengthDto source = (TargetLengthDto) evt.getSource(); + source.setWeightSource(false); + }; + lengthChanged = evt -> { + TargetLengthDto source = (TargetLengthDto) evt.getSource(); + source.setLengthSource(false); + }; + } + + @Override + public TargetSampleUI getUi() { + return (TargetSampleUI) super.getUi(); + } + + public void resetWeightSource() { + getTableEditBean().setWeightSource(false); + getUi().getWeight().grabFocus(); + } + + public void resetLengthSource() { + getTableEditBean().setLengthSource(false); + getUi().getLength().grabFocus(); + } + + @Override + protected String getEditBeanIdToLoad() { + String id = getDataContext().getSelectedSetId(); + return id; + } + + protected void onSelectedRowChanged(int editingRow, TargetLengthDto bean, boolean create) { + + ContentTableModel<TargetSampleDto, TargetLengthDto> model = getTableModel(); + TargetSampleUI ui = getUi(); + if (!model.isEditable()) { + return; + } + + ReferentialReference<SpeciesDto> species = bean.getSpecies(); + + JComponent requestFocus; + + if (create) { + +// if (model.isCreate() && editingRow > 0) { + if (model.isCreate()) { + + if (editingRow > 0) { + // on recupere l'species de la ligne precedente + TargetLengthDto editBean = model.getValueAt(editingRow - 1); + species = editBean.getSpecies(); + } + + // on passe le mode de saisie en count + ui.getAcquisitionModeGroup().setSelectedValue(null); + ui.getAcquisitionModeGroup().setSelectedValue(ModeSaisieEchantillonEnum.byEffectif); + + // on utilise par défaut le code mesure lf + ui.getMeasureType().setSelectedItem(null); + ui.getMeasureType().setSelectedItem(CodeMesureEnum.lf); + } + + requestFocus = ui.getSpecies(); + + } else { + + requestFocus = ui.getCount(); + + // on passe le mode de saisie + int acquisitionMode = bean.getAcquisitionMode(); + ModeSaisieEchantillonEnum enumValue = + ModeSaisieEchantillonEnum.valueOf(acquisitionMode); + ui.getAcquisitionModeGroup().setSelectedValue(null); + ui.getAcquisitionModeGroup().setSelectedValue(enumValue); + } + + // on met a jour l'espce + ui.getSpecies().setSelectedItem(null); + + if (species != null) { + if (log.isDebugEnabled()) { + log.debug("species to use " + species); + } + ui.getSpecies().setSelectedItem(species); + } + requestFocus.requestFocus(); + + TargetLengthDto tableEditBean = getTableEditBean(); + tableEditBean.removePropertyChangeListener(TargetLengthDto.PROPERTY_WEIGHT, weightChanged); + tableEditBean.addPropertyChangeListener(TargetLengthDto.PROPERTY_WEIGHT, weightChanged); + + tableEditBean.removePropertyChangeListener(TargetLengthDto.PROPERTY_LENGTH, lengthChanged); + tableEditBean.addPropertyChangeListener(TargetLengthDto.PROPERTY_LENGTH, lengthChanged); + } + + @Override + protected void initTableUI(DefaultTableCellRenderer renderer) { + + JTable table = getUi().getTable(); + + UIHelper.setI18nTableHeaderRenderer( + table, + n("observe.content.targetSample.table.speciesThon"), + n("observe.content.targetSample.table.speciesThon.tip"), + n("observe.content.targetSample.table.measureType"), + n("observe.content.targetSample.table.measureType.tip"), + n("observe.content.targetSample.table.length"), + n("observe.content.targetSample.table.length.tip"), + n("observe.content.targetSample.table.meanWeight"), + n("observe.content.targetSample.table.meanWeight.tip"), + n("observe.content.targetSample.table.count"), + n("observe.content.targetSample.table.count.tip"), + n("observe.content.targetSample.table.totalWeight"), + n("observe.content.targetSample.table.totalWeight.tip")); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesDto.class)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEnumTableCellRenderer(renderer, CodeMesureEnum.class)); + UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 4, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 5, UIHelper.newEmptyNumberTableCellRenderer(renderer)); + } + + @Override + protected ContentMode getContentMode(DataContext dataContext) { + ContentMode mode = super.getContentMode(dataContext); + + String setId = dataContext.getSelectedSetId(); + + boolean showData = getTargetSampleService().canUseTargetSample(setId, discarded); + + getModel().setShowData(showData); + + if (mode == ContentMode.UPDATE && !showData) { + + mode = ContentMode.READ; + + addMessage(getUi(), + NuitonValidatorScope.INFO, + getEntityLabel(SetSeineDto.class), + discarded ? + t("observe.content.setSeine.message.no.targetCatch") : + t("observe.content.setSeine.message.no.targetDiscarded") + ); + } + return mode; + } + + /** + * Le mode de saisie a été mis à jour. + * + * @param newMode le nouveau de mode de saisie à utiliser + * @since 1.8 + */ + public void updateModeSaisie(ModeSaisieEchantillonEnum newMode) { + + if (log.isDebugEnabled()) { + log.debug("Change mode saisie to " + newMode); + } + if (newMode == null) { + + // mode null (cela peut arriver avec les bindings) + return; + } + + TargetSampleUI ui = getUi(); + + boolean createMode = ui.getTableModel().isCreate(); + + TargetLengthDto editBean = ui.getTableEditBean(); + switch (newMode) { + + case byEffectif: + + // le weight n'est pas modifiable + ui.getWeight().setEnabled(false); + + // l'count est modifiable + ui.getCount().setEnabled(true); + + if (createMode) { + + // on supprime le weight (si il a été saisie) + editBean.setWeight(null); + // on supprime aussi l'count (pour forcer la saisie) + editBean.setCount(null); + } + break; + + case byIndividu: + + // le weight est pas modifiable + ui.getWeight().setEnabled(true); + + // l'count n'est pas modifiable et est toujours de 1 + ui.getCount().setEnabled(false); + + + if (createMode) { + + // on positionne l'count à 1 (seule valeur possible) + editBean.setCount(1); + } + break; + } + + if (createMode) { + + // on propage le mode de saisie dans le bean + editBean.setAcquisitionMode(newMode.ordinal()); + } + } + + @Override + protected void doPersist(TargetSampleDto bean) { + + SaveResultDto saveResult = getTargetSampleService().save(getSelectedParentId(), bean); + saveResult.toDto(bean); + + } + + @Override + protected void loadEditBean(String beanId) { + Form<TargetSampleDto> form = getTargetSampleService().loadForm(beanId, discarded); + loadReferentialReferenceSetsInModel(form); + getModel().setForm(form); + TargetSampleDtos.copyTargetSampleDto(form.getObject(), getBean()); + } + + @Override + protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { + + Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); + + switch (propertyName) { + + case TargetLengthDto.PROPERTY_SPECIES: { + + result = (List) getTargetSampleService().getSampleSpecies(getSelectedParentId(), discarded); + + if (log.isDebugEnabled()) { + log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); + } + + } + + break; + + } + + return result; + + } + + protected TargetSampleService getTargetSampleService() { + return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTargetSampleService(); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetSampleUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetSampleUIModel.java new file mode 100644 index 0000000..b908f40 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/impl/seine/TargetSampleUIModel.java @@ -0,0 +1,99 @@ +package fr.ird.observe.application.swing.ui.content.table.impl.seine; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import fr.ird.observe.services.dto.seine.TargetLengthDto; +import fr.ird.observe.services.dto.seine.TargetLengthDtos; +import fr.ird.observe.services.dto.seine.TargetSampleDto; +import fr.ird.observe.application.swing.ui.content.table.ContentTableMeta; +import fr.ird.observe.application.swing.ui.content.table.ContentTableModel; +import fr.ird.observe.application.swing.ui.content.table.ContentTableUIModel; +import fr.ird.observe.application.swing.ui.content.table.ObserveContentTableUI; + +import java.util.Collection; +import java.util.List; + +/** + * Created on 9/26/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since XXX + */ +public class TargetSampleUIModel extends ContentTableUIModel<TargetSampleDto, TargetLengthDto> { + + private static final long serialVersionUID = 1L; + + public TargetSampleUIModel(TargetSampleUI ui) { + + super(TargetSampleDto.class, + TargetLengthDto.class, + new String[]{ + TargetSampleDto.PROPERTY_TARGET_LENGTH, + TargetSampleDto.PROPERTY_COMMENT}, + new String[]{ + TargetLengthDto.PROPERTY_SPECIES, + TargetLengthDto.PROPERTY_LENGTH, + TargetLengthDto.PROPERTY_LENGTH_SOURCE, + TargetLengthDto.PROPERTY_WEIGHT, + TargetLengthDto.PROPERTY_WEIGHT_SOURCE, + TargetLengthDto.PROPERTY_COUNT, + TargetLengthDto.PROPERTY_MEASURE_TYPE, + TargetLengthDto.PROPERTY_ACQUISITION_MODE}); + + List<ContentTableMeta<TargetLengthDto>> metas = Lists.newArrayList( + ContentTableModel.newTableMeta(TargetLengthDto.class, TargetLengthDto.PROPERTY_SPECIES, true), + ContentTableModel.newTableMeta(TargetLengthDto.class, TargetLengthDto.PROPERTY_MEASURE_TYPE, true), + ContentTableModel.newTableMeta(TargetLengthDto.class, TargetLengthDto.PROPERTY_LENGTH, true), + ContentTableModel.newTableMeta(TargetLengthDto.class, TargetLengthDto.PROPERTY_WEIGHT, true), + ContentTableModel.newTableMeta(TargetLengthDto.class, TargetLengthDto.PROPERTY_COUNT, false), + ContentTableModel.newTableMeta(TargetLengthDto.class, TargetLengthDto.PROPERTY_TOTAL_WEIGHT, true)); + + initModel(ui, metas); + + } + + @Override + protected ContentTableModel<TargetSampleDto, TargetLengthDto> createTableModel( + ObserveContentTableUI<TargetSampleDto, TargetLengthDto> ui, + List<ContentTableMeta<TargetLengthDto>> contentTableMetas) { + return new ContentTableModel<TargetSampleDto, TargetLengthDto>(ui, contentTableMetas) { + private static final long serialVersionUID = 1L; + @Override + protected Collection<TargetLengthDto> getChilds(TargetSampleDto bean) { + return bean.getTargetLength(); + } + + @Override + protected void load(TargetLengthDto source, TargetLengthDto target) { + TargetLengthDtos.copyTargetLengthDto(source, target); + } + + @Override + protected void setChilds(TargetSampleDto parent, List<TargetLengthDto> childs) { + parent.setTargetLength(Sets.newLinkedHashSet(childs)); + } + }; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/package.html b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/package.html similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/package.html rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/content/table/package.html diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/package.html b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/package.html similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/package.html rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/package.html diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/ObstunaAdminAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/ObstunaAdminAction.java new file mode 100644 index 0000000..3165c18 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/ObstunaAdminAction.java @@ -0,0 +1,352 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.storage; + +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableSet; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.db.constants.DbMode; +import fr.ird.observe.services.configuration.ObserveDataSourceConfiguration; +import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationRest; +import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaPG; +import fr.ird.observe.services.configuration.ObserveDataSourceInformation; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.DataSourceCreateConfigurationDto; +import fr.ird.observe.services.dto.ObserveDbUserDto; +import fr.ird.observe.services.service.BabModelVersionException; +import fr.ird.observe.services.service.DatabaseConnexionNotAuthorizedException; +import fr.ird.observe.services.service.DatabaseNotFoundException; +import fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel; +import jaxx.runtime.JAXXContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.version.Version; +import org.nuiton.version.Versions; + +import java.awt.Window; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Les différents types d'actions d'administration possible sur une base + * distante. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public enum ObstunaAdminAction { + + /** + * pour créer une nouvelle base obstuna. + * + * Il faut au préalable avoir exécuté le script {@code create-obstuna_v2.sh}. + */ + CREATE(n("observe.obstuna.action.create"), + n("observe.obstuna.action.create.description"), + null) { + @Override + public RemoteUILauncher newLauncher(JAXXContext context, Window frame) { + return new RemoteUILauncher(this, context, frame, t(getLabel())) { + + protected DataSourceCreateConfigurationDto createConfigurationDto; + protected ObserveSwingDataSource dataSource; + protected Set<ObserveDbUserDto> users; + + @Override + protected void init(StorageUI ui) { + StorageUIModel model = ui.getModel(); + + // on autorise le mode de creation import referentiel + // depuis une source distante + model.getPgConfig().setCanMigrate(true); + super.init(ui); + } + + protected void checkImportDbVersion(StorageUIModel model, ObserveDataSourceConfiguration dataSourceConfig) throws DatabaseConnexionNotAuthorizedException, DatabaseNotFoundException, BabModelVersionException { + + ObserveSwingDataSource importDataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(dataSourceConfig); + + Preconditions.checkState(importDataSource != null, "Can't select data on a null dataSource"); + + try { + + importDataSource.open(); + + model.checkImportDbVersion(importDataSource); + + } finally { + + importDataSource.close(); + } + + } + + protected void initTask(StorageUIModel model) throws Exception { + + if (DbMode.USE_REMOTE.equals(model.getDbMode())) { + ObserveDataSourceConfigurationTopiaPG pgConfig = model.getPgConfig(); + + // pas autorise a migrer automatiquement + pgConfig.setCanMigrate(false); + + dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(pgConfig); + } else { + ObserveDataSourceConfigurationRest restConfig = model.getRestConfig(); + + dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(restConfig); + } + + createConfigurationDto = model.toImportReferentielSourceConfig(); + + ObserveDataSourceConfiguration importReferentialConfig = createConfigurationDto.getImportReferentialDataSourceConfiguration(); + + + if (importReferentialConfig != null) { + + if (log.isInfoEnabled()) { + log.info("Use referentiel import data source " + importReferentialConfig.getLabel()); + } + + checkImportDbVersion(model, importReferentialConfig); + + } + + // data import + + ObserveSwingDataSource importDataConfig = model.toImportDataSourceConfig(); + + if (importDataConfig != null) { + + if (log.isInfoEnabled()) { + log.info("Use data import data source " + importDataConfig.getLabel()); + } + + checkImportDbVersion(model, importDataConfig.getConfiguration()); + + DataSelectionModel dataModel = model.getSelectDataModel(); + + ImmutableSet<String> importDataIds = ImmutableSet.copyOf( + dataModel.getSelectedData() + .stream() + .map(DataReference::getId) + .collect(Collectors.toSet())); + + createConfigurationDto.setImportDataConfiguration(importDataConfig.getConfiguration(), importDataIds); + } + + users = model.getSecurityModel().getUsers(); + + super.initTask(model); + } + + @Override + protected String getPgLabel() { + return t("observe.storage.label.db.to.create"); + } + + @Override + protected void execute() throws Exception { + if (log.isInfoEnabled()) { + log.info("Create db..."); + } + + try { + dataSource.create(createConfigurationDto); + + if (log.isInfoEnabled()) { + log.info("Open [" + dataSource.getLabel() + "] and create it."); + } + + } finally { + if (dataSource.isOpen()) { + dataSource.close(); + } + } + } + + @Override + protected void applySecurity() { + if (log.isInfoEnabled()) { + log.info("Apply security..."); + } + dataSource.applySecurity(users); + } + }; + } + }, + /** + * pour mettre à jour une base distante. + * + * Il faut au préalable avoir une base en version {@code 1.0}. + */ + UPDATE(n("observe.obstuna.action.update"), + n("observe.obstuna.action.update.description"), + Versions.valueOf("1.0")) { + @Override + public RemoteUILauncher newLauncher(JAXXContext context, Window frame) { + return new RemoteUILauncher(this, context, frame, t(getLabel())) { + + protected ObserveSwingDataSource dataSource; + protected ObserveDataSourceInformation dataSourceInformation; + protected Version targetVersion; + protected Set<ObserveDbUserDto> users; + + @Override + protected void initTask(StorageUIModel model) throws Exception { + + if (DbMode.USE_REMOTE.equals(model.getDbMode())) { + ObserveDataSourceConfigurationTopiaPG pgConfig = model.getPgConfig(); + + dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(pgConfig); + + } else { + + ObserveDataSourceConfigurationRest restConfig = model.getRestConfig(); + + dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(restConfig); + } + + targetVersion = ObserveSwingApplicationContext.get().getConfig().getModelVersion(); + + users = model.getSecurityModel().getUsers(); + + dataSourceInformation = model.getDataSourceInformation(); + + } + + @Override + protected void execute() throws Exception { + + dataSource.migrateData(dataSourceInformation, targetVersion); + } + + @Override + protected String getPgLabel() { + return t("observe.storage.label.db.to.update"); + } + + @Override + protected void applySecurity() { + if (log.isInfoEnabled()) { + log.info("Apply security..."); + } + dataSource.applySecurity(users); + } + }; + } + }, + /** + * pour mettre à jour la sécurité d'une base obstuna. + * + * Il faut au préalable avoir une base en version {@code 1.4}. + */ + SECURITY(n("observe.obstuna.action.security"), + n("observe.obstuna.action.security.description"), + Versions.valueOf("1.4")) { + @Override + public RemoteUILauncher newLauncher(JAXXContext context, Window frame) { + return new RemoteUILauncher(this, context, frame, t(getLabel())) { + + protected ObserveSwingDataSource dataSource; + protected Set<ObserveDbUserDto> users; + + @Override + protected void initTask(StorageUIModel model) throws Exception { + + if (DbMode.USE_REMOTE.equals(model.getDbMode())) { + ObserveDataSourceConfigurationTopiaPG pgConfig = model.getPgConfig(); + + // pas autorise a migrer automatiquement + pgConfig.setCanMigrate(false); + + dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(pgConfig); + } else { + ObserveDataSourceConfigurationRest restConfig = model.getRestConfig(); + + dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(restConfig); + } + + users = model.getSecurityModel().getUsers(); + + } + + @Override + protected String getPgLabel() { + return t("observe.storage.label.db.to.update.security"); + } + + @Override + protected void applySecurity() { + if (log.isInfoEnabled()) { + log.info("Apply security..."); + } + dataSource.applySecurity(users); + } + }; + } + }; + + /** Logger */ + private static final Log log = LogFactory.getLog(ObstunaAdminAction.class); + + private final String label; + + private final String description; + + private final Version requiredVersion; + + ObstunaAdminAction(String label, + String description, + Version requiredVersion) { + this.label = label; + this.description = description; + this.requiredVersion = requiredVersion; + } + + public String getLabel() { + return label; + } + + public String getDescription() { + return description; + } + + public Version getRequiredVersion() { + return requiredVersion; + } + + public static ObstunaAdminAction valueOfIgnoreCase(String value) { + for (ObstunaAdminAction step : ObstunaAdminAction.values()) { + if (step.name().equalsIgnoreCase(value)) { + return step; + } + } + return null; + } + + public abstract RemoteUILauncher newLauncher(JAXXContext context, + Window frame); +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/RemoteUILauncher.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/RemoteUILauncher.java new file mode 100644 index 0000000..cc0ee4f --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/RemoteUILauncher.java @@ -0,0 +1,142 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.storage; + +import fr.ird.observe.application.swing.db.constants.DbMode; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.storage.tabs.SecurityModel; +import jaxx.runtime.JAXXContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.awt.Window; +import java.util.ArrayList; +import java.util.List; + +/** + * Un wizard pour effectuer des opération de création ou mise à jour d'une + * base distante. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public abstract class RemoteUILauncher extends StorageUILauncher { + + /** Logger */ + private static final Log log = LogFactory.getLog(RemoteUILauncher.class); + + protected ObstunaAdminAction action; + + public RemoteUILauncher(ObstunaAdminAction action, + JAXXContext context, + Window frame, + String title) { + super(context, frame, title); + this.action = action; + } + + @Override + protected void init(StorageUI ui) { + super.init(ui); + + StorageUIModel model = ui.getModel(); + model.setCanCreateLocalService(false); + model.setCanUseLocalService(false); + model.setCanUseRemoteService(true); + model.setCanUseServerService(true); + model.setDbMode(DbMode.USE_REMOTE); + model.setAdminAction(action); + + List<StorageStep> steps = new ArrayList<>(); + steps.add(StorageStep.CONFIG); + + if (action == ObstunaAdminAction.CREATE) { + + // configuration de l'import de référentiel + steps.add(StorageStep.CONFIG_REFERENTIEL); + + // configuration de l'import de données + steps.add(StorageStep.CONFIG_DATA); + + // choix des données à importer + steps.add(StorageStep.SELECT_DATA); + + } + steps.add(StorageStep.ROLES); + steps.add(StorageStep.CONFIRM); + + model.setSteps(steps.toArray(new StorageStep[steps.size()])); + ui.setSize(800, 600); + } + + @Override + protected void doAction(StorageUI ui) { + super.doAction(ui); + StorageUIModel model = ui.getModel(); + SecurityModel securityModel = model.getSecurityModel(); + if (log.isInfoEnabled()) { + log.info("Will use security model " + securityModel); + } + + try { + + initTask(model); + } catch (Exception e) { + UIHelper.handlingError("Could not init task.", e); + throw new RuntimeException(e); + } + + try { + execute(); + + } catch (Exception e) { + UIHelper.handlingError("Could not create db.", e); + throw new RuntimeException(e); + } + + try { + applySecurity(); + } catch (Exception e) { + UIHelper.handlingError("Could not apply security to db.", e); + throw new RuntimeException(e); + } + } + +// @Override +// protected void doClose(StorageUI ui, boolean wasCanceld) { +// super.doClose(ui, wasCanceld); +// ui.setVisible(false); +// } + + protected abstract String getPgLabel(); + + protected void initTask(StorageUIModel model) throws Exception { + // FIXME + // task.init(model.toPostgresStorageConfig(getPgLabel()), model.getSecurityModel(), false); + } + + protected void execute() throws Exception { + } + + protected void applySecurity() { + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/StorageBackupUILauncher.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/StorageBackupUILauncher.java new file mode 100644 index 0000000..9fcfe94 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/StorageBackupUILauncher.java @@ -0,0 +1,119 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.storage; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.db.constants.DbMode; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel; +import jaxx.runtime.JAXXContext; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.awt.Window; +import java.io.File; +import java.util.Set; + +/** + * Un wizard pour effectuer des backup de storages. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.2 + */ +public class StorageBackupUILauncher extends StorageUILauncher { + + + /** + * Logger + */ + private static final Log log = LogFactory.getLog(StorageBackupUILauncher.class); + + public StorageBackupUILauncher(JAXXContext context, + Window frame, + String title) { + super(context, frame, title); + } + + @Override + protected void init(StorageUI ui) { + super.init(ui); + ui.getBACKUP().getDoBackup().setSelected(true); + ui.getBACKUP().getDoBackup().setVisible(false); + + ObserveSwingDataSource source = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); + + StorageUIModel model = ui.getModel(); + model.setCanCreateLocalService(false); + + if (source.isLocal()) { + model.setCanUseLocalService(true); + model.setDbMode(DbMode.USE_LOCAL); + } else if (source.isRemote()) { + model.setCanUseRemoteService(true); + model.setDbMode(DbMode.USE_REMOTE); + } else if (source.isServer()) { + model.setCanUseServerService(true); + model.setDbMode(DbMode.USE_SERVER); + } + + model.setSteps(StorageStep.BACKUP, + StorageStep.SELECT_DATA, + StorageStep.CONFIRM + ); + ui.setTitle(title); + try { + + // Selection des données uniquement pour une base locale + // Voir https://forge.codelutin.com/issues/7207 + boolean selectAllData = model.isLocal(); + getStorageUIHandler().initSelectData(ui, source, selectAllData); + + } catch (Exception e) { + if (log.isErrorEnabled()) { + log.error(e, e); + } + } + } + + @Override + protected void doAction(StorageUI ui) { + super.doAction(ui); + StorageUIHandler handler = getStorageUIHandler(); + + ObserveSwingDataSource source = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); + + StorageUIModel storageModel = ui.getModel(); + File backupFile = storageModel.getBackupFile(); + + DataSelectionModel dataModel = storageModel.getSelectDataModel(); + Set<DataReference> trips = null; + if (dataModel != null && !dataModel.isDataFull()) { + // on renseigne les marees a exporter uniquement si + // on en a selectionner, de plus si on a selectionne + // toutes les marees, on le les passe pas : car c un dump + // complet de la base. + trips = dataModel.getSelectedData(); + } + handler.backupLocalDatabase(source, backupFile, trips); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/StorageStep.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/StorageStep.java new file mode 100644 index 0000000..1917fea --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/StorageStep.java @@ -0,0 +1,113 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.storage; + +import jaxx.runtime.swing.wizard.WizardStep; + +import static org.nuiton.i18n.I18n.n; + +/** + * Pour caractériser les étapes (correspond aux onglets de l'ui). + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public enum StorageStep implements WizardStep { + + /** pour choisir le mode de connexion (local ou remote) */ + CHOOSE_DB_MODE( + n("observe.storage.step.dbMode"), + n("observe.storage.step.dbMode.description") + ), + /** + * pour configurer la connexion à la source de données (uniquement si + * besoin) + */ + CONFIG( + n("observe.storage.step.config"), + n("observe.storage.step.config.description") + ), + /** + * pour configurer le referentiel a utiliser lors de la creation d'une base + * distante + */ + CONFIG_REFERENTIEL( + n("observe.storage.step.configReferentiel"), + n("observe.storage.step.configReferentiel.description") + ), + /** + * pour configurer la sources des données a utiliser lors de la creation d'une base + * distante + */ + CONFIG_DATA( + n("observe.storage.step.configData"), + n("observe.storage.step.configData.description") + ), + /** + * pour effectuer une sauvegarde de la base locale. (uniquement disponible + * si on veut générer une nouvelle base locale) + */ + BACKUP( + n("observe.storage.step.backup"), + n("observe.storage.step.backup.description") + ), + /** + * pour sélectionner les données à sauvegarder (unqiuement sur une ui de + * backup) + */ + SELECT_DATA( + n("observe.storage.step.selectData"), + n("observe.storage.step.selectData.description") + ), + /** + * Pour sélectionner les rôles à appliquer pour la création ou mise à jour + * d'une base distante + */ + ROLES( + n("observe.storage.step.roles"), + n("observe.storage.step.roles.description") + ), + /** pour confirmer et réaliser les actions demandées */ + CONFIRM( + n("observe.storage.step.confirm"), + n("observe.storage.step.confirm.description") + ); + + private final String label; + + private final String description; + + StorageStep(String label, String description) { + this.label = label; + this.description = description; + } + + @Override + public String getLabel() { + return label; + } + + @Override + public String getDescription() { + return description; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/StorageUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/StorageUI.jaxx new file mode 100644 index 0000000..116fc38 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/StorageUI.jaxx @@ -0,0 +1,189 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<JDialog id="storageMain" + implements='jaxx.runtime.swing.wizard.WizardUI<StorageStep, StorageUIModel>' + width='550' height='600' defaultCloseOperation='dispose_on_close' + > + + <import> + fr.ird.observe.application.swing.ui.UIHelper + fr.ird.observe.application.swing.ui.storage.tabs.StorageTabUI + fr.ird.observe.application.swing.ui.storage.tabs.BackupUI + fr.ird.observe.application.swing.ui.storage.tabs.ChooseDbModeUI + fr.ird.observe.application.swing.ui.storage.tabs.ConfigReferentielUI + fr.ird.observe.application.swing.ui.storage.tabs.ConfigDataUI + fr.ird.observe.application.swing.ui.storage.tabs.ConfigUI + fr.ird.observe.application.swing.ui.storage.tabs.ConfirmUI + fr.ird.observe.application.swing.ui.storage.tabs.RolesUI + fr.ird.observe.application.swing.ui.storage.tabs.SelectDataUI + + java.awt.Window + + jaxx.runtime.JAXXContext + javax.swing.UIManager + </import> + + <StorageUIHandler id='handler' initializer='getContextValue(StorageUIHandler.class)'/> + + <StorageUIModel id='model' javaBean='getContextValue(StorageUIModel.class)'/> + + <!-- le bloqueur d'ui lorsqu'une action est en cours ou annulée --> + <BlockingLayerUI id='busyBlockLayerUI'/> + + <CardLayout> + <!-- les differents contenu d'onglets --> + <ChooseDbModeUI id='CHOOSE_DB_MODE' constructorParams='this'/> + <ConfigUI id='CONFIG' constructorParams='this'/> + <ConfigReferentielUI id='CONFIG_REFERENTIEL' constructorParams='this'/> + <ConfigDataUI id='CONFIG_DATA' constructorParams='this'/> + <BackupUI id='BACKUP' constructorParams='this'/> + <SelectDataUI id='SELECT_DATA' constructorParams='this'/> + <RolesUI id='ROLES' constructorParams='this'/> + <ConfirmUI id='CONFIRM' constructorParams='this'/> + </CardLayout> + + <script><![CDATA[ + +private boolean contextInitialized; + +public StorageUI(Window owner, JAXXContext parentContext) { + super(owner); + // verification du context parent + UIHelper.checkJAXXContextEntry(parentContext, UIHelper.newContextEntryDef(StorageUIHandler.class)); + UIHelper.checkJAXXContextEntry(parentContext, UIHelper.newContextEntryDef(StorageUIModel.class)); + UIHelper.checkJAXXContextEntry(parentContext, UIHelper.newContextEntryDef("apply", Runnable.class)); + UIHelper.checkJAXXContextEntry(parentContext, UIHelper.newContextEntryDef("cancel", Runnable.class)); + + if (owner != null) { + setContextValue(owner, "parent"); + } + UIHelper.initContext(this, parentContext); + contextInitialized = true; +} + +public void destroy() { + getHandler().destroy(this); +} + +@Override +public void dispose() { + if (log.isDebugEnabled()) { + log.debug("dispose storage ui " + this); + } + destroy(); + super.dispose(); +} + +@Override +protected void finalize() throws Throwable { + super.finalize(); + destroy(); +} + +@Override +public void start() { + getHandler().start(this); +} + +@Override +public StorageStep getSelectedStep() { + int index = tabs.getSelectedIndex(); + StorageTabUI c = null; + if (index > -1) { + c = (StorageTabUI) tabs.getComponentAt(index); + } + StorageStep result = c == null ? null : c.getStep(); + return result; +} + +@Override +public StorageTabUI getStepUI(StorageStep step) { + if (step != null) { + return (StorageTabUI) getObjectById(step.name()); + } + return null; +} + +@Override +public StorageTabUI getStepUI(int stepIndex) { + if (stepIndex > tabs.getTabCount()) { + return null; + } + return (StorageTabUI) tabs.getComponentAt(stepIndex); +} + +@Override +public StorageTabUI getSelectedStepUI() { + StorageStep step = getSelectedStep(); + StorageTabUI ui = getStepUI(step); + return ui; +} + +@Override +public void onStepChanged(StorageStep oldStep, StorageStep newStep) { + getHandler().onStepChanged(this, oldStep, newStep); +} + +@Override +public void onStepsChanged(StorageStep[] steps) { + +} + +void $afterCompleteSetup() { + getHandler().initUI(this); +} +]]> + </script> + + <!-- les onglets --> + <JTabbedPane id='tabs' decorator='boxed' + constraints='BorderLayout.CENTER' + onStateChanged='if (getSelectedStep() != null) { getModel().gotoStep(getSelectedStep()); }'/> + + <!-- les actions --> + <Table id='actions' weightx='1' fill='both' constraints='BorderLayout.SOUTH'> + <row> + <cell weightx='0.5' fill="both"> + <!-- pour annuler --> + <JButton id="cancelAction" + onActionPerformed='getHandler().launchCancel(this)'/> + </cell> + <cell weightx='0.5' fill="both"> + <!-- pour aller sur l'onglet précédent --> + <JButton id="previousAction" + onActionPerformed='getModel().gotoPreviousStep()'/> + </cell> + <cell weightx='0.5' fill="both"> + <!-- pour aller sur l'onglet suivant --> + <JButton id="nextAction" + onActionPerformed='getModel().gotoNextStep()'/> + </cell> + <cell weightx='0.5' fill="both"> + <!-- pour apliquer la configuration --> + <JButton id="applyAction" + onActionPerformed='getHandler().launchApply(this)'/> + </cell> + </row> + </Table> + +</JDialog> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/StorageUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/StorageUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/storage/StorageUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/StorageUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/StorageUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/StorageUIHandler.java new file mode 100644 index 0000000..eb21776 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/StorageUIHandler.java @@ -0,0 +1,813 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.storage; + +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableSet; +import fr.ird.observe.application.swing.ObserveActionExecutor; +import fr.ird.observe.application.swing.ObserveRunner; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.ObserveTextGenerator; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.db.constants.ConnexionStatus; +import fr.ird.observe.application.swing.db.constants.CreationMode; +import fr.ird.observe.application.swing.db.constants.DbMode; +import fr.ird.observe.application.swing.db.event.ObserveSwingDataSourceEvent; +import fr.ird.observe.application.swing.db.event.ObserveSwingDataSourceListenerAdapter; +import fr.ird.observe.services.configuration.ObserveDataSourceConfiguration; +import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationRest; +import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaH2; +import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaPG; +import fr.ird.observe.services.configuration.ObserveDataSourceInformation; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.DataSourceCreateConfigurationDto; +import fr.ird.observe.services.dto.ObserveDbUserDto; +import fr.ird.observe.services.service.AddSqlScriptProducerRequest; +import fr.ird.observe.services.service.SqlScriptProducerService; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel; +import fr.ird.observe.application.swing.ui.storage.tabs.RolesTableModel; +import fr.ird.observe.application.swing.ui.storage.tabs.SecurityModel; +import fr.ird.observe.application.swing.ui.storage.tabs.StorageTabUI; +import jaxx.runtime.context.DefaultApplicationContext.AutoLoad; +import jaxx.runtime.swing.wizard.WizardUILancher; +import org.apache.commons.io.FileUtils; +import org.apache.commons.io.IOUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JTabbedPane; +import java.awt.Component; +import java.awt.Window; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.util.Date; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.nuiton.i18n.I18n.t; + +/** + * Le handler des actions sur base. + * + * On retrouve ici les méthodes pour importer, exporter, faire des backup, + * synchroniser les bases. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +@AutoLoad +public class StorageUIHandler { + + /** Logger */ + private static final Log log = LogFactory.getLog(StorageUIHandler.class); + + /** + * Prépare une service de persistance à partir d'un modèle. + * + * Le service ne sera pas ouvert. + * + * @param model le modèle de la source de données + * @return le service de persistance initialisé mais non ouvert. + */ + public ObserveSwingDataSource newDataSourceFromModel( + StorageUIModel model) { + + ObserveSwingDataSource dataSource = null; + ObserveDataSourceConfiguration configuration; + switch (model.getDbMode()) { + case CREATE_LOCAL: + case USE_LOCAL: + configuration = model.toH2StorageConfig(t("observe.storage.label.local")); + + dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(configuration); + + dataSource.addObserveSwingDataSourceListener( + new ObserveSwingDataSourceListenerAdapter() { + + @Override + public void onOpened(ObserveSwingDataSourceEvent event) { + ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); + // la base locale existe desormais + context.getConfig().setLocalStorageExist(true); + } + }); + + break; + case USE_REMOTE: + configuration = model.toPGStorageConfig(t("observe.storage.label.remote")); + dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(configuration); + break; + case USE_SERVER: + configuration = model.toRestStorageConfig(t("observe.storage.label.server")); + dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(configuration); + break; + } + + return dataSource; + } + + public void initUI(final StorageUI ui) { + + StorageUIModel model = ui.getModel(); + + // on écoute les changements d'étapes + model.addPropertyChangeListener(StorageUIModel.STEP_PROPERTY_NAME, evt -> { + StorageUIModel model1 = (StorageUIModel) evt.getSource(); + StorageStep oldStep = (StorageStep) evt.getOldValue(); + StorageStep newStep = (StorageStep) evt.getNewValue(); + if (log.isDebugEnabled()) { + log.debug("step has changed <old:" + oldStep + ", new:" + newStep + ">"); + } + int oldStepIndex = oldStep == null ? -1 : model1.getStepIndex(oldStep); + int newStepIndex = model1.getStepIndex(newStep); + JTabbedPane tabs = ui.getTabs(); + if (oldStepIndex + 1 == newStepIndex) { + + // creation d'un nouvel onglet + StorageTabUI c = (StorageTabUI) ui.getObjectById(newStep.name()); + String title = t(newStep.getLabel()); + String tip = t(newStep.getDescription()); + + if (log.isDebugEnabled()) { + log.debug("Create tab " + title + " ui = " + c); + } + tabs.addTab(title, null, c, tip); + tabs.setMnemonicAt(newStepIndex, title.charAt(0)); + + // selection du nouvel onglet + int index = tabs.indexOfComponent(c); + if (index > -1) { + tabs.setSelectedIndex(index); + } + ui.onStepChanged(oldStep, newStep); + + } else if (oldStepIndex > newStepIndex) { + + // il s'agit d'un retour en arrière + // on supprime tous les onglets obsoletes + int index = newStepIndex + 1; + while (tabs.getTabCount() > index) { + if (log.isDebugEnabled()) { + log.debug("remove tab : " + index); + } + tabs.remove(index); + } + + ui.onStepChanged(oldStep, newStep); + } else { + throw new IllegalStateException("can not go from " + oldStep + " to " + newStep); + } + }); + + // initialisation des onglets + ui.CHOOSE_DB_MODE.init(); + ui.CONFIG.init(); + ui.CONFIG_REFERENTIEL.init(); + ui.CONFIG_DATA.init(); + ui.BACKUP.init(); + ui.SELECT_DATA.init(); + ui.ROLES.init(); + ui.CONFIRM.init(); + + // recuperation de la source de données en cours d'utilisation + ObserveDataSourceConfiguration dataSourceConfiguration = ui.getContextValue(ObserveDataSourceConfiguration.class); + + // chargement du modèle + model.init(ui, dataSourceConfiguration); + } + + public void start(StorageUI ui) { + + // on demarre le modele pour le type de base connu + ui.getModel().start(ui.getModel().getDbMode()); + + // centrage sur la frame parent + UIHelper.center(ui.getContextValue(Window.class, "parent"), ui); + + // affichage ui + ui.setVisible(true); + } + + public void onStepChanged(StorageUI ui, StorageStep oldStep, StorageStep newStep) { + if (newStep == null) { + return; + } + if (log.isDebugEnabled()) { + log.debug("new step : " + newStep); + } + StorageUIModel model = ui.getModel(); + + boolean mustRecompute = oldStep == null || oldStep.ordinal() < newStep.ordinal(); + + if (StorageStep.CONFIG == newStep) { + + model.updateEditConfigValues(); + + if (mustRecompute) { + + // on redemande un test de connexion a chaque fois qu'on rentre dans l'onglet + model.setConnexionStatus(ConnexionStatus.UNTESTED); + } + + } + + if (StorageStep.CONFIG_REFERENTIEL == newStep && mustRecompute) { + + // mise à jour de l'univers des étapes (ajout/suppression étape confg_data et select_data possible) + ui.getModel().updateUniverse(); + + } + + if (StorageStep.CONFIG_DATA == newStep && mustRecompute) { + + // mise à jour de l'univers des étapes (ajout/suppression étape select_data possible) + ui.getModel().updateUniverse(); + + } + + if (StorageStep.SELECT_DATA == newStep && mustRecompute) { + + if (ObstunaAdminAction.CREATE == ui.getModel().getAdminAction() + && (model.getSelectDataModel() == null || model.getSelectDataModel().isEmpty())) { + + // récupération des données possibles à importer + initSelectData(ui); + + } + + } + + if (StorageStep.ROLES == newStep && mustRecompute) { + + // récupération des rôles de la base cible + updateSecurity(model, ui.getROLES().getRolesModel()); + + } + + if (StorageStep.CONFIRM == newStep) { + + // generation du rapport + String text = computeReport(ui, oldStep); + ui.CONFIRM.getResume().setText(text); + + } + + } + + public void launchApply(final StorageUI ui) { + + ui.getModel().setAlreadyApplied(true); + + Runnable action = WizardUILancher.APPLY_DEF.getContextValue(ui); + + if (action == null) { + final StorageUILauncher launcher = ui.getContextValue(StorageUILauncher.class); + + action = () -> { + try { + launcher.doAction(ui); + } finally { + launcher.doClose(ui, false); + } + }; + } + ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); + if (mainUI == null) { + if (log.isWarnEnabled()) { + log.warn("Launch standalone apply action " + action); + } + //FIXME Action executor will not execute task until previous is finished... + action.run(); + } else { + ObserveActionExecutor executor = ObserveRunner.getActionExecutor(); + + executor.addAction(t("observe.action.storage.applyAction"), action); + } + } + + public void launchCancel(StorageUI ui) { + + Runnable action = WizardUILancher.CANCEL_DEF.getContextValue(ui); + + ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); + if (mainUI == null) { + if (log.isWarnEnabled()) { + log.warn("Launch standalone cancel action " + action); + } + //FIXME Action executor will not execute task until previous is finished... + if (action != null) { + action.run(); + } + } else { + ObserveActionExecutor executor = ObserveRunner.getActionExecutor(); + executor.addAction(t("observe.storage.action.cancel"), action); + } + } + + /** + * Utiliser le storage defini dans le modèle donné. + * + * @param model le model++ du storage a creer ou utiliser + */ + public void doChangeStorage(StorageUIModel model) { + ObserveSwingApplicationContext observeContext = ObserveSwingApplicationContext.get(); + + ObserveSwingApplicationConfig config = observeContext.getConfig(); + + // faut-il detruire la base locale ? + boolean destroyLocalBase = + config.isLocalStorageExist() && + model.getDbMode() == DbMode.CREATE_LOCAL; + + if (log.isDebugEnabled()) { + log.debug(">>> should destroy local db ? " + destroyLocalBase); + } + + + ObserveSwingDataSource currentDataSource = observeContext.getDataSourcesManager().getMainDataSource(); + + ObserveSwingDataSource localDataSource = null; + + if (currentDataSource != null && currentDataSource.isLocal()) { + localDataSource = currentDataSource; + } + + boolean localDbIsSane = true; + if (destroyLocalBase || model.isDoBackup()) { + if (localDataSource == null) { + ObserveDataSourceConfigurationTopiaH2 localConfiguration = config.getDataSourceConfigurationH2(t("observe.storage.label.local")); + + // la base ne doit pas etre mise a jour dans ce cas + localConfiguration.setCanMigrate(false); + + // on charge un storage sur la base locale + localDataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(localConfiguration); + } + + // Let's check if the datasource is opened or not : + // we could have close the datasource through the ui + // If the datasource is closed, we try to open it + if (!localDataSource.isOpen()) { + try { + + localDataSource.open(); + + } catch (Exception e) { + // on a pas reussi à ouvrir la base locale + // cela ne doit pas empécher de continuer + // il faut juste supprimer physiquement le repertoire + // de la base + UIHelper.handlingError(t("observe.error.storage.could.not.load.local.db", e.getMessage()), e); + + // on conserve l'état + localDbIsSane = false; + + // pour la suite on fait comme si il n'y a pas de local storage + localDataSource = null; + } + } + } + + if (model.isDoBackup()) { + if (!localDbIsSane) { + + // la base locale n'est pas saine, on doit arrêter l'objectOperation + // de changement de base sous peine de perdre la base. + Exception e = new Exception(t("observe.error.storage.could.not.backup.unsane.local.db")); + UIHelper.handlingError(e); + return; + } + // effectue la backup de la base locale existante + File f = model.getBackupFile(); + if (log.isDebugEnabled()) { + log.debug(">>> do backup with " + localDataSource + " in " + f); + } + try { + SqlScriptProducerService dumpProducerService = localDataSource.newSqlScriptProducerService(); + backupLocalDatabase(dumpProducerService, f); + } catch (Exception e) { + UIHelper.handlingError(e); + return; + } + } + + if (destroyLocalBase) { + if (log.isDebugEnabled()) { + log.debug(">>> destroy local db " + localDataSource); + } + if (!localDbIsSane) { + // la base locale n'est pas saine, on va supprimer directement + // le dossier de la base + File localDBDirectory = config.getLocalDBDirectory(); + if (log.isInfoEnabled()) { + log.info(">>> destroy local db directory " + localDBDirectory); + } + try { + FileUtils.deleteDirectory(localDBDirectory); + } catch (IOException e) { + UIHelper.handlingError(e); + } + } else { + try { + localDataSource.destroy(); + } catch (Exception e) { + UIHelper.handlingError(e); + return; + } + } + } + + // suppression du storage precedent + if (currentDataSource != null && currentDataSource.isOpen()) { + if (log.isDebugEnabled()) { + log.debug(">>> close main storage " + currentDataSource); + } + // on doit fermer le storage en cours d'utilisation + currentDataSource.close(); + } + + // suppression du storage local + if (localDataSource != null && localDataSource != currentDataSource) { + // ce cas peut arriver lorsque l'on fait juste une backup + // sans vouloir supprimer la base locale + if (log.isDebugEnabled()) { + log.debug(">>> close local storage " + localDataSource); + } + // on doit fermer le storage local ouvert + localDataSource.close(); + } + + localDataSource = null; + + if (log.isDebugEnabled()) { + log.debug("Will create new storage..."); + } + + // preparation du nouveau storage + + try { + + currentDataSource = newDataSourceFromModel(model); + + // si on utilise la base local on lance une migration de la base si necessaire + if (DbMode.USE_LOCAL.equals((model.getDbMode()))) { + + ObserveDataSourceInformation dataSourceInformation = currentDataSource.checkCanConnect(); + + currentDataSource.migrateData(dataSourceInformation, config.getModelVersion()); + + } + + observeContext.getDataSourcesManager().setMainDataSource(currentDataSource); + observeContext.prepareMainStorage(currentDataSource, true); + + if (model.getDbMode() == DbMode.CREATE_LOCAL) { + + DataSourceCreateConfigurationDto creationConfigurationDto = model.getCreationConfigurationDto(); + + try { + + currentDataSource.create(creationConfigurationDto); + + } catch (Exception e) { + //si il y a une erreur lor de la création de la base locla + + // on suprimer la base + File localDBDirectory = config.getLocalDBDirectory(); + if (log.isInfoEnabled()) { + log.info(">>> destroy local db directory " + localDBDirectory); + } + try { + FileUtils.deleteDirectory(localDBDirectory); + } catch (IOException e2) { + UIHelper.handlingError(e2); + } + + config.setLocalStorageExist(false); + observeContext.getDataSourcesManager().setMainDataSource(null); + + throw e; + } + } else { + // ouverture du nouveau storage + currentDataSource.open(); + } + + if (DbMode.CREATE_LOCAL.equals(model.getDbMode()) + && (CreationMode.IMPORT_REMOTE_STORAGE.equals(model.getCreationMode()) || CreationMode.IMPORT_SERVER_STORAGE.equals(model.getCreationMode())) + && config.isLocalStorageExist()) { + // si on a creer la base locale a partir d'un import d'une base + // distante, on sauvegarde la base locale comme dump initial + // il s'agit d'un dump du référentiel + File f = config.getInitialDbDump(); + if (f.exists()) { + // on supprime le dump sql de la base embarquée + if (!f.delete()) { + throw new IllegalStateException("could not delete " + f); + } + } + if (log.isInfoEnabled()) { + log.info(">>> create initial dump with " + localDataSource + " in " + f); + } + try { + SqlScriptProducerService dumpProducerService = observeContext.getMainDataSourceServicesProvider().newSqlScriptProducerService(); + backupLocalDatabase(dumpProducerService, f); + config.setInitialDumpExist(true); + } catch (Exception e) { + UIHelper.handlingError(e); + } + } + + if (log.isInfoEnabled()) { + log.info(">>> main storage opened " + currentDataSource.getLabel()); + } + + if (model.isStoreRemoteConfig()) { + storeRemoteConfig(model); + } + + } catch (Exception ex) { + UIHelper.handlingError(ex); + throw new RuntimeException(ex); + } + } + + /** + * Sauvegarder dans la configuration de l'application le paramétrage de la + * source de données distante donnée. + * + * @param model le model de la source de données + */ + public void storeRemoteConfig(StorageUIModel model) { + ObserveSwingApplicationConfig config = ObserveSwingApplicationContext.get().getConfig(); + // on sauvegarde dans le parametrage dans la configuration de + // l'application + + if (model.isEditRemoteConfig()) { + + ObserveDataSourceConfigurationTopiaPG configurationTopiaPG = model.toPGStorageConfig(""); + config.fromStorageConfig(configurationTopiaPG); + + } else if (model.isEditServerConfig()) { + + ObserveDataSourceConfigurationRest configurationRest = model.toRestStorageConfig(""); + config.fromStorageConfig(configurationRest); + + } + } + + /** + * @return le lastName par defaut du fichier de sauvegarde de la base locale + * (expression calculée à partir de la date courante et du pattern + * {@link ObserveSwingApplicationConfig#BACKUP_DB_PATTERN}). + */ + public String getDefaultBackupFilename() { + return String.format(ObserveSwingApplicationConfig.BACKUP_DB_PATTERN, new Date()); + } + + /** + * Effectue une sauvegarde de la base locale vers le fichier choisi. + * + * @param dumpProducerService le service de dump + * @param dst le fichier de sauvegarde + */ + public void backupLocalDatabase(SqlScriptProducerService dumpProducerService, File dst) { + if (dst == null) { + throw new IllegalArgumentException( + "file where to backup can not be null"); + } + if (log.isDebugEnabled()) { + log.debug(dst); + } + + AddSqlScriptProducerRequest request = AddSqlScriptProducerRequest.forH2().addSchema().addReferential().addAllData(); + byte[] dataDump = dumpProducerService.produceAddSqlScript(request); + + try (FileOutputStream outputStream = new FileOutputStream(dst)) { + + outputStream.write(dataDump); + } catch (Exception e) { + UIHelper.handlingError(e); + } + } + + /** + * Effectue une sauvegarde d'un service de persitances vers le fichier + * choisi. + * + * On peut spécifier les donnéees à exporter via le paramètre {@code + * marees}. + * + * <b>Note:</b> Si ce paramètre vaut {@code null}, on export tout. + * + * @param dataSource la source de donnée qui encapsule la base locale + * @param dst le fichier de sauvegarde + * @param trips les marees a exporter (si {@code null} on exporte tout) + */ + public void backupLocalDatabase(ObserveSwingDataSource dataSource, + File dst, + Set<DataReference> trips) { + + SqlScriptProducerService dumpService = dataSource.newSqlScriptProducerService(); + + + if (trips == null) { + if (log.isInfoEnabled()) { + log.info("will export all datas."); + } + backupLocalDatabase(dumpService, dst); + return; + } + if (dst == null) { + throw new IllegalArgumentException( + "file where to backup can not be null"); + } + if (log.isInfoEnabled()) { + log.info("will export " + trips.size() + " marees to " + dst); + } + if (log.isDebugEnabled()) { + log.debug(trips); + } + + // on doit dumper la base distante dans une base h2 et en faire + // la sauvegarde + + ImmutableSet<String> tripIds = ImmutableSet.copyOf(trips.stream().map(DataReference.ID_FUNCTION).collect(Collectors.toSet())); + + AddSqlScriptProducerRequest request = AddSqlScriptProducerRequest.forH2().addSchema().addReferential().dataIdsToAdd(tripIds); + byte[] dump = dumpService.produceAddSqlScript(request); + + try (FileOutputStream fileOutputStream = new FileOutputStream(dst)) { + + IOUtils.write(dump, fileOutputStream); + + } catch (IOException e) { + UIHelper.handlingError(e); + } + } + + public String computeReport(StorageUI ui, StorageStep step) { + if (log.isDebugEnabled()) { + log.debug("Build report from step " + step); + } + StorageUIModel model = ui.getModel(); + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ObserveTextGenerator textGenerator = applicationContext.getTextGenerator(); + String report = textGenerator.getDataSourceConnectionReport(model); + return report; + } + + public void destroy(StorageUI ui) { + ui.getModel().destroy(); + if (log.isDebugEnabled()) { + log.debug("destroy ui " + ui.getName()); + } + UIHelper.TabbedPaneIterator<Component> itr = + UIHelper.newTabbedPaneIterator(ui.getTabs()); + for (; itr.hasNext(); ) { + StorageTabUI tab = + (StorageTabUI) itr.next(); + if (log.isDebugEnabled()) { + log.debug("destroy ui " + tab.getName()); + } + tab.destroy(); + } + UIHelper.destroy(ui); + } + + protected DecoratorService getDecoratorService() { + DecoratorService decoratorService = + ObserveSwingApplicationContext.get().getDecoratorService(); + return decoratorService; + } + + public void initSelectData(StorageUI ui, ObserveSwingDataSource source, boolean selectAll) { + + StorageUIModel model = ui.getModel(); + + try { + + Preconditions.checkState(source != null, "Can't select data on a null dataSource"); + + DataSelectionModel dataModel = new DataSelectionModel(); + dataModel.setUseData(true); + dataModel.setUseOpenData(true); + dataModel.setUseReferentiel(false); + + DataSelectionModel.populate(dataModel, source); + + if (selectAll) { + + dataModel.addAllSelectedData(); + + } + + // positionnement du model de selection de données + // dans le model du wizard + model.setSelectDataModel(dataModel); + + // initialisation de l'ui dedié + ui.getSELECT_DATA().initTree(source); + + } catch (Exception e) { + throw new RuntimeException("Could not grab data to select", e); + } + + } + + protected void initSelectData(StorageUI ui) { + + StorageUIModel model = ui.getModel(); + + try { + + // Creation de la data source de lecture des données à sélectionner + ObserveSwingDataSource importDataSource = model.toImportDataSourceConfig(); + + Preconditions.checkState(importDataSource != null, "Can't select data on a null dataSource"); + + try { + + importDataSource.open(); + + model.checkImportDbVersion(importDataSource); + + initSelectData(ui, importDataSource, false); + + } finally { + importDataSource.close(); + } + + } catch (Exception e) { + if (log.isErrorEnabled()) { + log.error(e, e); + } + } + } + + protected void updateSecurity(StorageUIModel model, RolesTableModel roleModel) { + + SecurityModel security = model.getSecurityModel(); + + ObserveSwingDataSource dataSource = null; + + switch (model.getDbMode()) { + case USE_REMOTE: + ObserveDataSourceConfigurationTopiaPG pgConfig = model.getPgConfig(); + + dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(pgConfig); + break; + case USE_SERVER: + ObserveDataSourceConfigurationRest restConfig = model.getRestConfig(); + dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(restConfig); + + } + + if (dataSource != null) { + try { + + Set<ObserveDbUserDto> users = dataSource.getUsers(); + + if (log.isInfoEnabled()) { + log.info("Db roles : " + users); + } + + security.init(users); + roleModel.init(security); + + } catch (Exception e) { + throw new RuntimeException("Could not obtain db roles", e); + } finally { + if (dataSource.isOpen()) { + dataSource.close(); + } + } + } + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/StorageUILauncher.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/StorageUILauncher.java new file mode 100644 index 0000000..ec2afbc --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/StorageUILauncher.java @@ -0,0 +1,520 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.storage; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.db.constants.DbMode; +import fr.ird.observe.application.swing.ui.ObserveMainUIHandler; +import fr.ird.observe.application.swing.ui.UIHelper; +import jaxx.runtime.JAXXContext; +import jaxx.runtime.JAXXObject; +import jaxx.runtime.swing.wizard.BusyChangeListener; +import jaxx.runtime.swing.wizard.WizardModel; +import jaxx.runtime.swing.wizard.WizardUILancher; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.awt.Window; +import java.util.Arrays; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.nuiton.i18n.I18n.t; + +/** + * Le wizard de base pour les opération sur le service de données. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class StorageUILauncher extends WizardUILancher<StorageStep, StorageUIModel, StorageUI> { + + /** Logger */ + private static final Log log = LogFactory.getLog(StorageUILauncher.class); + + protected final String title; + + public StorageUILauncher(JAXXContext context, + Window frame, + StorageUIModel model, + String title) { + super(context, frame, StorageUI.class, StorageUIModel.class, model); + this.title = title; + } + + public StorageUILauncher(JAXXContext context, + Window frame, + String title) { + super(context, frame, StorageUI.class, StorageUIModel.class); + this.title = title; + } + + @Override + protected void init(StorageUI ui) { + if (log.isInfoEnabled()) { + log.info("Will init " + ui.getName()); + } + super.init(ui); + if (title != null) { + ui.setTitle(title); + } + BusyChangeListener listener = new BusyChangeListener(ui); + UIHelper.setLayerUI(ui.getTabs(), ui.getBusyBlockLayerUI()); + listener.setBlockingUI(ui.getBusyBlockLayerUI()); + ui.getModel().addPropertyChangeListener(WizardModel.BUSY_PROPERTY_NAME, listener); + ui.setContextValue(this); + } + + @Override + public void start() { + super.start(); + ui.getModel().setBusy(false); + } + + @Override + protected void doCancel(StorageUI ui) { + if (log.isDebugEnabled()) { + log.debug("Will cancel " + ui.getName()); + } + ui.getModel().setBusy(true); + super.doCancel(ui); + ObserveMainUIHandler.restartEdit(); + } + + @Override + protected void doAction(StorageUI ui) { + ui.getModel().setBusy(true); + super.doAction(ui); + } + + protected StorageUIHandler getStorageUIHandler() { + StorageUIHandler handler = + ui.getContextValue(StorageUIHandler.class); + return handler; + } + + @Override + protected void doClose(StorageUI ui, boolean wasCanceled) { + if (log.isDebugEnabled()) { + log.debug("Will close " + ui.getName() + " (was canceled ? " + wasCanceled + ")"); + } + super.doClose(ui, wasCanceled); + ui.getModel().setBusy(false); + ui.dispose(); + } + + /** + * Méthode pour lancer le changement de source de données. + * + * @param rootContext le context applicatif + * @param mainUI main ui + * @param modes les modes optionnel à utiliser + * @param title le titre de la fenetre + * @see StorageUIHandler + * @see StorageUI + */ + public static void changeStorage(final JAXXContext rootContext, + final Window mainUI, + final Set<DbMode> modes, + final String title) { + + new StorageUILauncher(rootContext, mainUI, title) { + + @Override + protected void init(StorageUI ui) { + super.init(ui); + if (log.isDebugEnabled()) { + log.debug("Incoming dbmode : " + modes.stream().map(DbMode::name).collect(Collectors.joining(", "))); + } + StorageUIModel model = ui.getModel(); + if (CollectionUtils.isNotEmpty(modes)) { + if (log.isInfoEnabled()) { + log.info("will use incoming mode " + modes.stream().map(DbMode::name).collect(Collectors.joining(", "))); + } + + model.setExcludeSteps( + Arrays.asList(StorageStep.SELECT_DATA, + StorageStep.BACKUP, + StorageStep.CONFIG_REFERENTIEL, + StorageStep.CONFIG_DATA, + StorageStep.ROLES) + ); + model.setCanCreateLocalService(modes.contains(DbMode.CREATE_LOCAL)); + model.setCanUseLocalService(modes.contains(DbMode.USE_LOCAL)); + model.setCanUseRemoteService(modes.contains(DbMode.USE_REMOTE)); + model.setCanUseServerService(modes.contains(DbMode.USE_SERVER)); + + model.updateUniverse(); + model.setDbMode(modes.stream().findFirst().get()); + + } else { + ObserveSwingApplicationConfig config = ObserveSwingApplicationContext.get().getConfig(); + Boolean localOpened = config.getMainStorageOpenedLocal(); + if (model.isLocalStorageExist() && localOpened != null && localOpened) { + if (log.isDebugEnabled()) { + log.debug("Can not use local db (already opened)"); + } + model.setCanUseLocalService(false); + } + model.setCanCreateLocalService(true); + model.setCanUseRemoteService(true); + model.setCanUseServerService(true); + } + model.updateUniverse(); + } + + @Override + protected void doAction(StorageUI ui) { + super.doAction(ui); + StorageUIHandler handler = getStorageUIHandler(); + handler.doChangeStorage(ui.getModel()); + } + + }.start(); + } + + /** + * Méthode pour lancer l'action de connexion à une base distante. + * + * Cette méthode doit être appelée avant toute action avec une base distante + * : + * + * synchronisation, récupération du référentiel distant... + * + * @param context le context applicatif + * @param mainUI la fenetre principale parent (peut etre null) + * @param model le modèle de source de données à utiliser + * @see StorageUI + */ + public static void obtainRemoteConnexion(final JAXXContext context, + Window mainUI, + final StorageUIModel model) { + obtainConnexion(context, mainUI, model, t("observe.title.connect.remoteDB"), DbMode.USE_REMOTE); + } + + /** + * Méthode pour lancer l'action de connexion à une base distante. + * + * Cette méthode doit être appelée avant toute action avec un server distant + * : + * + * synchronisation, récupération du référentiel distant... + * + * @param context le context applicatif + * @param mainUI la fenetre principale parent (peut etre null) + * @param model le modèle de source de données à utiliser + * @see StorageUI + */ + public static void obtainServerConnexion(final JAXXContext context, + Window mainUI, + final StorageUIModel model) { + obtainConnexion(context, mainUI, model, t("observe.title.connect.serverDB"), DbMode.USE_SERVER); + } + + /** + * Méthode pour lancer l'action de connexion à une source distante. + * + * Cette méthode doit être appelée avant toute action avec un source distante + * : + * + * synchronisation, récupération du référentiel distant... + * + * @param context le context applicatif + * @param mainUI la fenetre principale parent (peut etre null) + * @param model le modèle de source de données à utiliser + * @param title le titre de la fenêtre + * @param model le type deconnexion (base distante ou serveur distant) + * @see StorageUI + */ + public static void obtainConnexion(final JAXXContext context, + Window mainUI, + final StorageUIModel model, + String title, + DbMode dbMode) { + + + if (mainUI == null) { + mainUI = ObserveSwingApplicationContext.get().getMainUI(); + } + addStorageUIHandler(context); + StorageUILauncher launcher = new StorageUILauncher( + context, + mainUI, + model, + title) { + + @Override + protected void init(StorageUI ui) { + StorageUIModel model = ui.getModel(); + + model.setCanCreateLocalService(false); + model.setCanUseLocalService(false); + model.setCanUseRemoteService(true); + model.setCanUseServerService(true); + + model.setExcludeSteps(Arrays.asList( + StorageStep.CHOOSE_DB_MODE, + StorageStep.CONFIG_REFERENTIEL, + StorageStep.CONFIG_DATA, + StorageStep.SELECT_DATA, + StorageStep.ROLES, + StorageStep.BACKUP, + StorageStep.CONFIRM) + ); + model.setSteps(StorageStep.CONFIG); + model.updateUniverse(); + + model.setDbMode(dbMode); + } + + @Override + protected StorageUI createUI(JAXXContext context, + Window mainUI, + Class<StorageUI> storageUIClass, + Class<StorageUIModel> modelClass, + StorageUIModel model) throws Exception { + if (!(mainUI instanceof JAXXObject)) { + mainUI = null; + } + return super.createUI(context, + mainUI, + storageUIClass, + modelClass, + model + ); + } + + @Override + protected void doAction(StorageUI ui) { + super.doAction(ui); + if (log.isDebugEnabled()) { + log.debug("Apply new remote connexion to " + model); + } + ui.getModel().copyTo(model); + model.validate(); + } + }; + + launcher.start(); + } + + /** + * Méthode pour lancer l'action de connexion à une base locale. + * + * @param context le context applicatif + * @param mainUI la fenetre principale parent (peut etre null) + * @param model le modèle de source de données à utiliser + * @see StorageUI + */ + public static void obtainLocalConnexion(final JAXXContext context, + Window mainUI, + final StorageUIModel model) { + + if (mainUI == null) { + mainUI = ObserveSwingApplicationContext.get().getMainUI(); + } + + addStorageUIHandler(context); + + StorageUILauncher launcher = new StorageUILauncher( + context, + mainUI, + model, + t("observe.title.connect.localDB")) { + + @Override + protected StorageUI createUI(JAXXContext context, + Window mainUI, + Class<StorageUI> storageUIClass, + Class<StorageUIModel> modelClass, + StorageUIModel model) throws Exception { + if (!(mainUI instanceof JAXXObject)) { + // sinon on a pas de context propagé... + mainUI = null; + } + return super.createUI(context, mainUI, storageUIClass, modelClass, model); + } + + @Override + protected void init(StorageUI ui) { + StorageUIModel model = ui.getModel(); + + int nbModes = 0; + + DbMode mode = null; + if (model.isCanCreateLocalService()) { + nbModes++; + mode = DbMode.CREATE_LOCAL; + } + if (model.isCanUseLocalService()) { + nbModes++; + mode = DbMode.USE_LOCAL; + } + if (model.isCanUseRemoteService()) { + nbModes++; + mode = DbMode.USE_REMOTE; + } + if (model.isCanUseServerService()) { + nbModes++; + mode = DbMode.USE_SERVER; + } + + if (nbModes == 1) { + + if (log.isDebugEnabled()) { + log.debug("Only one mode available [" + mode + + "], set it in model"); + } + + // un seul mode possible, on le sélectionne + model.setDbMode(mode); + } + + // on supprime des étapes + model.setExcludeSteps(Arrays.asList( + StorageStep.BACKUP, + StorageStep.CONFIG_REFERENTIEL, + StorageStep.CONFIG_DATA, + StorageStep.SELECT_DATA, + StorageStep.CONFIRM)); + + model.updateUniverse(); + } + + @Override + protected void doAction(StorageUI ui) { + super.doAction(ui); + if (log.isDebugEnabled()) { + log.debug("Apply new local connexion to " + model); + } + ui.getModel().copyTo(model); + model.validate(); + } + }; + + launcher.start(); + } + + /** + * Méthode pour lancer l'action de connexion à une base locale ou distante. + * + * @param context le context applicatif + * @param mainUI la fenetre principale parent (peut etre null) + * @param model le modèle de source de données à utiliser + * @see StorageUI + */ + public static void obtainConnexion(final JAXXContext context, + Window mainUI, + final StorageUIModel model) { + + if (mainUI == null) { + mainUI = ObserveSwingApplicationContext.get().getMainUI(); + } + addStorageUIHandler(context); + StorageUILauncher launcher = new StorageUILauncher( + context, + mainUI, + model, + t("observe.title.connect.existingDB")) { + + @Override + protected void init(StorageUI ui) { + StorageUIModel model = ui.getModel(); + DbMode dbMode = model.getDbMode(); + + // exclusion des étapes non requises + model.setExcludeSteps(Arrays.asList( + StorageStep.SELECT_DATA, + StorageStep.CONFIG_REFERENTIEL, + StorageStep.CONFIG_DATA, + StorageStep.ROLES, + StorageStep.BACKUP, + StorageStep.CONFIRM) + ); + model.setSteps(StorageStep.CONFIG); + model.updateUniverse(); + + // par defaut, on se positionne sur la base distante ? + model.setDbMode(dbMode); + } + + @Override + public void start() { + super.start(); + } + + @Override + protected StorageUI createUI(JAXXContext context, + Window mainUI, + Class<StorageUI> storageUIClass, + Class<StorageUIModel> modelClass, + StorageUIModel model) throws Exception { + if (!(mainUI instanceof JAXXObject)) { + mainUI = null; + } + return super.createUI(context, + mainUI, + storageUIClass, + modelClass, + model + ); + } + + @Override + protected void doAction(StorageUI ui) { + super.doAction(ui); + if (log.isDebugEnabled()) { + log.debug("Apply new remote connexion to " + model); + } + ui.getModel().copyTo(model); + model.validate(); + } + }; + + launcher.start(); + } + + protected static void addStorageUIHandler(JAXXContext context) { + StorageUIHandler handler = + context.getContextValue(StorageUIHandler.class); + if (handler == null) { + + handler = new StorageUIHandler(); + context.setContextValue(handler); + + if (log.isWarnEnabled()) { + log.warn("Register in context an storage handler : " + handler); + } + } else { + if (log.isWarnEnabled()) { + log.warn("Use existing handler " + handler); + } + } + } + + public String getTitle() { + return title; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/StorageUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/StorageUIModel.java new file mode 100644 index 0000000..a4bf1aa --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/StorageUIModel.java @@ -0,0 +1,2058 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.storage; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.ObserveSwingTechnicalException; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.db.constants.ConnexionStatus; +import fr.ird.observe.application.swing.db.constants.CreationMode; +import fr.ird.observe.application.swing.db.constants.DbMode; +import fr.ird.observe.services.ObserveDataSourceConfigurationMainFactory; +import fr.ird.observe.services.configuration.ObserveDataSourceConfiguration; +import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationRest; +import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaH2; +import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaPG; +import fr.ird.observe.services.configuration.ObserveDataSourceInformation; +import fr.ird.observe.services.dto.DataSourceCreateConfigurationDto; +import fr.ird.observe.services.dto.DataSourceCreateWithNoReferentialImportException; +import fr.ird.observe.services.dto.IncompatibleDataSourceCreateConfigurationException; +import fr.ird.observe.services.dto.ObserveDbUserDto; +import fr.ird.observe.services.security.BadObserveWebUserPasswordException; +import fr.ird.observe.services.security.ObserveWebSecurityExceptionSupport; +import fr.ird.observe.services.security.UnknownObserveWebUserException; +import fr.ird.observe.services.security.UnknownObserveWebUserForDatabaseException; +import fr.ird.observe.services.security.UserLoginNotFoundException; +import fr.ird.observe.services.security.UserPasswordNotFoundException; +import fr.ird.observe.services.service.AddSqlScriptProducerRequest; +import fr.ird.observe.services.service.BabModelVersionException; +import fr.ird.observe.services.service.DatabaseConnexionNotAuthorizedException; +import fr.ird.observe.services.service.DatabaseNotFoundException; +import fr.ird.observe.services.service.PingService; +import fr.ird.observe.services.service.SqlScriptProducerService; +import fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel; +import fr.ird.observe.application.swing.ui.storage.tabs.SecurityModel; +import jaxx.runtime.JAXXContext; +import jaxx.runtime.swing.wizard.WizardModel; +import jaxx.runtime.swing.wizard.WizardUILancher; +import org.apache.commons.io.IOUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.version.Version; + +import java.beans.PropertyChangeListener; +import java.io.File; +import java.io.FileInputStream; +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Set; + +import static fr.ird.observe.application.swing.ui.admin.AdminUIModel.LOG_PROPERTY_CHANGE_LISTENER; +import static org.nuiton.i18n.I18n.t; + +/** + * Le modele de l'ui pour changer de source de données. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class StorageUIModel extends WizardModel<StorageStep> { + + /** Logger */ + private static final Log log = LogFactory.getLog(StorageUIModel.class); + + public static final String DB_MODE_PROPERTY_NAME = "dbMode"; + + public static final String CREATION_MODE_PROPERTY_NAME = "creationMode"; + + public static final String DO_BACKUP_PROPERTY_NAME = "doBackup"; + + public static final String BACKUP_FILE_PROPERTY_NAME = "backupFile"; + + public static final String DUMP_FILE_PROPERTY_NAME = "dumpFile"; + + public static final String LOCAL_STORAGE_EXIST_PROPERTY_NAME = "localStorageExist"; + + public static final String USE_SSL_PROPERTY_NAME = "useSsl"; + + public static final String REMOTE_URL_ROPERTY_NAME = "remoteUrl"; + + public static final String SERVER_DATABASE_PROPERTY_NAME = "serverDatabase"; + + public static final String REMOTE_LOGIN_ROPERTY_NAME = "remoteLogin"; + + public static final String REMOTE_PASSWORD_PROPERTY_NAME = "remotePassword"; + + public static final String STORE_REMOTE_CONFIG_PROPERTY_NAME = "storeRemoteConfig"; + + public static final String CONNEXION_STATUS_PROPERTY_NAME = "connexionStatus"; + + public static final String PREVIOUS_SERVICE_PROPERTY_NAME = "previousSource"; + + public static final String CAN_MIGRATE_PROPERTY_NAME = "canMigrate"; + + public static final String SHOW_MIGRATION_SQL_PROPERTY_NAME = "showMigrationSql"; + + public static final String SHOW_MIGRATION_PROGRESSION_PROPERTY_NAME = "showMigrationProgression"; + + private static final String CAN_USE_LOCALE_SERVICE_PROPERTY_NAME = "canUseLocalService"; + + private static final String CAN_CREATE_LOCALE_SERVICE_PROPERTY_NAME = "canCreateLocalService"; + + private static final String CAN_USE_REMOTE_SERVICE_PROPERTY_NAME = "canUseRemoteService"; + + private static final String CAN_USE_SERVER_SERVICE_PROPERTY_NAME = "canUseServerService"; + + public static final String REFERENTIEL_IMPORT_MODE_PROPERTY_NAME = "referentielImportMode"; + + public static final String DATA_IMPORT_MODE_PROPERTY_NAME = "dataImportMode"; + + public static final String EDIT_REMOTE_CONFIG_PROPERTY_NAME = "editRemoteConfig"; + + public static final String EDIT_SERVER_CONFIG_PROPERTY_NAME = "editServerConfig"; + + public static final String VALID_PROPERTY_NAME = "valid"; + + public static final String ALREADY_APPLIED_PROPERTY_NAME = "alreadyApplied"; + + private static final char[] EMPTY_PASSWORD = new char[0]; + + private static final String LOGIN_REFERENTIEL = "referentiel"; + + /** Le dbMode de connexion requis. */ + protected DbMode dbMode; + + protected boolean editServerConfig; + + protected boolean editRemoteConfig; + + /** Un drapeau pour savoir si une base locale existe. */ + protected boolean localStorageExist; + + /** + * Un drapeau pour savoir si l'utilisateur a demandé une sauvegarde de la + * base locale. + * + * Cette option n'est active uniquement si le drapeau localStorageExist est + * à true. + */ + protected boolean doBackup; + + /** + * Un drapeau pour savoir si on a déjà lancé l'action Appliquer (pour éviter le code ré-entrant). + * + * @since 4.0.4 + */ + protected boolean alreadyApplied; + + /** + * le fichier ou effectuer la sauvegarde de la base locale si le drapeau + * doBackup est active. + */ + protected File backupFile = new File(""); + + /** un drapeau pour savoir s'il faut sauver la configuration à distante */ + protected boolean storeRemoteConfig; + + /** le storage precedemment utilise */ + protected ObserveDataSourceConfiguration previousDataSourceConfiguration; + + protected ConnexionStatus connexionStatus; + protected String connexionStatusError; + + /** un drapeau pour definir si on peut utiliser la base locale */ + protected boolean canUseLocalService = true; + + /** un drapeau pour definir si on peut créer une base locale */ + protected boolean canCreateLocalService = true; + + /** un drapeau pour savoir si on a le droit d'utiliser une connexion distante */ + protected boolean canUseRemoteService = true; + + /** un drapeau pour savoir si on a le droit d'utiliser un serveur distant */ + protected boolean canUseServerService = true; + + /** le modèle de sélection de données (utilisé pour les exports) */ + protected DataSelectionModel selectDataModel; + + /** le modèle de sécurité (utilisé pour la mise à jour sécurité sur base distante) */ + protected SecurityModel securityModel; + + /** la configuration d'une base locale */ + protected ObserveDataSourceConfigurationTopiaH2 h2Config; + + /** la configuration d'une base distante */ + protected ObserveDataSourceConfigurationTopiaPG pgConfig; + + /** la configuration d'un serveur web */ + protected ObserveDataSourceConfigurationRest restConfig; + + protected String serverUrl; + + /** Les information de connextion a la base **/ + protected ObserveDataSourceInformation dataSourceInformation; + + /** Les information de connextion a la base **/ + protected ObserveDataSourceInformation h2DataSourceInformation; + + /** le fichier d'import des donné */ + protected File dumpFile; + + /** le mode de creation d'une base */ + protected CreationMode creationMode; + + /** la configuration pour impoter les données */ + protected ObserveDataSourceConfiguration importDataConfig; + + /** l'action d'administration de base obstuna */ + protected ObstunaAdminAction adminAction; + + /** la configuration de la base de referentiel à importer */ + protected StorageUIModel centralSourceModel; + + /** la configuration de la base de données à importer */ + protected StorageUIModel dataSourceModel; + + /** + * Le mode d'import de référentiel (uniquement pour la création de base distante). + * + * @since 3.0 + */ + protected CreationMode referentielImportMode; + + /** + * Le mode d'import des données (uniquement pour la création de base distante). + * + * @since 3.6 + */ + protected CreationMode dataImportMode; + + public StorageUIModel() { + super(StorageStep.class, + StorageStep.CHOOSE_DB_MODE, + StorageStep.BACKUP, + StorageStep.CONFIRM + ); + selectDataModel = new DataSelectionModel(); + securityModel = new SecurityModel(); + + connexionStatus = ConnexionStatus.UNTESTED; + + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ObserveDataSourceConfigurationMainFactory configurationMainFactory = applicationContext.getObserveDataSourceConfigurationMainFactory(); + + Version modelVersion = applicationContext.getConfig().getModelVersion(); + + h2Config = configurationMainFactory.createObserveDataSourceConfigurationTopiaH2( + t("observe.storage.label.local"), + null, + ObserveSwingApplicationConfig.DB_NAME, + "", + EMPTY_PASSWORD, + false, + false, + modelVersion + ); + + pgConfig = configurationMainFactory.createObserveDataSourceConfigurationTopiaPG( + t("observe.storage.label.remote"), + "", + "", + EMPTY_PASSWORD, + false, + false, + false, + modelVersion + ); + + restConfig = configurationMainFactory.createObserveDataSourceConfigurationRest( + t("observe.storage.label.server"), + null, + "", + EMPTY_PASSWORD, + null, + modelVersion + ); + + PropertyChangeListener clearStatus = evt -> { + setConnexionStatus(ConnexionStatus.UNTESTED); + dataSourceInformation = null; + }; + + addPropertyChangeListener(REMOTE_URL_ROPERTY_NAME, clearStatus); + addPropertyChangeListener(REMOTE_LOGIN_ROPERTY_NAME, clearStatus); + addPropertyChangeListener(REMOTE_PASSWORD_PROPERTY_NAME, clearStatus); + addPropertyChangeListener(SERVER_DATABASE_PROPERTY_NAME, clearStatus); + addPropertyChangeListener(USE_SSL_PROPERTY_NAME, clearStatus); + } + + @Override + public void setStep(StorageStep step) { + setAlreadyApplied(false); + super.setStep(step); + } + + /** + * La méthode pour initialiser le modèle à partir du context applicatif et + * d'un service existant. + * + * @param context le context applicatif + * @param source le service existant + */ + public void init(JAXXContext context, ObserveDataSourceConfiguration source) { + + ObserveSwingApplicationConfig config = ObserveSwingApplicationContext.get().getConfig(); + + StorageUIModel incomingModel = WizardUILancher.newModelEntry(StorageUIModel.class).getContextValue(context); + + if (incomingModel != null) { + + if (log.isDebugEnabled()) { + log.debug("from a incoming model " + incomingModel.getLabel() + " : " + incomingModel); + } + + // on initialie a partir d'un autre modèle + incomingModel.copyTo(this); + + return; + } + + StorageUIHandler storageUIHandler = context.getContextValue(StorageUIHandler.class); + + // ajout paramétrage depuis la configuration + + boolean isLocalStorageExist = config.isLocalStorageExist(); + setLocalStorageExist(isLocalStorageExist); + if (!isLocalStorageExist) { + + // on force a ne pas pouvoir utilisaer la base locale + setCanUseLocalService(false); + } + + if (log.isDebugEnabled()) { + log.debug("Local storage exists ? " + isLocalStorageExist()); + log.debug("can use local storage ? " + isCanUseLocalService()); + log.debug("can create local storage ? " + isCanCreateLocalService()); + log.debug("can use remote storage ? " + isCanUseRemoteService()); + log.debug("can use server storage ? " + isCanUseServerService()); + log.debug("previous service ? " + source); + } + + setStoreRemoteConfig(config.isStoreRemoteStorage()); + setBackupFile(new File(config.getBackupDirectory(), storageUIHandler.getDefaultBackupFilename())); + setDumpFile(config.getBackupDirectory()); + setShowMigrationProgression(config.isShowMigrationProgression()); + setShowMigrationSql(config.isShowMigrationSql()); + setDoBackup(false); + setPreviousDataSourceConfiguration(source); + + if (log.isDebugEnabled()) { + log.debug("canMigrate ? " + isCanMigrate()); + } + + CreationMode mode = config.getDefaultCreationMode(); + + // on initialise les configuration avec les valeurs par défaut + h2Config = config.getDataSourceConfigurationH2(t("observe.storage.label.local")); + pgConfig = config.getDataSourceConfigurationPG(t("observe.storage.label.remote")); + restConfig = config.getDataSourceConfigurationRest(t("observe.storage.label.server")); + + if (source != null) { + + // on initialise le modèle à partir d'un service existant + + if (log.isDebugEnabled()) { + log.debug("from a previous service " + source); + } + + if (source instanceof ObserveDataSourceConfigurationTopiaH2) { + + // on est actuellement connecte sur une base locale + fromStorageConfig((ObserveDataSourceConfigurationTopiaH2) source); + + } else if (source instanceof ObserveDataSourceConfigurationTopiaPG) { + + if (!isLocalStorageExist) { + // aucune base locale, on positionne le mode de création + // de base locale par défaut. + + setCreationMode(mode); + } + + // on est sur une base distante + fromStorageConfig((ObserveDataSourceConfigurationTopiaPG) source); + + } else if (source instanceof ObserveDataSourceConfigurationRest) { + + // on est sur une base distante + fromStorageConfig((ObserveDataSourceConfigurationRest) source); + } + + return; + } + + if (log.isDebugEnabled()) { + log.debug("no service found, using default configuration"); + } + + DbMode newDbMode = config.getDefaultDbMode(); + if (getAdminAction() != null) { + + // une action d'admin obstuna toujours sur base distante + newDbMode = DbMode.USE_REMOTE; + } else { + if (isCanUseLocalService()) { + mode = null; + } else if (isCanCreateLocalService()) { + mode = CreationMode.IMPORT_EXTERNAL_DUMP; + } else if (isCanUseRemoteService()) { + mode = CreationMode.IMPORT_REMOTE_STORAGE; + } else if (isCanUseServerService()) { + mode = CreationMode.IMPORT_SERVER_STORAGE; + } + } + if (log.isDebugEnabled()) { + log.debug("Will use creationMode : " + mode); + } + setDbMode(newDbMode); + setCreationMode(mode); + } + + /** + * La méthode pour initialiser le modèle à partir du context applicatif et + * d'une configuration de source de donnée existante. + * + * @param context le context applicatif + * @param previousConfig la configuration de service existant + * @since 2.0 + */ + public void initFromPreviousConfig(JAXXContext context, + ObserveDataSourceConfiguration previousConfig, + ObserveDataSourceInformation previousInfo) { + + Objects.requireNonNull(previousConfig, "previousConfig parameter can not be null in method initFromPreviousConfig"); + + ObserveSwingApplicationConfig config = ObserveSwingApplicationContext.get().getConfig(); + + StorageUIHandler storageUIHandler = context.getContextValue(StorageUIHandler.class); + + // ajout paramétrage depuis la configuration + + boolean isLocalStorageExist = config.isLocalStorageExist(); + setLocalStorageExist(isLocalStorageExist); + + if (log.isDebugEnabled()) { + log.debug("Local storage exists ? " + isLocalStorageExist()); + log.debug("can use local storage ? " + isCanUseLocalService()); + log.debug("can create local storage ? " + isCanCreateLocalService()); + log.debug("can use remote storage ? " + isCanUseRemoteService()); + log.debug("can use server storage ? " + isCanUseServerService()); + log.debug("previous service ? " + previousConfig); + } + + setStoreRemoteConfig(config.isStoreRemoteStorage()); + setBackupFile(new File(config.getBackupDirectory(), storageUIHandler.getDefaultBackupFilename())); + setDumpFile(config.getBackupDirectory()); + setShowMigrationProgression(config.isShowMigrationProgression()); + setShowMigrationSql(config.isShowMigrationSql()); + setDoBackup(false); + + if (log.isDebugEnabled()) { + log.debug("canMigrate ? " + isCanMigrate()); + } + + // on initialise les configuration avec les valeurs par défaut + h2Config = config.getDataSourceConfigurationH2(t("observe.storage.label.local")); + pgConfig = config.getDataSourceConfigurationPG(t("observe.storage.label.remote")); + restConfig = config.getDataSourceConfigurationRest(t("observe.storage.label.server")); + + if (previousConfig instanceof ObserveDataSourceConfigurationTopiaH2) { + + // on est actuellement connecte sur une base locale + fromStorageConfig((ObserveDataSourceConfigurationTopiaH2) previousConfig); + h2DataSourceInformation = previousInfo; + } else if (previousConfig instanceof ObserveDataSourceConfigurationTopiaPG) { + + if (!isLocalStorageExist) { + + // aucune base locale, on ne peut pas utiliser la base locale + setCanUseLocalService(false); + } + + // on est sur une base distante + fromStorageConfig((ObserveDataSourceConfigurationTopiaPG) previousConfig); + + } else if (previousConfig instanceof ObserveDataSourceConfigurationRest) { + + // on est sur une base distante + fromStorageConfig((ObserveDataSourceConfigurationRest) previousConfig); + } + setDataSourceInformation(previousInfo); + } + + /** + * La méthode pour initialiser le modèle à partir du context applicatif et + * d'un service existant. + */ + public void initFromModel() { + + ObserveSwingApplicationConfig config = ObserveSwingApplicationContext.get().getConfig(); + + + // ajout paramétrage depuis la configuration + boolean isLocalStorageExist = config.isLocalStorageExist(); + setLocalStorageExist(isLocalStorageExist); + if (!isLocalStorageExist) { + + // on force a ne pas pouvoir utilisaer la base locale + setCanUseLocalService(false); + } + + if (log.isDebugEnabled()) { + log.debug("Local storage exists ? " + isLocalStorageExist()); + log.debug("can use local storage ? " + isCanUseLocalService()); + log.debug("can create local storage ? " + isCanCreateLocalService()); + log.debug("can use remote storage ? " + isCanUseRemoteService()); + log.debug("can use server storage ? " + isCanUseServerService()); + } + + setStoreRemoteConfig(config.isStoreRemoteStorage()); + setDumpFile(config.getBackupDirectory()); + setShowMigrationProgression(config.isShowMigrationProgression()); + setShowMigrationSql(config.isShowMigrationSql()); + setDoBackup(false); + setPreviousDataSourceConfiguration(null); + + if (log.isDebugEnabled()) { + log.debug("canMigrate ? " + isCanMigrate()); + } + + CreationMode mode = config.getDefaultCreationMode(); + + if (log.isDebugEnabled()) { + log.debug("no service found, using default configuration"); + } + + // aucun service de persistance ouvert, + // on utilise la configuration par defaut + // ce cas ne devrait arriver uniquement tant qu'aucune + // base locale est crée + h2Config = config.getDataSourceConfigurationH2(t("observe.storage.label.local")); + pgConfig = config.getDataSourceConfigurationPG(t("observe.storage.label.remote")); + restConfig = config.getDataSourceConfigurationRest(t("observe.storage.label.server")); + + DbMode newDbMode = config.getDefaultDbMode(); + if (getAdminAction() != null) { + + // une action d'admin obstuna toujours sur base distante + newDbMode = DbMode.USE_REMOTE; + } else { + if (isCanUseLocalService()) { + mode = null; + } else if (isCanCreateLocalService()) { + mode = CreationMode.IMPORT_EXTERNAL_DUMP; + } else if (isCanUseRemoteService()) { + mode = CreationMode.IMPORT_REMOTE_STORAGE; + } else if (isCanUseServerService()) { + mode = CreationMode.IMPORT_SERVER_STORAGE; + } + } + if (log.isDebugEnabled()) { + log.debug("Will use creationMode : " + mode); + } + setDbMode(newDbMode); + setCreationMode(mode); + } + + protected void startCentralSourceModel() { + + if (!isNeedReferentielDataSource()) { + + // pas besoin de la base distante + return; + } + + // par default, on tente d'utiliser la base distance + getCentralSourceModel().initFromModel(); + centralSourceModel.setCanCreateLocalService(false); + centralSourceModel.setCanUseLocalService(false); + centralSourceModel.setCanUseRemoteService(true); + centralSourceModel.setCanUseServerService(true); + centralSourceModel.start(DbMode.USE_REMOTE); + + if (log.isDebugEnabled()) { + centralSourceModel.removePropertyChangeListener(LOG_PROPERTY_CHANGE_LISTENER); + centralSourceModel.addPropertyChangeListener(LOG_PROPERTY_CHANGE_LISTENER); + } + + // on teste si la connexion distante existe + if (centralSourceModel.isValid()) { + centralSourceModel.testRemote(); + } + } + + protected void startCentralDataSourceModel() { + + if (!isNeedDataDataSource()) { + + // pas besoin de la base distante + return; + } + + // par default, on tente d'utiliser la base distance + getDataSourceModel().initFromModel(); + dataSourceModel.setCanCreateLocalService(false); + dataSourceModel.setCanUseLocalService(false); + dataSourceModel.setCanUseRemoteService(true); + dataSourceModel.setCanUseServerService(true); + dataSourceModel.start(DbMode.USE_REMOTE); + + if (log.isDebugEnabled()) { + dataSourceModel.removePropertyChangeListener(LOG_PROPERTY_CHANGE_LISTENER); + dataSourceModel.addPropertyChangeListener(LOG_PROPERTY_CHANGE_LISTENER); + } + + // on teste si la connexion distante existe + if (dataSourceModel.isValid()) { + dataSourceModel.testRemote(); + } + } + + public boolean isNeedReferentielDataSource() { + return adminAction != null && + adminAction == ObstunaAdminAction.CREATE; + } + + public boolean isNeedDataDataSource() { + return adminAction != null && + adminAction == ObstunaAdminAction.CREATE; + } + + public void start(DbMode dbMode) { + + if (log.isDebugEnabled()) { + log.debug("Will use dbMode : " + dbMode + " vs previous mode " + getDbMode()); + } + setDbMode(dbMode); + + startCentralSourceModel(); + startCentralDataSourceModel(); + + start(); + firePropertyChange(DB_MODE_PROPERTY_NAME, getDbMode()); + firePropertyChange(CREATION_MODE_PROPERTY_NAME, getCreationMode()); + firePropertyChange(DUMP_FILE_PROPERTY_NAME, getDumpFile()); + firePropertyChange(BACKUP_FILE_PROPERTY_NAME, getBackupFile()); + firePropertyChange(DO_BACKUP_PROPERTY_NAME, isDoBackup()); + firePropertyChange(CAN_USE_LOCALE_SERVICE_PROPERTY_NAME, isCanUseLocalService()); + firePropertyChange(CAN_CREATE_LOCALE_SERVICE_PROPERTY_NAME, isCanCreateLocalService()); + firePropertyChange(CAN_USE_REMOTE_SERVICE_PROPERTY_NAME, isCanUseRemoteService()); + firePropertyChange(CAN_USE_SERVER_SERVICE_PROPERTY_NAME, isCanUseServerService()); + firePropertyChange(CONNEXION_STATUS_PROPERTY_NAME, getConnexionStatus()); + firePropertyChange(PREVIOUS_SERVICE_PROPERTY_NAME, getPreviousDataSourceConfiguration()); + firePropertyChange(LOCAL_STORAGE_EXIST_PROPERTY_NAME, isLocalStorageExist()); + firePropertyChange(STORE_REMOTE_CONFIG_PROPERTY_NAME, isStoreRemoteConfig()); + firePropertyChange(REMOTE_URL_ROPERTY_NAME, getRemoteUrl()); + firePropertyChange(REMOTE_LOGIN_ROPERTY_NAME, getRemoteLogin()); + firePropertyChange(REMOTE_PASSWORD_PROPERTY_NAME, getRemotePassword()); + firePropertyChange(SERVER_DATABASE_PROPERTY_NAME, getServerDatabase()); + + firePropertyChange(EDIT_REMOTE_CONFIG_PROPERTY_NAME, isEditRemoteConfig()); + firePropertyChange(EDIT_SERVER_CONFIG_PROPERTY_NAME, isEditServerConfig()); + + firePropertyChange(USE_SSL_PROPERTY_NAME, null, isUseSsl()); + firePropertyChange(CAN_MIGRATE_PROPERTY_NAME, isCanMigrate()); + firePropertyChange(SHOW_MIGRATION_SQL_PROPERTY_NAME, isShowMigrationSql()); + firePropertyChange(SHOW_MIGRATION_PROGRESSION_PROPERTY_NAME, isShowMigrationProgression()); + } + + public boolean isCanUseLocalService() { + return canUseLocalService; + } + + public boolean isCanCreateLocalService() { + return canCreateLocalService; + } + + public boolean isCanUseRemoteService() { + return canUseRemoteService; + } + + public boolean isCanUseServerService() { + return canUseServerService; + } + + public SecurityModel getSecurityModel() { + return securityModel; + } + + public ObstunaAdminAction getAdminAction() { + return adminAction; + } + + public String getAdminActionLabel() { + return t(getAdminAction().getLabel()); + } + + public DataSelectionModel getSelectDataModel() { + return selectDataModel; + } + + public void setSelectDataModel(DataSelectionModel selectDataModel) { + this.selectDataModel = selectDataModel; + } + + public CreationMode getReferentielImportMode() { + return referentielImportMode; + } + + public CreationMode getDataImportMode() { + return dataImportMode; + } + + public boolean isImportReferentiel() { + return referentielImportMode != null && CreationMode.EMPTY != referentielImportMode; + } + + public boolean isImportData() { + return dataImportMode != null && CreationMode.EMPTY != dataImportMode; + } + + public StorageUIModel getCentralSourceModel() { + if (centralSourceModel == null) { + centralSourceModel = new StorageUIModel() { + + @Override + public String getLabel() { + String txt = t("observe.storage.label.import.referentiel"); + if (getDbMode() == DbMode.CREATE_LOCAL) { + txt = t("observe.storage.label.import.referentiel", getH2Config().getDirectory().getAbsolutePath()); + } else if (isRemote()) { + txt = t("observe.storage.label.import.referentiel.remote", getRemoteUrl()); + } else if (isServer()) { + txt = t("observe.storage.label.import.referentiel.server", getServerUrl()); + } + return txt; + } + + @Override + public void validate() { + super.validate(); + + // on declanche la revalidation du modèle + StorageUIModel.this.firePropertyChange(VALID_PROPERTY_NAME, isValid()); + } + }; + } + return centralSourceModel; + } + + public StorageUIModel getDataSourceModel() { + if (dataSourceModel == null) { + dataSourceModel = new StorageUIModel() { + + @Override + public String getLabel() { + String txt = t("observe.storage.label.import.data"); + if (getDbMode() == DbMode.CREATE_LOCAL) { + txt = t("observe.storage.label.import.data", getH2Config().getDirectory().getAbsolutePath()); + } else if (isRemote()) { + txt = t("observe.storage.label.import.data.remote", getRemoteUrl()); + } else if (isServer()) { + txt = t("observe.storage.label.import.data.server", getServerUrl()); + } + return txt; + } + + @Override + public void validate() { + super.validate(); + + // on declanche la revalidation du modèle + StorageUIModel.this.firePropertyChange(VALID_PROPERTY_NAME, isValid()); + } + }; + } + return dataSourceModel; + } + + public void setAdminAction(ObstunaAdminAction adminAction) { + this.adminAction = adminAction; + } + + protected void firePropertyChange(String propertyName, Object newValue) { + firePropertyChange(propertyName, null, newValue); + } + + @Override + public void updateUniverse() { + if (dbMode == null) { + + // pas de mode choisi donc l'univers ne change pas + return; + } + List<StorageStep> universe = new ArrayList<>(); + if (adminAction == null) { + + // when doing an admin mode we do not choose db mode, we always work on remote + universe.add(StorageStep.CHOOSE_DB_MODE); + } + + boolean canBackup = localStorageExist; + switch (dbMode) { + case CREATE_LOCAL: + CreationMode creationMode = getCreationMode(); + + if (creationMode != null) { + switch (creationMode) { + case IMPORT_EXTERNAL_DUMP: + universe.add(StorageStep.CONFIG); + break; + //case IMPORT_LOCAL_STORAGE: + case IMPORT_REMOTE_STORAGE: + importDataConfig = pgConfig; + universe.add(StorageStep.CONFIG); + break; + case IMPORT_SERVER_STORAGE: + importDataConfig = restConfig; + universe.add(StorageStep.CONFIG); + break; + } + } + break; + case USE_LOCAL: + // pas de backup si on veut utiliser la base locale + canBackup = false; + break; + case USE_REMOTE: + canBackup = false; + universe.add(StorageStep.CONFIG); + break; + case USE_SERVER: + canBackup = false; + universe.add(StorageStep.CONFIG); + break; + } + if (canBackup) { + universe.add(StorageStep.BACKUP); + + // when backup is possible always + setDoBackup(true); + } + if (adminAction != null) { + if (adminAction == ObstunaAdminAction.CREATE) { + universe.add(StorageStep.CONFIG_REFERENTIEL); + + if (getReferentielImportMode() != null && getReferentielImportMode() != CreationMode.EMPTY) { + + // can import data only if import a referentiel + universe.add(StorageStep.CONFIG_DATA); + } + + if (getDataImportMode() != null && getDataImportMode() != CreationMode.EMPTY) { + universe.add(StorageStep.SELECT_DATA); + } + } + universe.add(StorageStep.ROLES); + } + universe.add(StorageStep.CONFIRM); + if (excludeSteps != null) { + universe.removeAll(excludeSteps); + } + if (log.isDebugEnabled()) { + log.debug("steps to use : " + universe); + } + setSteps(universe.toArray(new StorageStep[universe.size()])); + } + + @Override + public boolean validate(StorageStep s) { + boolean validate = super.validate(s); + if (validate) { + switch (s) { + case CHOOSE_DB_MODE: + validate = dbMode != null; + if (validate) { + if (!isCanUseRemoteService() && dbMode.equals(DbMode.USE_REMOTE)) { + validate = false; + } else if (!isCanUseLocalService() && dbMode.equals(DbMode.USE_LOCAL)) { + validate = false; + } else if (!isCanCreateLocalService() && dbMode.equals(DbMode.CREATE_LOCAL)) { + validate = false; + } else if (!isCanUseServerService() && dbMode.equals(DbMode.USE_SERVER)) { + validate = false; + } + } + if (validate && isLocal()) { + if (dbMode == DbMode.CREATE_LOCAL) { + validate = getCreationMode() != null; + } + } + break; + case CONFIG: + if (DbMode.USE_REMOTE.equals(dbMode) + || DbMode.USE_SERVER.equals(dbMode) + || DbMode.CREATE_LOCAL.equals(dbMode) + && (CreationMode.IMPORT_SERVER_STORAGE.equals(creationMode) + || CreationMode.IMPORT_REMOTE_STORAGE.equals(creationMode))) { + validate = ConnexionStatus.SUCCESS.equals(getConnexionStatus()); + //FIXME Il faut savoir si l'utilisateur est le + //FIXME propriétaire de la base +// if (validate) { +// if (getAdminAction() != null) { +// +// // il faut des droits rw sur la base distante +// validate = dataSourceInformation != null && +// dataSourceInformation.canReadReferential() && +// dataSourceInformation.canWriteReferential() && +// dataSourceInformation.canWriteData() && +// dataSourceInformation.canReadData(); +// } +// } + } else if (DbMode.CREATE_LOCAL.equals(dbMode) && CreationMode.IMPORT_EXTERNAL_DUMP.equals(creationMode)) { + validate = isValidDumpFile(dumpFile); + } + break; + case CONFIG_REFERENTIEL: + + switch (getReferentielImportMode()) { + + case EMPTY: + validate = true; + break; + case IMPORT_LOCAL_STORAGE: + case IMPORT_INTERNAL_DUMP: + + break; + case IMPORT_EXTERNAL_DUMP: + // external dumb must be filled + validate = isValidDumpFile(centralSourceModel.getDumpFile()); + break; + case IMPORT_REMOTE_STORAGE: + case IMPORT_SERVER_STORAGE: + // remote db connexion must be valid + validate = centralSourceModel.isValid(); + + if (validate) { + + // check remote db != remote import db + validate = !centralSourceModel.getRemoteUrl().equals( + getRemoteUrl()); + } + if (validate) { + + validate = centralSourceModel.getDataSourceInformation().canReadReferential(); + } + break; + } + + break; + + case CONFIG_DATA: + + switch (getDataImportMode()) { + + case EMPTY: + validate = true; + break; + case IMPORT_LOCAL_STORAGE: + case IMPORT_INTERNAL_DUMP: + + break; + case IMPORT_EXTERNAL_DUMP: + // external dumb must be filled + validate = isValidDumpFile(dataSourceModel.getDumpFile()); + break; + case IMPORT_REMOTE_STORAGE: + // remote db connexion must be valid + validate = dataSourceModel.isValid(); + + if (validate) { + + // check remote db != remote import db + validate = !dataSourceModel.getRemoteUrl().equals(getRemoteUrl()); + + } + + if (validate) { + + validate = dataSourceModel.getDataSourceInformation().canReadData(); + + } + + break; + } + + break; + case BACKUP: + validate = !doBackup || + backupFile != null && + !backupFile.exists() && + backupFile.getName().endsWith(".sql.gz"); + break; + case SELECT_DATA: + // chemit 20100525 : aucune contrainte dans ce cas + validate = selectDataModel != null; + break; + case ROLES: + + Set<ObserveDbUserDto> role = getSecurityModel().getUsers(); + + int assigned = getSecurityModel().getAssigned(); + + validate = role.size() == assigned; + break; + case CONFIRM: + validate = true; + break; + } + } + return validate; + } + + public void validate() { + super.validate(); + + // toujours forcer la propagation + firePropertyChange(VALID_PROPERTY_NAME, isValid()); + } + + public boolean isValid() { + boolean result = false; + if (dbMode != null) { + switch (dbMode) { + + case CREATE_LOCAL: + result = getCreationMode() != null && + validate(StorageStep.CONFIG); + break; + case USE_REMOTE: + case USE_SERVER: + result = validate(StorageStep.CONFIG); + break; + case USE_LOCAL: + //TODO A tester... + result = h2Config.getDatabaseFile().exists(); + break; + } + } + return result; + } + + public boolean isAlreadyApplied() { + return alreadyApplied; + } + + public void setAlreadyApplied(boolean alreadyApplied) { + boolean oldValue = isAlreadyApplied(); + this.alreadyApplied = alreadyApplied; + firePropertyChange(ALREADY_APPLIED_PROPERTY_NAME, oldValue, alreadyApplied); + } + + public boolean isUseSelectData() { + return getSteps() != null && + getSteps().contains(StorageStep.SELECT_DATA); + } + + public boolean isBackupAction() { + return getSteps() != null && getStepIndex(StorageStep.BACKUP) == 0; + } + + public boolean isLocal() { + return dbMode != null && (dbMode == DbMode.CREATE_LOCAL || dbMode == DbMode.USE_LOCAL); + } + + public boolean isRemote() { + return dbMode != null && dbMode == DbMode.USE_REMOTE; + } + + public boolean isServer() { + return dbMode != null && dbMode == DbMode.USE_SERVER; + } + + public boolean isCanMigrate() { + boolean result = false; + if (dbMode != null) { + switch (dbMode) { + case USE_LOCAL: + result = true; + break; + case CREATE_LOCAL: + // en cration de base local on autorise les migration uniquement pour les imports de dump + result = CreationMode.IMPORT_EXTERNAL_DUMP.equals(creationMode) || CreationMode.IMPORT_INTERNAL_DUMP.equals(creationMode); + break; + case USE_REMOTE: + case USE_SERVER: + result = ObstunaAdminAction.UPDATE.equals(adminAction); + break; + } + } + return result; + } + + public String getLabel() { + String txt; + if (dbMode == DbMode.CREATE_LOCAL) { + txt = h2Config.getLabel(); + } else { + if (isRemote()) { + txt = pgConfig.getLabel(); + } else { + txt = restConfig.getLabel(); + } + } + return txt; + } + + public boolean isLocalStorageExist() { + return localStorageExist; + } + + public boolean isStoreRemoteConfig() { + return storeRemoteConfig; + } + + public File getBackupFile() { + return backupFile; + } + + public boolean isDoBackup() { + return doBackup; + } + + public Version getModelVersion() { + return ObserveSwingApplicationContext.get().getConfig().getModelVersion(); + } + + public DbMode getDbMode() { + return dbMode; + } + + public boolean isEditRemoteConfig() { + return editRemoteConfig; + } + + public boolean isEditServerConfig() { + return editServerConfig; + } + + public ObserveDataSourceConfiguration getPreviousDataSourceConfiguration() { + return previousDataSourceConfiguration; + } + + public void setDbMode(DbMode dbMode) { + DbMode oldValue = this.dbMode; + this.dbMode = dbMode; + firePropertyChange(DB_MODE_PROPERTY_NAME, oldValue, dbMode); + updateEditConfig(); + if (oldValue != dbMode) { + + // on recalcule l'univers des étapes disponibles + updateUniverse(); + } + + // validation du modèle + validate(); + + // le drapeau canMigrate peut avoir changé, on doit notifié les écouteurs + firePropertyChange(CAN_MIGRATE_PROPERTY_NAME, null, isCanMigrate()); + } + + protected void updateEditConfig() { + + boolean oldValueRemote = isEditRemoteConfig(); + boolean oldValueServer = isEditServerConfig(); + + editRemoteConfig = DbMode.USE_REMOTE.equals(dbMode) || + DbMode.CREATE_LOCAL.equals(dbMode) && CreationMode.IMPORT_REMOTE_STORAGE.equals(creationMode); + firePropertyChange(EDIT_REMOTE_CONFIG_PROPERTY_NAME, oldValueRemote, editRemoteConfig); + + editServerConfig = DbMode.USE_SERVER.equals(dbMode) || + DbMode.CREATE_LOCAL.equals(dbMode) && CreationMode.IMPORT_SERVER_STORAGE.equals(creationMode); + firePropertyChange(EDIT_SERVER_CONFIG_PROPERTY_NAME, oldValueServer, editServerConfig); + } + + public void updateEditConfigValues() { + + if (isEditRemoteConfig()) { + // bind from pg config model + setRemoteLogin(pgConfig.getUsername()); + setRemoteUrl(pgConfig.getJdbcUrl()); + setRemotePassword(pgConfig.getPassword()); + } + + if (isEditServerConfig()) { + // bind from rest config model + setRemoteLogin(restConfig.getLogin()); + setRemoteUrl(restConfig.getServerUrl() == null ? "" : restConfig.getServerUrl().toString()); + setRemotePassword(restConfig.getPassword()); + setServerDatabase(restConfig.getOptionalDatabaseName().orElse(null)); + } + + } + + public void setLocalStorageExist(boolean localStorageExist) { + boolean oldValue = this.localStorageExist; + this.localStorageExist = localStorageExist; + firePropertyChange(LOCAL_STORAGE_EXIST_PROPERTY_NAME, oldValue, + localStorageExist); + validate(); + } + + public void setStoreRemoteConfig(boolean storeRemoteConfig) { + boolean oldValue = this.storeRemoteConfig; + this.storeRemoteConfig = storeRemoteConfig; + firePropertyChange(STORE_REMOTE_CONFIG_PROPERTY_NAME, oldValue, + storeRemoteConfig); + } + + public void setDoBackup(boolean doBackup) { + boolean oldValue = this.doBackup; + this.doBackup = doBackup; + firePropertyChange(DO_BACKUP_PROPERTY_NAME, oldValue, doBackup); + } + + public void setBackupFile(File backupFile) { + File oldValue = this.backupFile; + this.backupFile = backupFile; + firePropertyChange(BACKUP_FILE_PROPERTY_NAME, oldValue, backupFile); + validate(); + } + + public void setReferentielImportMode(CreationMode referentielImportMode) { + CreationMode oldValue = this.referentielImportMode; + this.referentielImportMode = referentielImportMode; + firePropertyChange(REFERENTIEL_IMPORT_MODE_PROPERTY_NAME, + oldValue, + referentielImportMode); + + if (oldValue != referentielImportMode) { + updateUniverse(); + } + validate(); + } + + public void setDataImportMode(CreationMode dataImportMode) { + CreationMode oldValue = this.dataImportMode; + this.dataImportMode = dataImportMode; + firePropertyChange(DATA_IMPORT_MODE_PROPERTY_NAME, + oldValue, + dataImportMode); + if (oldValue != dataImportMode) { + + // reset selected data to import + setSelectDataModel(null); + + updateUniverse(); + } + validate(); + } + + public void setExcludeSteps(List<StorageStep> excludeSteps) { + this.excludeSteps = excludeSteps; + } + + public void destroy() { + super.destroy(); + } + + public void setShowMigrationSql(boolean showMigrationSql) { + boolean oldValue = pgConfig.isShowMigrationSql(); + pgConfig.setShowMigrationSql(showMigrationSql); + h2Config.setShowMigrationSql(showMigrationSql); + firePropertyChange(SHOW_MIGRATION_SQL_PROPERTY_NAME, oldValue, showMigrationSql); + } + + public void setShowMigrationProgression(boolean showMigrationProgression) { + boolean oldValue = pgConfig.isShowMigrationProgression(); + pgConfig.setShowMigrationProgression(showMigrationProgression); + h2Config.setShowMigrationProgression(showMigrationProgression); + firePropertyChange(SHOW_MIGRATION_PROGRESSION_PROPERTY_NAME, oldValue, showMigrationProgression); + } + + // ---------------------------------------------------------- + // -- h2Config delegate methods + // ---------------------------------------------------------- + + public CreationMode getCreationMode() { + return creationMode; + } + + public File getDumpFile() { + return dumpFile; + } + + public void setCreationMode(CreationMode creationMode) { + CreationMode oldValue = getCreationMode(); + this.creationMode = creationMode; + firePropertyChange(CREATION_MODE_PROPERTY_NAME, oldValue, creationMode); + updateEditConfig(); + if (oldValue != creationMode) { + updateUniverse(); + } + if (CreationMode.IMPORT_REMOTE_STORAGE.equals(creationMode) || CreationMode.IMPORT_SERVER_STORAGE.equals(creationMode)) { + //TC-20100308 : dans le cas d'un import du référentiel distant + //TC-20100308 : on utilise toujours l'utilisateur referentiel + String s = getRemoteLogin(); + if (s != null && !LOGIN_REFERENTIEL.equals(s)) { + setRemoteLogin(LOGIN_REFERENTIEL); + setRemotePassword(EMPTY_PASSWORD); + } + } + validate(); + } + + public void setDumpFile(File dumpFile) { + File oldValue = this.dumpFile; + this.dumpFile = dumpFile; + firePropertyChange(DUMP_FILE_PROPERTY_NAME, oldValue, dumpFile); + validate(); + } + + // ---------------------------------------------------------- + // -- pg2Config delegate methods + // ---------------------------------------------------------- + + public String getRemoteLogin() { + String login = ""; + + if (isEditRemoteConfig()) { + + login = pgConfig.getUsername(); + + } else if (isEditServerConfig()) { + + login = restConfig.getLogin(); + + } + return login; + } + + public char[] getRemotePassword() { + char[] password = EMPTY_PASSWORD; + + if (isEditRemoteConfig()) { + + password = pgConfig.getPassword(); + + } else if (isEditServerConfig()) { + + password = restConfig.getPassword(); + + } + return password; + } + + public String getRemoteUrl() { + String url = ""; + + if (isEditRemoteConfig()) { + + url = pgConfig.getJdbcUrl(); + + } else if (isEditServerConfig()) { + + url = serverUrl; + + } + return url; + } + + protected String getServerUrl() { + return serverUrl; + } + + protected void setServerUrl(String serverUrl) { + this.serverUrl = serverUrl; + } + + public boolean isUseSsl() { + return pgConfig.isUseSsl(); + } + + public String getServerDatabase() { + return restConfig.getOptionalDatabaseName().orElse(null); + } + + public ConnexionStatus getConnexionStatus() { + return connexionStatus; + } + + public void setPreviousDataSourceConfiguration(ObserveDataSourceConfiguration previousDataSourceConfiguration) { + this.previousDataSourceConfiguration = previousDataSourceConfiguration; + } + + public ObserveDataSourceConfigurationTopiaH2 getH2Config() { + return h2Config; + } + + public ObserveDataSourceConfigurationTopiaPG getPgConfig() { + return pgConfig; + } + + public ObserveDataSourceConfigurationRest getRestConfig() { + return restConfig; + } + + public void setRemoteLogin(String remoteLogin) { + +// String oldValue = getRemoteLogin(); + + if (isEditRemoteConfig()) { + + pgConfig.setUsername(remoteLogin); + + } else if (isEditServerConfig()) { + + restConfig.setLogin(remoteLogin); + + } + + firePgConfigChanged(REMOTE_LOGIN_ROPERTY_NAME, null, remoteLogin); + } + + public void setRemotePassword(char... remotePassword) { +// char[] oldValue = getRemotePassword(); + + if (isEditRemoteConfig()) { + + pgConfig.setPassword(remotePassword); + + } else if (isEditServerConfig()) { + + restConfig.setPassword(remotePassword); + + } + firePgConfigChanged(REMOTE_PASSWORD_PROPERTY_NAME, null, remotePassword); + } + + public void setCanUseLocalService(boolean canUseLocalService) { + this.canUseLocalService = canUseLocalService; + firePgConfigChanged(CAN_USE_LOCALE_SERVICE_PROPERTY_NAME, null, + canUseLocalService); + } + + public void setCanCreateLocalService(boolean canCreateLocalService) { + this.canCreateLocalService = canCreateLocalService; + firePgConfigChanged(CAN_CREATE_LOCALE_SERVICE_PROPERTY_NAME, null, + canCreateLocalService); + } + + public void setCanUseRemoteService(boolean canUseRemoteService) { + this.canUseRemoteService = canUseRemoteService; + firePropertyChange(CAN_USE_REMOTE_SERVICE_PROPERTY_NAME, null, canUseRemoteService); + } + + public void setCanUseServerService(boolean canUseServerService) { + this.canUseServerService = canUseServerService; + firePropertyChange(CAN_USE_SERVER_SERVICE_PROPERTY_NAME, null, canUseServerService); + } + + public void setRemoteUrl(String remoteUrl) { + if (isEditRemoteConfig()) { + + pgConfig.setJdbcUrl(remoteUrl); + + } else if (isEditServerConfig()) { + + serverUrl = remoteUrl; + + } + firePgConfigChanged(REMOTE_URL_ROPERTY_NAME, null, remoteUrl); + } + + public void setUseSsl(boolean useSsl) { + pgConfig.setUseSsl(useSsl); + firePgConfigChanged(USE_SSL_PROPERTY_NAME, null, useSsl); + } + + public void setServerDatabase(String database) { + if (StringUtils.isBlank(database)) { + restConfig.setOptionalDatabaseName(null); + } else { + restConfig.setOptionalDatabaseName(database); + } + firePgConfigChanged(SERVER_DATABASE_PROPERTY_NAME, null, database); + } + + // ---------------------------------------------------------- + // -- StorageConfigSupport implementation methods + // ---------------------------------------------------------- + + public void fromStorageConfig(ObserveDataSourceConfigurationTopiaH2 sourceConfig) { + + setDbMode(sourceConfig.getDatabaseFile().exists() ? DbMode.USE_LOCAL : DbMode.CREATE_LOCAL); + h2Config = sourceConfig; + } + + public void fromStorageConfig(ObserveDataSourceConfigurationTopiaPG sourceConfig) { + setDbMode(DbMode.USE_REMOTE); + pgConfig = sourceConfig; + } + + public void fromStorageConfig(ObserveDataSourceConfigurationRest sourceConfig) { + setDbMode(DbMode.USE_SERVER); + restConfig = sourceConfig; + } + + public DataSourceCreateConfigurationDto getCreationConfigurationDto() throws IOException, DatabaseConnexionNotAuthorizedException, DatabaseNotFoundException, BabModelVersionException { + + DataSourceCreateConfigurationDto result = null; + + if (getDbMode() == DbMode.CREATE_LOCAL) { + result = new DataSourceCreateConfigurationDto(); + + if (CreationMode.IMPORT_EXTERNAL_DUMP.equals(creationMode) || CreationMode.IMPORT_INTERNAL_DUMP.equals(creationMode)) { + + File dumpFile; + + if (CreationMode.IMPORT_EXTERNAL_DUMP.equals(creationMode)) { + dumpFile = getDumpFile(); + } else { + dumpFile = ObserveSwingApplicationContext.get().getConfig().getInitialDbDump(); + } + + byte[] dump = Files.readAllBytes(dumpFile.toPath()); + result.setImportDatabase(dump); + + } else { + + ObserveDataSourceConfiguration configSrc = null; + + switch (getCreationMode()) { + case IMPORT_LOCAL_STORAGE: + configSrc = h2Config; + break; + case IMPORT_REMOTE_STORAGE: + configSrc = pgConfig; + break; + case IMPORT_SERVER_STORAGE: + configSrc = restConfig; + break; + } + + if (configSrc != null) { + try (ObserveSwingDataSource source = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(configSrc)) { + + source.open(); + + SqlScriptProducerService dumpService = source.newSqlScriptProducerService(); + + AddSqlScriptProducerRequest request = AddSqlScriptProducerRequest.forH2().addSchema().addReferential(); + byte[] dump = dumpService.produceAddSqlScript(request); + + result.setImportDatabase(dump); + } + + } + + } + + } + + return result; + } + + public ObserveDataSourceConfigurationTopiaH2 toH2StorageConfig(String label) { + + ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); + ObserveDataSourceConfigurationMainFactory configurationFactory = context.getObserveDataSourceConfigurationMainFactory(); + ObserveDataSourceConfigurationTopiaH2 result = configurationFactory.createObserveDataSourceConfigurationTopiaH2( + label, + h2Config.getDirectory(), + h2Config.getDbName(), + h2Config.getUsername(), + h2Config.getPassword(), + h2Config.isShowMigrationProgression(), + h2Config.isShowMigrationSql(), + h2Config.getModelVersion() + ); + return result; + } + + public ObserveDataSourceConfigurationTopiaPG toPGStorageConfig(String label) { + + ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); + ObserveDataSourceConfigurationMainFactory configurationFactory = context.getObserveDataSourceConfigurationMainFactory(); + ObserveDataSourceConfigurationTopiaPG result = configurationFactory.createObserveDataSourceConfigurationTopiaPG( + label, + pgConfig.getJdbcUrl(), + pgConfig.getUsername(), + pgConfig.getPassword(), + pgConfig.isUseSsl(), + pgConfig.isShowMigrationProgression(), + pgConfig.isShowMigrationSql(), + pgConfig.getModelVersion() + ); + return result; + } + + public ObserveDataSourceConfigurationRest toRestStorageConfig(String label) { + + ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); + ObserveDataSourceConfigurationMainFactory configurationFactory = context.getObserveDataSourceConfigurationMainFactory(); + ObserveDataSourceConfigurationRest result = configurationFactory.createObserveDataSourceConfigurationRest( + label, + restConfig.getServerUrl(), + restConfig.getLogin(), + restConfig.getPassword(), + restConfig.getOptionalDatabaseName().orElse(null), + restConfig.getModelVersion() + ); + return result; + } + + protected void copyTo(StorageUIModel dst) { + dst.setLocalStorageExist(isLocalStorageExist()); + dst.setBackupFile(getBackupFile()); + dst.setDoBackup(isDoBackup()); + dst.setStoreRemoteConfig(isStoreRemoteConfig()); + dst.setPreviousDataSourceConfiguration(getPreviousDataSourceConfiguration()); + dst.setCanCreateLocalService(isCanCreateLocalService()); + dst.setCanUseLocalService(isCanUseLocalService()); + dst.setCanUseRemoteService(isCanUseRemoteService()); + dst.setCanUseServerService(isCanUseServerService()); + dst.fromStorageConfig(h2Config); + dst.fromStorageConfig(pgConfig); + dst.fromStorageConfig(restConfig); + dst.setDbMode(getDbMode()); + dst.setSelectDataModel(getSelectDataModel()); + dst.setSecurityModel(getSecurityModel()); + dst.setAdminAction(getAdminAction()); + + dst.updateEditConfig(); + + dst.setUseSsl(isUseSsl()); + dst.setRemoteUrl(getRemoteUrl()); + dst.setRemoteLogin(getRemoteLogin()); + dst.setRemotePassword(getRemotePassword()); + dst.setServerDatabase(getServerDatabase()); + + dst.setDataSourceInformation(getDataSourceInformation()); + dst.setConnexionStatus(getConnexionStatus()); + + } + + public void firePgConfigChanged(String propertyName, + Object oldValue, + Object newValue) { + firePropertyChange(propertyName, oldValue, newValue); + validate(); + } + + /** + * Teste une connexion à distance à partir du modèle passé en paramètre. + * + * @return {@code true} si la connexion a pu être établie, + * {@code false} sinon. + */ + public boolean testRemote() { + + ObserveDataSourceConfiguration config = null; + boolean result = false; + boolean error = false; + connexionStatusError = ""; + setBusy(true); + + try { + + if (isEditRemoteConfig()) { + config = pgConfig; + } else if (isEditServerConfig()) { + try { + URL url = new URL(serverUrl); + + restConfig.setServerUrl(url); + + config = restConfig; + + } catch (MalformedURLException e) { + + connexionStatusError = t("observe.storage.error.badUrl", serverUrl); + + setConnexionStatus(ConnexionStatus.FAILED); + + } + + } + + if (config != null) { + + ObserveSwingDataSource dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(config); + + try { + + if (DbMode.USE_SERVER.equals(getDbMode()) + || DbMode.CREATE_LOCAL.equals(getDbMode()) && CreationMode.IMPORT_SERVER_STORAGE.equals(creationMode)) { + + PingService pingService = dataSource.newPingService(); + + Version modelServerVersion = pingService.ping(); + + if (!getModelVersion().equals(modelServerVersion)) { + + connexionStatusError = t("observe.storage.error.serverVersionMismatch", modelServerVersion, getModelVersion()); + + setConnexionStatus(ConnexionStatus.FAILED); + + error = true; + } + + } + + if (!error) { + + dataSourceInformation = dataSource.checkCanConnect(); + + Version versionDataSource = dataSourceInformation.getVersion(); + + // en mise a jour de la base on ne test pas la version + if (getModelVersion().equals(versionDataSource) || isCanMigrate() || ObstunaAdminAction.CREATE.equals(adminAction)) { + + setConnexionStatus(ConnexionStatus.SUCCESS); + + result = true; + + } else { + + connexionStatusError = t("observe.storage.error.dbVersionMismatch", versionDataSource, getModelVersion()); + + setConnexionStatus(ConnexionStatus.FAILED); + + } + } + + } catch (UnknownObserveWebUserException e) { + + connexionStatusError = t("observe.storage.error.rest.user.unknown", e.getUserLogin()); + setConnexionStatus(ConnexionStatus.FAILED); + + } catch (BadObserveWebUserPasswordException e) { + + connexionStatusError = t("observe.storage.error.rest.password.bad", e.getUserLogin()); + setConnexionStatus(ConnexionStatus.FAILED); + + } catch (UnknownObserveWebUserForDatabaseException e) { + + connexionStatusError = t("observe.storage.error.rest.database.unknownForUser", e.getDatabaseName(), e.getRole()); + setConnexionStatus(ConnexionStatus.FAILED); + + } catch (UserLoginNotFoundException e) { + + connexionStatusError = t("observe.storage.error.rest.user.required"); + setConnexionStatus(ConnexionStatus.FAILED); + + } catch (UserPasswordNotFoundException e) { + + connexionStatusError = t("observe.storage.error.rest.pasword.required"); + setConnexionStatus(ConnexionStatus.FAILED); + + } catch (ObserveWebSecurityExceptionSupport e) { + + connexionStatusError = e.getClass().getSimpleName(); + setConnexionStatus(ConnexionStatus.FAILED); + + } catch (Exception e) { + + connexionStatusError = e.getMessage(); + + if (log.isErrorEnabled()) { + log.error("Error in test remote", e); + } + + setConnexionStatus(ConnexionStatus.FAILED); + + } finally { + if (dataSource.isOpen()) { + dataSource.close(); + } + } + } + + } finally { + setBusy(false); + } + + return result; + } + + + public String getConnexionStatusError() { + return connexionStatusError; + } + + public void setSecurityModel(SecurityModel securityModel) { + this.securityModel = securityModel; + } + + public boolean isShowMigrationSql() { + return pgConfig.isShowMigrationSql(); + } + + public boolean isShowMigrationProgression() { + return pgConfig.isShowMigrationProgression(); + } + + public void setConnexionStatus(ConnexionStatus connexionStatus) { + ConnexionStatus oldValue = this.connexionStatus; + this.connexionStatus = connexionStatus; + firePgConfigChanged(CONNEXION_STATUS_PROPERTY_NAME, oldValue, connexionStatus); + } + + public void checkImportDbVersion(ObserveSwingDataSource source) { + + Version importServiceDbVersion = source.getVersion(); + Version currentDbVersion = getModelVersion(); + if (importServiceDbVersion.before(currentDbVersion)) { + throw new IllegalStateException("Import db version (" + importServiceDbVersion + ") is not compatible with the current database version (" + currentDbVersion + ")"); + } + + } + + public DataSourceCreateConfigurationDto toImportReferentielSourceConfig() { + + DataSourceCreateConfigurationDto importReferenceConfig = new DataSourceCreateConfigurationDto(); + + // on peut créer une base vide + importReferenceConfig.setCanCreateEmptyDatabase(true); + + if (isImportReferentiel()) { + + String dbLabel = t("observe.storage.label.reference.import.db"); + + switch (getReferentielImportMode()) { + + case IMPORT_EXTERNAL_DUMP: + + if (ObstunaAdminAction.CREATE.equals(getAdminAction())) { + + // on import que le référentiel donc on créé un base temporaire pour cette import + ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); + + DataSourceCreateConfigurationDto createConfigurationDto = new DataSourceCreateConfigurationDto(); + + File dumpFile = getCentralSourceModel().getDumpFile(); + + try (FileInputStream inputStream = new FileInputStream(dumpFile)) { + + byte[] bytes = IOUtils.toByteArray(inputStream); + + createConfigurationDto.setImportDatabase(bytes); + + } catch (Exception e) { + + throw new RuntimeException("Could not read dump file", e); + + } + + try (ObserveSwingDataSource importDataSource = context.createTemporaryH2Storage(dbLabel)) { + + try { + importDataSource.create(createConfigurationDto); + } catch (IncompatibleDataSourceCreateConfigurationException + | DataSourceCreateWithNoReferentialImportException + | DatabaseNotFoundException + | DatabaseConnexionNotAuthorizedException + | BabModelVersionException e) { + throw new ObserveSwingTechnicalException("Could not create import data source", e); + } + + importReferenceConfig.setImportReferentialDataSourceConfiguration(importDataSource.getConfiguration()); + + } + + + } else { + + File dumpFile = getDumpFile(); + + try (FileInputStream inputStream = new FileInputStream(dumpFile)) { + + byte[] bytes = IOUtils.toByteArray(inputStream); + + importReferenceConfig.setImportDatabase(bytes); + + } catch (IOException e) { + + throw new RuntimeException("Could not read dump file", e); + + } + + } + + + break; + case IMPORT_REMOTE_STORAGE: + + // import referentiel from a remote db + ObserveDataSourceConfigurationTopiaPG pgConfig = getCentralSourceModel().toPGStorageConfig(dbLabel); + + pgConfig.setCanMigrate(false); + + importReferenceConfig.setImportReferentialDataSourceConfiguration(pgConfig); + + break; + + case IMPORT_SERVER_STORAGE: + + // import referentiel from a server db + ObserveDataSourceConfigurationRest restConfig = getCentralSourceModel().toRestStorageConfig(dbLabel); + + importReferenceConfig.setImportReferentialDataSourceConfiguration(restConfig); + + break; + + default: + throw new IllegalStateException("Can't come here"); + + } + + } + + return importReferenceConfig; + + + } + + public ObserveSwingDataSource toImportDataSourceConfig() { + + ObserveSwingDataSource importDataSource; + + if (isImportData()) { + + String dbLabel = t("observe.storage.label.data.import.db"); + + switch (getDataImportMode()) { + + case IMPORT_EXTERNAL_DUMP: + + ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); + + DataSourceCreateConfigurationDto createConfigurationDto = new DataSourceCreateConfigurationDto(); + + File dumpFile = ObstunaAdminAction.CREATE.equals(getAdminAction()) ? getDataSourceModel().getDumpFile() : getDumpFile(); + + try (FileInputStream inputStream = new FileInputStream(dumpFile)) { + + byte[] bytes = IOUtils.toByteArray(inputStream); + + createConfigurationDto.setImportDatabase(bytes); + + + } catch (Exception e) { + + throw new RuntimeException("Could not read dump file", e); + + } + + try (ObserveSwingDataSource importDataSource2 = context.createTemporaryH2Storage(dbLabel)) { + + importDataSource = importDataSource2; + + try { + importDataSource2.create(createConfigurationDto); + } catch (IncompatibleDataSourceCreateConfigurationException + | DataSourceCreateWithNoReferentialImportException + | DatabaseNotFoundException + | DatabaseConnexionNotAuthorizedException + | BabModelVersionException e) { + throw new ObserveSwingTechnicalException("Could not create import data source", e); + } + + } + + break; + case IMPORT_REMOTE_STORAGE: { + + // import referentiel from a remote db + ObserveDataSourceConfigurationTopiaPG dataSourceConfig = getDataSourceModel().toPGStorageConfig(dbLabel); + + dataSourceConfig.setCanMigrate(false); + + importDataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(dataSourceConfig); + + } + break; + + case IMPORT_SERVER_STORAGE: { + + // import referentiel from a server db + ObserveDataSourceConfigurationRest dataSourceConfig = getDataSourceModel().toRestStorageConfig(dbLabel); + + importDataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(dataSourceConfig); + + } + break; + default: + throw new IllegalStateException("Can't come here"); + } + + } else { + + importDataSource = null; + + } + + return importDataSource; + + } + + public ObserveDataSourceInformation getDataSourceInformation() { + if (DbMode.USE_LOCAL.equals(dbMode)) { + return getH2DataSourceInformation(); + } + + return dataSourceInformation; + } + + public ObserveDataSourceInformation getH2DataSourceInformation() { + if (h2DataSourceInformation == null && localStorageExist) { + ObserveSwingDataSource dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(h2Config); + try { + h2DataSourceInformation = dataSource.checkCanConnect(); + } catch (Exception e) { + if (log.isDebugEnabled()) { + log.debug("error on load data source information for local storage", e); + } + } + } + + return h2DataSourceInformation; + } + + public void setDataSourceInformation(ObserveDataSourceInformation dataSourceInformation) { + this.dataSourceInformation = dataSourceInformation; + } + + private boolean isValidDumpFile(File dumpFile) { + return dumpFile != null && + dumpFile.exists() && + dumpFile.getName().endsWith(".sql.gz"); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/package.html b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/package.html similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/storage/package.html rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/package.html diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/BackupUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/BackupUI.jaxx new file mode 100644 index 0000000..b09dc4a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/BackupUI.jaxx @@ -0,0 +1,86 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<!-- *************************************** --> +<!-- L'écran de sauvegarde de la base locale --> +<!-- *************************************** --> + +<StorageTabUI> + + <import> + fr.ird.observe.application.swing.ui.storage.StorageStep + java.io.File + </import> + + <StorageStep id='step' initializer='StorageStep.BACKUP'/> + + <fr.ird.observe.application.swing.ui.storage.StorageUIModel id='model'/> + + <script><![CDATA[ + +@Override +public void init() { + getHandler().initUI(this); +} +]]> + </script> + + <JPanel id='content'> + <Table fill='both' constraints='BorderLayout.CENTER'> + <row> + <cell columns='2'> + <JCheckBox id='doBackup' + onStateChanged='getModel().setDoBackup(((JCheckBox)event.getSource()).isSelected())'/> + </cell> + </row> + <row> + <cell weightx='1' fill="both"> + <Table fill='both'> + <row> + <cell> + <JLabel id="directoryLabel"/> + </cell> + <cell weightx='1' fill="horizontal"> + <JTextField id='directoryText' + onKeyReleased='getHandler().changeDirectory(this, new File(((JTextField)event.getSource()).getText()))'/> + </cell> + <cell anchor="east"> + <JButton id="chooseFileAction" + onActionPerformed="getHandler().chooseBackupFile(this)"/> + </cell> + </row> + <row> + <cell> + <JLabel id="fileLabel"/> + </cell> + <cell weightx='1' fill="horizontal" columns="2"> + <JTextField id='filenameText' + onKeyReleased='getHandler().changeFilename(this, ((JTextField) event.getSource()).getText())'/> + </cell> + </row> + </Table> + </cell> + </row> + </Table> + </JPanel> + +</StorageTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/BackupUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/BackupUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/BackupUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/BackupUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ChooseDbModeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ChooseDbModeUI.jaxx new file mode 100644 index 0000000..5ab2632 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ChooseDbModeUI.jaxx @@ -0,0 +1,109 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<!-- ***************************************** --> +<!-- L'écran de sélection de type de connexion --> +<!-- ***************************************** --> +<StorageTabUI> + + <import> + fr.ird.observe.application.swing.ObserveSwingApplicationContext + fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig + fr.ird.observe.application.swing.ui.UIHelper + fr.ird.observe.application.swing.ui.storage.StorageStep + fr.ird.observe.application.swing.db.constants.DbMode + fr.ird.observe.application.swing.db.constants.CreationMode + </import> + + <StorageStep id='step' initializer='StorageStep.CHOOSE_DB_MODE'/> + + <fr.ird.observe.application.swing.ui.storage.StorageUIModel id='model'/> + + <ObserveSwingApplicationConfig id='config' initializer="ObserveSwingApplicationContext.get().getConfig()"/> + + <ButtonGroup id='dbMode' onStateChanged='getModel().setDbMode((DbMode) dbMode.getSelectedValue())'/> + + <ButtonGroup id='creationMode' onStateChanged='getModel().setCreationMode((CreationMode) creationMode.getSelectedValue())'/> + + <CardLayout2Ext id='creationModeLayout' constructorParams='this, "creationModeContent"'/> + + <script><![CDATA[ +@Override +public void init() { + getHandler().initUI(this); +} + +protected String updateMigrationPolicy(boolean canMigrate) { + if (canMigrate) { + return t("observe.storage.report.can.migrate", config.getModelVersion()); + } else { + return t("observe.storage.report.can.not.migrate"); + } +} + +protected String updateCreationModeContent(DbMode mode) { + return mode == DbMode.CREATE_LOCAL ? "createMode" : "noCreateMode"; +} +]]> + </script> + + <JPanel id='content'> + + <JPanel layout='{new BorderLayout()}' constraints='BorderLayout.NORTH'> + <JPanel id='dbModeContent' constraints='BorderLayout.NORTH'> + <JRadioButton id="useLocalMode" styleClass='dbMode'/> + <JRadioButton id="useRemoteMode" styleClass='dbMode'/> + <JRadioButton id="useServerMode" styleClass='dbMode'/> + <JRadioButton id="createLocalMode" styleClass='dbMode'/> + </JPanel> + + <JPanel id='creationModeContent' constraints='BorderLayout.CENTER'> + + <JPanel id='useCreateMode' constraints='"createMode"'> + <JRadioButton id="importInternalDumpMode" styleClass='creationMode'/> + <JRadioButton id="importExternalDumpMode" styleClass='creationMode'/> + <JRadioButton id="importLocalStorageMode" styleClass='creationMode'/> + <JRadioButton id="importRemoteStorageMode" styleClass='creationMode'/> + <JRadioButton id="importServerStorageMode" styleClass='creationMode'/> + </JPanel> + <JLabel id='noCreateMode' constraints='"noCreateMode"'/> + + </JPanel> + + <JPanel id='migrationContent' constraints='BorderLayout.SOUTH'> + <JLabel id='migrationPolicy'/> + <JCheckBox id='showMigrationSql' + onStateChanged='getModel().setShowMigrationSql(((JCheckBox)event.getSource()).isSelected())'/> + <JCheckBox id='showMigrationProgression' + onStateChanged='getModel().setShowMigrationProgression(((JCheckBox)event.getSource()).isSelected())'/> + </JPanel> + </JPanel> + + <JScrollPane id="resumePane" constraints='BorderLayout.CENTER'> + <JTextPane id='resume'/> + </JScrollPane> + + </JPanel> + + <JScrollPane id="descriptionPane" visible='false'/> + +</StorageTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ChooseDbModeUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ChooseDbModeUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ChooseDbModeUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ChooseDbModeUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ConfigDataUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ConfigDataUI.jaxx new file mode 100644 index 0000000..22ffff5 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ConfigDataUI.jaxx @@ -0,0 +1,174 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<!-- ************************************************** --> +<!-- L'écran de configuration des données à importer --> +<!-- ************************************************** --> + +<StorageTabUI> + + <import> + fr.ird.observe.application.swing.db.constants.CreationMode + fr.ird.observe.application.swing.ui.storage.StorageStep + + javax.swing.Icon + + java.io.File + + static org.nuiton.i18n.I18n.n + </import> + + <StorageStep id='step' initializer='StorageStep.CONFIG_DATA'/> + + <fr.ird.observe.application.swing.ui.storage.StorageUIModel id='model'/> + <fr.ird.observe.application.swing.ui.storage.StorageUIModel id='centralSourceModel' initializer='model.getDataSourceModel()'/> + + <ButtonGroup id='creationMode' + onStateChanged='model.setDataImportMode((CreationMode) creationMode.getSelectedValue())'/> + + <CardLayout id='configLayout'/> + + <script><![CDATA[ +@Override +public void init() { + getHandler().initUI(this); +} +]]> + </script> + + <JPanel id='content' layout='{new BorderLayout()}'> + + <Table id="dataSourceConfig" insets="1" weightx='1' fill='both' + constraints='BorderLayout.CENTER'> + <row> + <cell anchor='north'> + <JPanel id='dataModeConfig'> + <JRadioButton id="noImportData" styleClass='creationMode'/> + <JRadioButton id="importDataFromBackup" styleClass='creationMode'/> + <JRadioButton id="importDataFromRemote" styleClass='creationMode'/> + <JRadioButton id="importDataFromServer" styleClass='creationMode'/> + </JPanel> + </cell> + </row> + <row> + <cell anchor='center'> + <JPanel id='configContent'> + + <!-- pas d'import de data --> + <Table id='EMPTY' constraints='"EMPTY"' fill='both'> + <row> + <cell> + <JLabel id='noImportDataConfig'/> + </cell> + </row> + </Table> + + <!-- importer des données a partir d'une sauvegarde --> + <Table id='IMPORT_EXTERNAL_DUMP' constraints='"IMPORT_EXTERNAL_DUMP"'> + <row> + <cell> + <JLabel text='observe.storage.importExternalDumpData.config'/> + </cell> + </row> + <row weighty='1'> + <cell weightx='1' fill="horizontal"> + <JTextField id="dumpFile" + onKeyReleased='centralSourceModel.setDumpFile(new File(((JTextField)event.getSource()).getText())); model.validate();'/> + </cell> + <cell anchor="east"> + <JButton id="fileChooserAction" + onActionPerformed="getHandler().chooseDumpFile(this)"/> + </cell> + </row> + </Table> + + <!-- importer les données a partir d'une base distante --> + <Table id='IMPORT_REMOTE_STORAGE' fill="both" + constraints='"IMPORT_REMOTE_STORAGE"'> + <row> + <cell> + <JLabel + text='observe.storage.importRemoteStorageData.config'/> + </cell> + </row> + <row> + <cell weightx='1' fill='both'> + <JLabel id='centralSourceLabel'/> + </cell> + <cell> + <JButton id='configureCentralSource' + onActionPerformed='getHandler().obtainRemoteConnexion(this)'/> + </cell> + <cell anchor='east'> + <JLabel id='centralSourceStatus'/> + </cell> + </row> + <row> + <cell fill='both' columns="2"> + <JLabel id='centralSourcePolicy'/> + </cell> + </row> + <row> + <cell fill='both' columns="2"> + <JLabel id='centralSourceInfoLabel'/> + </cell> + </row> + </Table> + + <!-- importer les données a partir d'une base distante --> + <Table id='IMPORT_SERVER_STORAGE' fill="both" + constraints='"IMPORT_SERVER_STORAGE"'> + <row> + <cell> + <JLabel + text='observe.storage.importServerStorageData.config'/> + </cell> + </row> + <row> + <cell weightx='1' fill='both'> + <JLabel id='centralSourceServerLabel'/> + </cell> + <cell> + <JButton id='configureCentralSourceServer' + onActionPerformed='getHandler().obtainServerConnexion(this)'/> + </cell> + <cell anchor='east'> + <JLabel id='centralSourceServerStatus'/> + </cell> + </row> + <row> + <cell fill='both' columns="2"> + <JLabel id='centralSourceServerPolicy'/> + </cell> + </row> + <row> + <cell fill='both' columns="2"> + <JLabel id='centralSourceServerInfoLabel'/> + </cell> + </row> + </Table> + </JPanel> + </cell> + </row> + </Table> + </JPanel> + +</StorageTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ConfigDataUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ConfigDataUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ConfigDataUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ConfigDataUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ConfigReferentielUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ConfigReferentielUI.jaxx new file mode 100644 index 0000000..09b1148 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ConfigReferentielUI.jaxx @@ -0,0 +1,181 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<!-- ************************************************** --> +<!-- L'écran de configuration du référentiel à importer --> +<!-- ************************************************** --> + +<StorageTabUI> + + <import> + fr.ird.observe.application.swing.db.constants.CreationMode + fr.ird.observe.application.swing.ui.storage.StorageStep + + javax.swing.Icon + + java.io.File + + static org.nuiton.i18n.I18n.n + </import> + + <StorageStep id='step' initializer='StorageStep.CONFIG_REFERENTIEL'/> + + <fr.ird.observe.application.swing.ui.storage.StorageUIModel id='model'/> + <fr.ird.observe.application.swing.ui.storage.StorageUIModel id='centralSourceModel' + initializer='model.getCentralSourceModel()'/> + + <ButtonGroup id='creationMode' + onStateChanged='model.setReferentielImportMode((CreationMode) creationMode.getSelectedValue())'/> + + <CardLayout id='configLayout'/> + + <script><![CDATA[ +@Override +public void init() { + getHandler().initUI(this); +} +]]> + </script> + + <JPanel id='content' layout='{new BorderLayout()}'> + + <Table id="referentielSourceConfig" insets="1" weightx='1' fill='both' + constraints='BorderLayout.CENTER'> + <row> + <cell anchor='north'> + <JPanel id='referentielModeConfig'> + <JRadioButton id="noImportReferentiel" styleClass='creationMode'/> + <JRadioButton id="importReferentielFromBackup" + styleClass='creationMode'/> + <JRadioButton id="importReferentielFromRemote" + styleClass='creationMode'/> + <JRadioButton id="importReferentielFromServer" + styleClass='creationMode'/> + </JPanel> + </cell> + </row> + <row> + <cell anchor='center'> + <JPanel id='configContent'> + + <!-- pas de referentiel --> + <Table id='EMPTY' constraints='"EMPTY"' fill='both'> + <row> + <cell> + <JLabel id='noImportReferentielConfig'/> + </cell> + </row> + </Table> + + <!-- importer le référentiel a partir d'une sauvegarde --> + <Table id='IMPORT_EXTERNAL_DUMP' + constraints='"IMPORT_EXTERNAL_DUMP"'> + <row> + <cell> + <JLabel + text='observe.storage.importExternalDumpReferentiel.config'/> + </cell> + </row> + <row weighty='1'> + <cell weightx='1' fill="horizontal"> + <JTextField id="dumpFile" + onKeyReleased='centralSourceModel.setDumpFile(new File(((JTextField)event.getSource()).getText())); model.validate();'/> + </cell> + <cell anchor="east"> + <JButton id="fileChooserAction" + onActionPerformed="getHandler().chooseDumpFile(this)"/> + </cell> + </row> + </Table> + + <!-- importer le référentiel a partir d'une base distante --> + <Table id='IMPORT_REMOTE_STORAGE' fill="both" + constraints='"IMPORT_REMOTE_STORAGE"'> + <row> + <cell> + <JLabel + text='observe.storage.importRemoteStorageReferentiel.config'/> + </cell> + </row> + <row> + <cell weightx='1' fill='both'> + <JLabel id='centralSourceLabel'/> + </cell> + <cell> + <JButton id='configureCentralSource' + onActionPerformed='getHandler().obtainRemoteConnexion(this)'/> + </cell> + <cell anchor='east'> + <JLabel id='centralSourceStatus'/> + </cell> + </row> + <row> + <cell fill='both' columns="2"> + <JLabel id='centralSourcePolicy'/> + </cell> + </row> + <row> + <cell fill='both' columns="2"> + <JLabel id='centralSourceInfoLabel'/> + </cell> + </row> + </Table> + + <!-- importer le référentiel a partir d'un serveur distant --> + <Table id='IMPORT_SERVER_STORAGE' fill="both" + constraints='"IMPORT_SERVER_STORAGE"'> + <row> + <cell> + <JLabel + text='observe.storage.importServerStorageReferentiel.config'/> + </cell> + </row> + <row> + <cell weightx='1' fill='both'> + <JLabel id='centralSourceServerLabel'/> + </cell> + <cell> + <JButton id='configureCentralSourceServer' + onActionPerformed='getHandler().obtainServerConnexion(this)'/> + </cell> + <cell anchor='east'> + <JLabel id='centralSourceServerStatus'/> + </cell> + </row> + <row> + <cell fill='both' columns="2"> + <JLabel id='centralSourceServerPolicy'/> + </cell> + </row> + <row> + <cell fill='both' columns="2"> + <JLabel id='centralSourceServerInfoLabel'/> + </cell> + </row> + </Table> + + </JPanel> + </cell> + </row> + </Table> + </JPanel> + +</StorageTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ConfigReferentielUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ConfigReferentielUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ConfigReferentielUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ConfigReferentielUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ConfigUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ConfigUI.jaxx new file mode 100644 index 0000000..c0d1cbb --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ConfigUI.jaxx @@ -0,0 +1,293 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<!-- ***************************************** --> +<!-- L'écran de configuration de la source --> +<!-- ***************************************** --> + +<StorageTabUI> + + <import> + fr.ird.observe.application.swing.ui.storage.StorageStep + fr.ird.observe.application.swing.db.constants.ConnexionStatus + fr.ird.observe.application.swing.db.constants.DbMode; + + java.awt.Color + java.awt.Dimension + + java.io.File + + javax.swing.border.LineBorder + javax.swing.text.html.HTMLEditorKit + + static org.nuiton.i18n.I18n.n + </import> + + <StorageStep id='step' initializer='StorageStep.CONFIG'/> + + <fr.ird.observe.application.swing.ui.storage.StorageUIModel id='model'/> + + <CardLayout id='configLayout'/> + + <script><![CDATA[ +@Override +public void init() { + getHandler().initUI(this); +} +]]> + </script> + + <JPanel id='content' layout='{new BorderLayout()}'> + <Table fill='both' weightx='1' constraints='BorderLayout.CENTER'> + <row> + <cell anchor='north'> + <JPanel id='configContent'> + + <!-- configurer creation base locale a partir d'une sauvegarde --> + <Table id='IMPORT_EXTERNAL_DUMP' + constraints='"IMPORT_EXTERNAL_DUMP"'> + <row> + <cell> + <JLabel text='observe.storage.importExternalDump.config'/> + </cell> + </row> + <row weighty='1'> + <cell weightx='1' fill="horizontal"> + <JTextField id="dumpFile" + onKeyReleased='getModel().setDumpFile(new File(((JTextField)event.getSource()).getText()))'/> + </cell> + <cell anchor="east"> + <JButton id="fileChooserAction" + onActionPerformed="getHandler().chooseDumpFile(this)"/> + </cell> + </row> + </Table> + + <!-- configurer creation base locale et import referentiel depuis base distante --> + <!--Table id='IMPORT_LOCAL_STORAGE' + constraints='"IMPORT_LOCAL_STORAGE"' + _description='n("observe.storage.importLocalStorage.description")'> + <row> + <cell> + <JLabel text='observe.storage.importLocalStorage.config'/> + </cell> + </row> + <row weighty='1'> + <cell weightx='1' fill="horizontal"> + <JTextField text='{model.getLocalStorageFile()+""}' + onKeyReleased='getModel().setLocalStorageFile(new File(((JTextField)event.getSource()).getText()))'/> + </cell> + <cell anchor="east"> + <JButton actionIcon='fileChooser' onActionPerformed="chooseLocalStorageFile()"/> + </cell> + </row> + </Table--> + + <!-- configurer creation base locale et import referentiel depuis base distante --> + <Table id='IMPORT_REMOTE_STORAGE' + fill="both" + constraints='"IMPORT_REMOTE_STORAGE"'> + <row> + <cell> + <JLabel text='observe.storage.importRemoteStorage.config'/> + </cell> + </row> + <row> + <cell weighty='1' weightx='1'> + <JPanel id='IMPORT_REMOTE_STORAGE_content'/> + </cell> + </row> + + </Table> + + <!-- configurer creation base locale et import referentiel depuis un server distant --> + <Table id='IMPORT_SERVER_STORAGE' + fill="both" + constraints='"IMPORT_SERVER_STORAGE"'> + <row> + <cell> + <JLabel text='observe.storage.importServerStorage.config'/> + </cell> + </row> + <row> + <cell weighty='1' weightx='1'> + <JPanel id='IMPORT_SERVER_STORAGE_content'/> + </cell> + </row> + + </Table> + + <!-- configurer connexion a base distante --> + <Table id='USE_REMOTE' + constraints='"USE_REMOTE"' fill='both'> + <row> + <cell> + <JLabel text='observe.storage.useRemoteStorage.config'/> + </cell> + </row> + <row> + <cell weighty='1' weightx='1'> + <JPanel id='USE_REMOTE_content' + minimumSize='{new Dimension(20,300)}'/> + </cell> + </row> + </Table> + + <!-- configurer connexion au server base distante --> + <Table id='USE_SERVER' + constraints='"USE_SERVER"' fill='both'> + <row> + <cell> + <JLabel text='observe.storage.useServerStorage.config'/> + </cell> + </row> + <row> + <cell weighty='1' weightx='1'> + <JPanel id='USE_SERVER_content' + minimumSize='{new Dimension(20,300)}'/> + </cell> + </row> + </Table> + + <JPanel constraints='"$$hideme$$"' visible='false'> + <JPanel id='remoteConfig'> + <Table constraints='BorderLayout.CENTER' + fill="both"> + <row> + <cell anchor='west'> + <JLabel text='observe.storage.remote.url'/> + </cell> + <cell weightx='1' fill="both" anchor='east'> + <JTextField id="remoteUrl" + onKeyReleased='getModel().setRemoteUrl(((JTextField)event.getSource()).getText())'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel text='observe.storage.remote.login'/> + </cell> + <cell weightx='1' fill="both" anchor='east'> + <JTextField id="remoteLogin" + onKeyReleased='getModel().setRemoteLogin(((JTextField)event.getSource()).getText())'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel text='observe.storage.remote.password'/> + </cell> + <cell weightx='1' fill="both" anchor='east'> + <JPasswordField id="remotePassword" + onKeyReleased='getModel().setRemotePassword(((JPasswordField)event.getSource()).getPassword())'/> + </cell> + </row> + <row> + <cell anchor='west'> + <JLabel id="serverDataBaseLabel" + text='observe.storage.server.dataBase'/> + </cell> + <cell weightx='1' fill="both" anchor='east'> + <JTextField id="serverDataBase" + onKeyReleased='getModel().setServerDatabase(((JTextField)event.getSource()).getText())'/> + </cell> + </row> + <row> + <cell columns='2'> + <JCheckBox id="remoteUseSsl" + onActionPerformed='getModel().setUseSsl(((JCheckBox)event.getSource()).isSelected())'/> + </cell> + </row> + <!--row weighty='1'--> + <!--row> + <cell columns='2'> + <Table insets='0'> + <row> + <cell weightx='1' + fill="horizontal"> + <JTextField + id="remoteSslCertificatFile" + onKeyReleased='getModel().setSslCertificatFile(new File(((JTextField)event.getSource()).getText()))'/> + </cell> + <cell anchor="east"> + <JButton + id="remoteSslCertificatFileChooseaction" + onActionPerformed="getHandler().chooseSslCertificatFile(this)"/> + </cell> + </row> + </Table> + </cell> + </row--> + <!--row> + <cell columns='2'> + <Table insets='0'> + <row> + <cell anchor='west'> + <JLabel text='observe.storage.remote.ssl.password'/> + </cell> + <cell weightx='1' fill="both" anchor='east'> + <JPasswordField id="remoteSslCertificatPassword" + onKeyReleased='getModel().setSslCertificatPassword(((JPasswordField)event.getSource()).getPassword())'/> + </cell> + </row> + </Table> + </cell> + </row--> + + <!-- sauver dans la configuration --> + <row> + <cell columns='2'> + <JCheckBox id="storeRemoteConfig" + onActionPerformed='getModel().setStoreRemoteConfig(((JCheckBox)event.getSource()).isSelected())'/> + </cell> + </row> + <!-- tester la connexion --> + <row> + <cell columns='2'> + <JButton id="testRemoteAction" + onActionPerformed='getModel().testRemote()'/> + </cell> + </row> + </Table> + <!-- résumé du test de connexion --> + <Table constraints='BorderLayout.SOUTH' fill='both' + insets='0'> + <row> + <cell weightx='1' weighty='1'> + <JScrollPane id="connexionStatusPanel"> + <JTextPane id='connexionStatus'/> + </JScrollPane> + </cell> + </row> + <row> + <cell> + <JLabel id="connexionStatusLabel"/> + </cell> + </row> + </Table> + </JPanel> + </JPanel> + </JPanel> + </cell> + </row> + </Table> + </JPanel> + +</StorageTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ConfigUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ConfigUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ConfigUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ConfigUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ConfirmUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ConfirmUI.jaxx new file mode 100644 index 0000000..f5578b0 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ConfirmUI.jaxx @@ -0,0 +1,51 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<!-- ************************--> +<!-- L'écran de confirmation --> +<!-- ************************--> + +<StorageTabUI> + + <import> + fr.ird.observe.application.swing.ui.storage.StorageStep + </import> + + <StorageStep id='step' initializer='StorageStep.CONFIRM'/> + + <fr.ird.observe.application.swing.ui.storage.StorageUIModel id='model'/> + + <script><![CDATA[ +@Override +public void init() { + getHandler().initUI(this); +} +]]> + </script> + + <JPanel id='content'> + <JScrollPane id="resumePane" constraints='BorderLayout.CENTER'> + <JTextPane id='resume'/> + </JScrollPane> + </JPanel> + +</StorageTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ConfirmUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ConfirmUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ConfirmUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/ConfirmUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/DataSelectionModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/DataSelectionModel.java new file mode 100644 index 0000000..8234387 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/DataSelectionModel.java @@ -0,0 +1,566 @@ +/* + * #%L + * ObServe :: Business + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.storage.tabs; + +import com.google.common.base.Preconditions; +import com.google.common.collect.Lists; +import com.google.common.collect.Maps; +import com.google.common.collect.Sets; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.AbstractReference; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.DataReferenceSet; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.referential.ProgramDtos; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialDtos; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.services.service.longline.TripLonglineService; +import fr.ird.observe.services.service.seine.TripSeineService; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.beans.PropertyChangeListener; +import java.beans.PropertyChangeSupport; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * Un modèle pour représenter la sélection de données. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class DataSelectionModel implements Serializable { + + public static void populate(DataSelectionModel model, ObserveSwingDataSource source) { + + Preconditions.checkState(source.isOpen()); + + Map<ReferentialReference<ProgramDto>, List<DataReference>> datas = Maps.newHashMap(); + + TripSeineService tripSeineService = source.newTripSeineService(); + TripLonglineService tripLonglineService = source.newTripLonglineService(); + + Set<ReferentialReference<ProgramDto>> programSet = source.getReferentialReferences(ProgramDto.class); + + for (ReferentialReference<ProgramDto> program : programSet) { + + List<DataReference> referenceDtos = Lists.newArrayList(); + + if (ProgramDtos.isProgramSeine(program)) { + + DataReferenceSet<TripSeineDto> tripSeineRef = tripSeineService.getTripSeineByProgram(program.getId()); + referenceDtos.addAll(tripSeineRef.getReferences()); + + } else if (ProgramDtos.isProgramLongline(program)) { + + DataReferenceSet<TripLonglineDto> tripLonglineRef = tripLonglineService.getTripLonglineByProgram(program.getId()); + referenceDtos.addAll(tripLonglineRef.getReferences()); + + } + + populate(program, referenceDtos, datas); + + } + model.setDatas(datas); + + } + + protected static void populate(ReferentialReference<ProgramDto> program, + List<DataReference> trips, + Map<ReferentialReference<ProgramDto>, List<DataReference>> datas) { + + if (!trips.isEmpty()) { + + datas.put(program, trips); + if (log.isDebugEnabled()) { + log.debug("Add program " + program.getPropertyValue(ProgramDto.PROPERTY_LABEL1) + " with " + trips.size() + " trip(s)."); + } + + + } + + } + + public static final String PROPERTY_USE_REFERENTIEL = "useReferentiel"; + + public static final String PROPERTY_USE_DATA = "useData"; + + public static final String PROPERTY_USE_OPEN_DATA = "useOpenData"; + + public static final String PROPERTY_SELECTED_DATA = "selectedData"; + + public static final String PROPERTY_SELECTED_REFERENTIEL = "selectedReferentiel"; + + public static final String PROPERTY_DATAS = "datas"; + + /** Logger */ + private static final Log log = LogFactory.getLog(DataSelectionModel.class); + + private static final long serialVersionUID = 2L; + + /** un drapeau pour selectionner ou non les donnees observers */ + protected boolean useData; + + /** un drapeau pour selectionner ou non des donnees observers ouvertes */ + protected boolean useOpenData; + + /** un drapeau pour selectionner ou non des donnees observer */ + protected boolean useReferentiel; + + /** la liste des programs utilisables (qui ont des marees) */ + protected transient Map<ReferentialReference<ProgramDto>, List<DataReference>> datas; + + /** la liste des marees selectionnee */ + protected transient Set<DataReference> selectedData; + + /** la liste des referentiels possibles */ + protected final Set<Class<? extends ReferentialDto>> referentiel; + + /** la liste des referentiels selectionnes */ + protected final Set<Class<? extends ReferentialDto>> selectedReferentiel; + + /** nb marees */ + protected int nbTrips; + + /** nb referentiels */ + protected final int nbReferentiels; + + protected final PropertyChangeSupport pcs; + + public void populate() { + throw new UnsupportedOperationException(); + } + + public DataSelectionModel() { + pcs = new PropertyChangeSupport(this); + referentiel = Sets.newHashSet(ReferentialDtos.REFERENCE_DTOS); + selectedReferentiel = Sets.newHashSet(); + nbReferentiels = referentiel.size(); + } + + public boolean isUseReferentiel() { + return useReferentiel; + } + + public boolean isUseData() { + return useData; + } + + public boolean isUseOpenData() { + return useOpenData; + } + + public boolean isEmpty() { + if (isUseReferentiel()) { + if (!isReferentielEmpty()) { + return false; + } + } + if (isUseData()) { + if (!isDataEmpty()) { + return false; + } + } + return true; + } + + + public boolean isReferentielEmpty() { + return selectedReferentiel.isEmpty(); + } + + public boolean isReferentielFull() { + return selectedReferentiel.size() == nbReferentiels; + } + + public boolean isDataEmpty() { + return selectedData == null || selectedData.isEmpty(); + } + + public boolean isDataFull() { + return selectedData != null && selectedData.size() == nbTrips; + } + + public int selectDataSize() { + return selectedData == null ? 0 : selectedData.size(); + } + + public Set<Class<? extends ReferentialDto>> getSelectedReferentiel() { + return selectedReferentiel; + } + + public Map<ReferentialReference<ProgramDto>, List<DataReference>> getDatas() { + if (datas == null) { + datas = Maps.newHashMap(); + } + return datas; + } + + public boolean containsData(ReferentialReference<ProgramDto> program, DataReference trip) { + List<DataReference> datas = getDatas(program.getId()); + return datas!=null && datas.contains(trip); + } + + public Set<DataReference> getSelectedData() { + if (selectedData == null) { + selectedData = Sets.newHashSet(); + } + return selectedData; + } + + public Map<ReferentialReference<ProgramDto>, List<DataReference>> getSelectedDataByProgram() { + if (datas == null || selectedData == null || selectedData.isEmpty()) { + return Collections.emptyMap(); + } + Map<ReferentialReference<ProgramDto>, List<DataReference>> result = Maps.newHashMap(); + + for (DataReference referenceDto : selectedData) { + + // on recherche son program + for (ReferentialReference<ProgramDto> p : datas.keySet()) { + if (datas.get(p).contains(referenceDto)) { + List<DataReference> referenceDtos = result.get(p); + if (referenceDtos == null) { + referenceDtos = Lists.newArrayList(); + result.put(p, referenceDtos); + } + referenceDtos.add(referenceDto); + break; + } + } + } + return result; + } + + public List<ReferentialReference<ProgramDto>> getSelectedProgram() { + if (datas == null || selectedData == null || selectedData.isEmpty()) { + return Collections.emptyList(); + } + + Set<ReferentialReference<ProgramDto>> result = Sets.newHashSet(); + + for (DataReference referenceDto : selectedData) { + + // on recherche son program + for (ReferentialReference<ProgramDto> p : datas.keySet()) { + if (datas.get(p).contains(referenceDto)) { + result.add(p); + break; + } + } + } + + return result.stream().collect(Collectors.toList()); + } + + public List<DataReference> getSelectedTripsByProgram(ReferentialReference<ProgramDto> program) { + if (datas == null || selectedData == null || selectedData.isEmpty()) { + return Collections.emptyList(); + } + + List<DataReference> result = datas.get(program).stream() + .filter(trip -> selectedData.contains(trip)) + .collect(Collectors.toList()); + + return result; + } + + + public boolean isSelectedData(AbstractReference<?> referenceDto) { + + boolean result; + + if (ProgramDto.class.isAssignableFrom(referenceDto.getType())) { + + List<DataReference> trips = datas.get(referenceDto); + result = CollectionUtils.isNotEmpty(trips); + + if (result) { + for (DataReference trip : trips) { + if (!getSelectedData().contains(trip)) { + + // au moins une marée non sélectionnée + + result = false; + } + } + } + } else { + + // recherche directe sur les ids de marees + result = getSelectedData().contains(referenceDto); + + } + + // ne devrait pas arrivée + return result; + + } + + public boolean isSelectedReferentiel(Class<?> type) { + checkReferentielType(type); + return getSelectedReferentiel().contains(type); + } + + public void setUseReferentiel(boolean useReferentiel) { + this.useReferentiel = useReferentiel; + firePropertyChange(PROPERTY_USE_REFERENTIEL, useReferentiel); + } + + public void setUseData(boolean useData) { + this.useData = useData; + firePropertyChange(PROPERTY_USE_DATA, useData); + } + + public void setUseOpenData(boolean useOpenData) { + this.useOpenData = useOpenData; + firePropertyChange(PROPERTY_USE_OPEN_DATA, useOpenData); + } + + public void addSelectedReferentiel(Class<? extends ReferentialDto> type) { + checkReferentielType(type); + if (log.isDebugEnabled()) { + log.debug("Add referentiel type " + type); + } + getSelectedReferentiel().add(type); + firePropertyChange(PROPERTY_SELECTED_REFERENTIEL, selectedReferentiel); + } + + public void addAllSelectedReferentiel() { + getSelectedReferentiel().addAll(referentiel); + firePropertyChange(PROPERTY_SELECTED_REFERENTIEL, selectedReferentiel); + } + + public void removeSelectedReferentiel(Class<?> type) { + checkReferentielType(type); + if (log.isDebugEnabled()) { + log.debug("remove referentiel type " + type); + } + getSelectedReferentiel().remove(type); + firePropertyChange(PROPERTY_SELECTED_REFERENTIEL, selectedReferentiel); + } + + public void removeAll() { + getSelectedReferentiel().clear(); + getSelectedData().clear(); + firePropertyChange(PROPERTY_SELECTED_REFERENTIEL, selectedReferentiel); + firePropertyChange(PROPERTY_SELECTED_DATA, selectedData); + } + + public void removeAllSelectedReferentiel() { + getSelectedReferentiel().clear(); + firePropertyChange(PROPERTY_SELECTED_REFERENTIEL, selectedReferentiel); + } + + public boolean isReferentielSelectAll(Collection<Class<? extends ReferentialDto>> classes) { + return selectedReferentiel.containsAll(classes); + } + + public void removeAllReferentiel(Collection<Class<? extends ReferentialDto>> classes) { + selectedReferentiel.removeAll(classes); + firePropertyChange(PROPERTY_SELECTED_REFERENTIEL, selectedReferentiel); + } + + public void addAllReferentiel(Collection<Class<? extends ReferentialDto>> classes) { + selectedReferentiel.addAll(classes); + firePropertyChange(PROPERTY_SELECTED_REFERENTIEL, selectedReferentiel); + } + + public void setDatas(Map<ReferentialReference<ProgramDto>, List<DataReference>> datas) { + this.datas = datas; + + // on compte le count de marées totale + int nbTrips = 0; + if (datas != null) { + for (List<DataReference> marees : datas.values()) { + nbTrips += marees.size(); + } + } + this.nbTrips = nbTrips; + + if (log.isDebugEnabled()) { + log.debug("Nb program registred : " + (datas == null ? 0 : datas.size())); + log.debug("Nb trip registred : " + this.nbTrips); + } + firePropertyChange(PROPERTY_DATAS, datas); + } + + public void addSelectedData(AbstractReference referenceDto) { + + if (ProgramDto.class.isAssignableFrom(referenceDto.getType())) { + + // ajout de toutes les marées du program + + if (log.isDebugEnabled()) { + log.debug("Add all trips of program " + referenceDto.getId()); + } + getSelectedData().addAll(datas.get(referenceDto)); + + } else { + // ajout d'une marée + if (log.isDebugEnabled()) { + log.debug("Add Trip " + referenceDto.getId()); + } + getSelectedData().add((DataReference) referenceDto); + } + firePropertyChange(PROPERTY_SELECTED_DATA, selectedData); + } + + public void addAllSelectedData() { + if (log.isDebugEnabled()) { + log.debug("All all data."); + } + for (List<DataReference> p : datas.values()) { + getSelectedData().addAll(p); + } + firePropertyChange(PROPERTY_SELECTED_DATA, selectedData); + } + + public void removeSelectedData(AbstractReference referenceDto) { + + if (ProgramDto.class.isAssignableFrom(referenceDto.getType())) { + + // ajout de toutes les marées du program + + if (log.isDebugEnabled()) { + log.debug("Remove all marees of program " + referenceDto); + } + getSelectedData().removeAll(datas.get(referenceDto)); + } else { + + // ajout d'une marée + if (log.isDebugEnabled()) { + log.debug("Remove maree " + referenceDto); + } + getSelectedData().remove(referenceDto); + } + firePropertyChange(PROPERTY_SELECTED_DATA, selectedData); + } + + public void removeAllSelectedData() { + if (selectedData != null) { + selectedData.clear(); + } + firePropertyChange(PROPERTY_SELECTED_DATA, selectedData); + } + + public void addPropertyChangeListener(PropertyChangeListener listener) { + pcs.addPropertyChangeListener(listener); + } + + public void addPropertyChangeListener(String propertyName, + PropertyChangeListener listener) { + pcs.addPropertyChangeListener(propertyName, listener); + } + + public void removePropertyChangeListener(PropertyChangeListener listener) { + pcs.removePropertyChangeListener(listener); + } + + public void removePropertyChangeListener(String propertyName, + PropertyChangeListener listener) { + pcs.removePropertyChangeListener(propertyName, listener); + } + + protected void firePropertyChange(String propertyName, Object newValue) { + pcs.firePropertyChange(propertyName, null, newValue); + } + + protected void firePropertyChange(String propertyName, + Object oldValue, + Object newValue) { + pcs.firePropertyChange(propertyName, oldValue, newValue); + } + + protected void checkReferentielType(Class<?> type) { + if (!referentiel.contains(type)) { + throw new IllegalArgumentException( + "given <" + type + "> is not in referentiel universe : " + + referentiel); + } + } + + public void destroy() { + removeAll(); + // suppression de tous les listeners + PropertyChangeListener[] listeners = pcs.getPropertyChangeListeners(); + for (PropertyChangeListener l : listeners) { + removePropertyChangeListener(l); + } + } + + @Override + protected void finalize() throws Throwable { + super.finalize(); + destroy(); + } + + public List<DataReference> getDatas(String programId) { + Optional<ReferentialReference<ProgramDto>> programRefOptional = getDatas().keySet().stream().filter(ReferentialReference.newIdPredicate(programId)).findFirst(); + + List<DataReference> result; + + if (programRefOptional.isPresent()) { + + result = getDatas().get(programRefOptional.get()); + + } else { + + result = Collections.emptyList(); + + } + + return result; + } + + public void addData(ReferentialReference<ProgramDto> program, DataReference trip) { + if (!getDatas().containsKey(program)) { + getDatas().put(program, new ArrayList<>()); + } + getDatas(program.getId()).add(trip); + firePropertyChange(PROPERTY_DATAS, getDatas()); + } + + public Set<ReferentialReference<ProgramDto>> getPrograms() { + return getDatas().keySet(); + } + + public void removeTrip(ReferentialReference<ProgramDto> program, DataReference trip) { + List<DataReference> trips = getDatas(program.getId()); + trips.remove(trip); + if (trips.isEmpty()) { + getDatas().remove(program); + } + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/RolesTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/RolesTableModel.java new file mode 100644 index 0000000..f8c16de --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/RolesTableModel.java @@ -0,0 +1,190 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.storage.tabs; + + +import com.google.common.collect.Lists; +import fr.ird.observe.services.dto.ObserveDbUserDto; +import fr.ird.observe.services.dto.ObserveDbUserDtos; +import fr.ird.observe.services.dto.constants.ObserveDbRole; + +import javax.swing.table.AbstractTableModel; +import java.util.Collections; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; + +/** + * Le modèle pour la tableau dans l'export GPS qui contient les activités et les + * points gps calculés via le fichier gps importé. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class RolesTableModel extends AbstractTableModel { + + private static final long serialVersionUID = 1L; + + public static final String[] COLUMN_NAMES = { + n("observe.security.role"), + n("observe.security.unused"), + n("observe.security.referentiel"), + n("observe.security.utilisateur"), + n("observe.security.technicien") + }; + + public static final String[] COLUMN_NAME_TIPS = { + n("observe.security.role.tip"), + n("observe.security.unused.tip"), + n("observe.security.referentiel.tip"), + n("observe.security.utilisateur.tip"), + n("observe.security.technicien.tip") + }; + + protected static final Class<?>[] COLUMN_CLASSES = { + String.class, + Boolean.class, + Boolean.class, + Boolean.class, + Boolean.class + }; + + protected SecurityModel model; + + protected List<ObserveDbUserDto> roles; + + public RolesTableModel() { + } + + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + // seule la première colonne n'est pas éditable (on ne peut pas + // changer le lastName d'un role) + return columnIndex > 0; + } + + + /** + * Initialise le modèle. + * + * @param model le modèle de sécurité attaché + */ + public void init(SecurityModel model) { + + this.model = model; + this.roles = Lists.newArrayList(model.getUsersWithoutAdministrator()); + Collections.sort(this.roles, ObserveDbUserDtos.getUserDtoComparator()); + fireTableDataChanged(); + } + + public void clear() { + model = null; + roles = null; + fireTableDataChanged(); + } + + @Override + public int getRowCount() { + return roles == null ? 0 : roles.size(); + } + + @Override + public int getColumnCount() { + return COLUMN_CLASSES.length; + } + + @Override + public Object getValueAt(int rowIndex, int columnIndex) { + Object value = null; + + ObserveDbUserDto user = getUser(rowIndex); + if (user != null) { + + switch (columnIndex) { + case 0: + value = user.getName(); + break; + case 1: + value = ObserveDbRole.UNUSED.equals(user.getRole()); + break; + case 2: + value = ObserveDbRole.REFERENTIAL.equals(user.getRole()); + break; + case 3: + value = ObserveDbRole.USER.equals(user.getRole()); + break; + case 4: + value = ObserveDbRole.TECHNICAL.equals(user.getRole()); + break; + default: + throw new IllegalStateException( + "can not get value for row " + rowIndex + + ", col " + columnIndex); + } + } + return value; + } + + @Override + public void setValueAt(Object aValue, int rowIndex, int columnIndex) { + + if (columnIndex == 0) { + + // pas possible + return; + } + + Boolean value = (Boolean) aValue; + ObserveDbUserDto userDto = getUser(rowIndex); + + ObserveDbRole role; + + if (!value) { + role = null; + } else { + switch (columnIndex) { + case 2: + role = ObserveDbRole.REFERENTIAL; + break; + case 3: + role = ObserveDbRole.USER; + break; + case 4: + role = ObserveDbRole.TECHNICAL; + break; + default: + role = ObserveDbRole.UNUSED; + } + } + + model.setRole(userDto, role, true); + + // toute la ligne (sauf le role change) + fireTableRowsUpdated(rowIndex, rowIndex); + } + + protected ObserveDbUserDto getUser(int rowIndex) { + ObserveDbUserDto user = roles == null ? null : roles.get(rowIndex); + return user; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/RolesUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/RolesUI.jaxx new file mode 100644 index 0000000..7b94eaa --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/RolesUI.jaxx @@ -0,0 +1,72 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<!-- *************************************** --> +<!-- L'écran de sauvegarde de la base locale --> +<!-- *************************************** --> + +<StorageTabUI> + + <import> + fr.ird.observe.application.swing.ui.storage.tabs.SecurityModel + fr.ird.observe.application.swing.ui.storage.StorageStep + fr.ird.observe.application.swing.ui.storage.StorageUIModel + </import> + + <StorageStep id='step' initializer='StorageStep.ROLES'/> + + <StorageUIModel id='model'/> + + <SecurityModel id='securityModel' + initializer='model.getSecurityModel()'/> + + <!-- les roles récupérés depuis la base distante --> + <RolesTableModel id='rolesModel'/> + + <script><![CDATA[ + +@Override +public void init() { + getHandler().initUI(this); +} + +public String updateAdministrateur(String role) { + return t("observe.storage.security.administrateur", role); +} +]]> + </script> + + <JPanel id='content'> + + <!-- le lastName du role administrateur --> + <JPanel id='administrateurPanel' constraints='BorderLayout.NORTH'> + <JLabel id='administrateur' constraints='BorderLayout.NORTH'/> + </JPanel> + + <!-- la liste des roles --> + <JScrollPane id='rolesPane' constraints='BorderLayout.CENTER'> + <JTable id='roles'/> + </JScrollPane> + + </JPanel> + +</StorageTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/RolesUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/RolesUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/RolesUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/RolesUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/SecurityModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/SecurityModel.java new file mode 100644 index 0000000..a890021 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/SecurityModel.java @@ -0,0 +1,173 @@ +/* + * #%L + * ObServe :: Business + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.storage.tabs; + +import com.google.common.collect.Sets; +import fr.ird.observe.services.dto.ObserveDbUserDto; +import fr.ird.observe.services.dto.ObserveDbUserDtos; +import fr.ird.observe.services.dto.constants.ObserveDbRole; + +import java.beans.PropertyChangeListener; +import java.beans.PropertyChangeSupport; +import java.io.Serializable; +import java.util.Collection; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +/** + * Le modèle la sécurité à appliquer sur une base postgres + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class SecurityModel implements Serializable { + + public static final String PROPERTY_ADMINISTRATEUR = "administrateur"; + + public static final String PROPERTY_ROLE = "role"; + + public static final String PROPERTY_ASSIGNED = "assigned"; + + private static final long serialVersionUID = 1L; + + protected ObserveDbUserDto administrateur; + + protected final Set<ObserveDbUserDto> users; + + protected final PropertyChangeSupport pcs = new PropertyChangeSupport(this); + + public SecurityModel() { + users = Sets.newHashSet(); + } + + public ObserveDbUserDto getAdministrateur() { + return administrateur; + } + + public Set<ObserveDbUserDto> getUsersByRole(ObserveDbRole role) { + return users.stream() + .filter(ObserveDbUserDtos.newRolePredicate(role)) + .collect(Collectors.toSet()); + } + + public List<String> getUserNamesByRole(ObserveDbRole role) { + return users.stream() + .filter(ObserveDbUserDtos.newRolePredicate(role)) + .map(ObserveDbUserDtos.NAME_FUNCTION) + .collect(Collectors.toList()); + } + + public List<String> getDataUserNames() { + return getUserNamesByRole(ObserveDbRole.USER); + } + + public List<String> getReferentialUserNames() { + return getUserNamesByRole(ObserveDbRole.REFERENTIAL); + } + + public List<String> getTechnicalUserNames() { + return getUserNamesByRole(ObserveDbRole.TECHNICAL); + } + + public List<String> getUnusedUserNames() { + return getUserNamesByRole(ObserveDbRole.UNUSED); + } + + public Set<ObserveDbUserDto> getUsers() { + return Sets.newHashSet(users); + } + + public Set<ObserveDbUserDto> getUsersWithoutAdministrator() { + Predicate<ObserveDbUserDto> predicate = ObserveDbUserDtos.newRolePredicate(ObserveDbRole.ADMINISTRATOR); + return users.stream().filter(u -> !predicate.test(u)).collect(Collectors.toSet()); + } + + public boolean isRole(ObserveDbRole r, ObserveDbUserDto user) { + return r.equals(user.getRole()); + } + + public void init(Collection<ObserveDbUserDto> users) { + this.users.clear(); + this.users.addAll(users); + + Optional<ObserveDbUserDto> optionalAdministrator = users.stream().filter(ObserveDbUserDtos.newRolePredicate(ObserveDbRole.ADMINISTRATOR)).findFirst(); + if (optionalAdministrator.isPresent()) { + this.administrateur = optionalAdministrator.get(); + } else { + throw new IllegalStateException("No administrator found"); + } + firePropertyChange(PROPERTY_ROLE, null, getUsers()); + firePropertyChange(PROPERTY_ADMINISTRATEUR, null, getAdministrateur()); + firePropertyChange(PROPERTY_ASSIGNED, null, getAssigned()); + } + + public void setRole(ObserveDbUserDto user, ObserveDbRole role, boolean fire) { + user.setRole(role); + if (fire) { + if (role != null) { + firePropertyChange(role.name(), null, getUsersByRole(role)); + } + firePropertyChange(PROPERTY_ASSIGNED, null, getAssigned()); + } + } + + public void setRole(Iterable<ObserveDbUserDto> users, ObserveDbRole role) { + for (ObserveDbUserDto user : users) { + setRole(user, role, false); + } + firePropertyChange(role.name(), null, getUsersByRole(role)); + firePropertyChange(PROPERTY_ASSIGNED, null, getAssigned()); + } + + public int getAssigned() { + int countNotAssigned = (int) users.stream().filter(ObserveDbUserDtos.newRolePredicate(null)).count(); + int count = users.size() - countNotAssigned; + return count; + } + + public void addPropertyChangeListener(PropertyChangeListener listener) { + pcs.addPropertyChangeListener(listener); + } + + public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { + pcs.addPropertyChangeListener(propertyName, listener); + } + + public void removePropertyChangeListener(PropertyChangeListener listener) { + pcs.removePropertyChangeListener(listener); + } + + public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { + pcs.removePropertyChangeListener(propertyName, listener); + } + + protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { + pcs.firePropertyChange(propertyName, oldValue, newValue); + } + + protected void firePropertyChange(String propertyName, Object newValue) { + firePropertyChange(propertyName, null, newValue); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/SelectDataUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/SelectDataUI.jaxx new file mode 100644 index 0000000..78855a0 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/SelectDataUI.jaxx @@ -0,0 +1,65 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<!-- *******************************************--> +<!-- L'écran de sélection des données à traiter --> +<!-- *******************************************--> + +<StorageTabUI> + + <import> + fr.ird.observe.application.swing.db.ObserveSwingDataSource + fr.ird.observe.application.swing.ui.storage.StorageStep + fr.ird.observe.application.swing.ui.tree.DataSelectionTreeSelectionModel + fr.ird.observe.application.swing.ui.tree.DataSelectionTreeCellRenderer + </import> + + <StorageStep id='step' initializer='StorageStep.SELECT_DATA'/> + + <fr.ird.observe.application.swing.ui.storage.StorageUIModel id='model'/> + + <DataSelectionTreeSelectionModel id='selectionModel'/> + + <script><![CDATA[ +@Override +public void init() { + getHandler().initUI(this); +} + +public void initTree(ObserveSwingDataSource dataSource) { + getHandler().initTree(this, dataSource); +} +]]> + </script> + + <JPanel id='content'> + + <JScrollPane id='selectedTreePane' constraints='BorderLayout.CENTER'> + + <!-- arbre de selection des exports --> + <JTree id='selectTree'/> + + </JScrollPane> + </JPanel> + + +</StorageTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/SelectDataUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/SelectDataUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/SelectDataUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/SelectDataUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/StorageTabUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/StorageTabUI.jaxx new file mode 100644 index 0000000..e5185cf --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/StorageTabUI.jaxx @@ -0,0 +1,96 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<!-- **************************** --> +<!-- La base des contenu d'onglet --> +<!-- **************************** --> + +<JPanel id="tabPanel" + abstract='true' + implements='jaxx.runtime.swing.wizard.WizardStepUI<StorageStep, StorageUIModel>'> + + <import> + fr.ird.observe.application.swing.ui.UIHelper + fr.ird.observe.application.swing.ui.storage.StorageStep + fr.ird.observe.application.swing.ui.storage.StorageUIModel + + java.awt.Color + + javax.swing.JLabel + javax.swing.border.LineBorder + + static org.nuiton.i18n.I18n.t + static org.nuiton.i18n.I18n.n + </import> + + <StorageTabUIHandler id='handler'/> + + <StorageUIModel id='model' + initializer='getContextValue(StorageUIModel.class)'/> + + <script><![CDATA[ + +public abstract StorageStep getStep(); + +public abstract void init(); + +public void destroy() { + description.setText(""); + UIHelper.destroy(this); +} + +@Override +protected void finalize() throws Throwable { + super.finalize(); + destroy(); +} + +protected void setDescriptionText(String text) { + description.setText(text); +} + +protected String getProgressString(int currentStep, int nbStep) { + StorageStep step = getStep(); + String txt = ""; + if (step != null) { + txt = n("observe.storage.step.label"); + txt = t(txt, currentStep + 1, nbStep, t(step.getLabel())); + } + return txt; +} +]]> + </script> + + <!-- titre --> + <JPanel layout='{new BorderLayout()}' constraints='BorderLayout.NORTH'> + <JProgressBar id='progress' constraints='BorderLayout.CENTER'/> + </JPanel> + + <!-- content --> + <JPanel id='content' constraints='BorderLayout.CENTER'/> + + <!-- description --> + <JScrollPane id="descriptionPane" constraints='BorderLayout.SOUTH'> + <JTextArea id='description'/> + </JScrollPane> + +</JPanel> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/StorageTabUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/StorageTabUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/StorageTabUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/StorageTabUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/StorageTabUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/StorageTabUIHandler.java new file mode 100644 index 0000000..97195b5 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/StorageTabUIHandler.java @@ -0,0 +1,491 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.storage.tabs; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.ObserveTextGenerator; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.db.constants.ConnexionStatus; +import fr.ird.observe.application.swing.db.constants.CreationMode; +import fr.ird.observe.application.swing.db.constants.DbMode; +import fr.ird.observe.services.configuration.ObserveDataSourceInformation; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.storage.StorageStep; +import fr.ird.observe.application.swing.ui.storage.StorageUILauncher; +import fr.ird.observe.application.swing.ui.storage.StorageUIModel; +import fr.ird.observe.application.swing.ui.tree.DataSelectionTreeSelectionModel; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import jaxx.runtime.swing.editor.MyDefaultCellEditor; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.Icon; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JRadioButton; +import javax.swing.JTable; +import javax.swing.JTree; +import javax.swing.table.DefaultTableCellRenderer; +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Window; +import java.beans.PropertyChangeListener; +import java.io.File; +import java.util.Date; + +import static org.nuiton.i18n.I18n.t; + +/** + * Le controleur comun à tous les onglets. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class StorageTabUIHandler { + + private static final Log log = LogFactory.getLog(StorageTabUIHandler.class); + + public boolean updateCreationModeLayout(ChooseDbModeUI ui, + boolean visible, + JRadioButton button) { + JPanel panel = ui.getUseCreateMode(); + if (visible) { + for (Component c : panel.getComponents()) { + if (button.equals(c)) { + // button already in + return true; + } + } + + panel.add(button); + } else { + for (Component c : panel.getComponents()) { + if (button.equals(c)) { + // button still in + panel.remove(c); + return false; + } + } + } + return visible; + } + + public void initUI(final ChooseDbModeUI ui) { + + PropertyChangeListener listener = evt -> { + StorageUIModel model = (StorageUIModel) evt.getSource(); + + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ObserveTextGenerator textGenerator = applicationContext.getTextGenerator(); + String txt = textGenerator.getLoadDataSourceResume(model); + ui.getResume().setText(txt); + }; + StorageUIModel model = ui.getModel(); + model.addPropertyChangeListener(StorageUIModel.DB_MODE_PROPERTY_NAME, listener); + model.addPropertyChangeListener(StorageUIModel.CREATION_MODE_PROPERTY_NAME, listener); + ui.setDescriptionText(t(ui.getStep().getDescription())); + } + + public void initUI(final ConfigUI ui) { + + PropertyChangeListener listener = evt -> { + StorageUIModel model = (StorageUIModel) evt.getSource(); + String propertyName = evt.getPropertyName(); + if (StorageUIModel.CREATION_MODE_PROPERTY_NAME.equals(propertyName) || + StorageUIModel.DB_MODE_PROPERTY_NAME.equals(propertyName)) { + String id = null; + if (model.getDbMode() == DbMode.USE_REMOTE) { + id = DbMode.USE_REMOTE.name(); + } else if (model.getDbMode() == DbMode.USE_SERVER) { + id = DbMode.USE_SERVER.name(); + } else { + if (model.getCreationMode() != null) { + id = model.getCreationMode().name(); + } + } + if (id != null) { + refreshConfig(ui, id); + } + } + }; + ui.getModel().addPropertyChangeListener(listener); + } + + public void initUI(final ConfigReferentielUI ui) { + if (ui.getStep() != null) { + ui.setDescriptionText(t(ui.getStep().getDescription())); + + PropertyChangeListener listener = evt -> { + String propertyName = evt.getPropertyName(); + if (StorageUIModel.REFERENTIEL_IMPORT_MODE_PROPERTY_NAME.equals(propertyName)) { + CreationMode id = (CreationMode) evt.getNewValue(); + refreshConfig(ui, id.name()); + } + }; + ui.getModel().addPropertyChangeListener(listener); + ui.getModel().setReferentielImportMode(CreationMode.IMPORT_EXTERNAL_DUMP); + } + } + + public void initUI(final ConfigDataUI ui) { + if (ui.getStep() != null) { + ui.setDescriptionText(t(ui.getStep().getDescription())); + + PropertyChangeListener listener = evt -> { + String propertyName = evt.getPropertyName(); + if (StorageUIModel.DATA_IMPORT_MODE_PROPERTY_NAME.equals(propertyName)) { + CreationMode id = (CreationMode) evt.getNewValue(); + + if (id != null) { + refreshConfig(ui, id.name()); + + } + + } + }; + ui.getModel().addPropertyChangeListener(listener); + ui.getModel().setDataImportMode(CreationMode.EMPTY); + } + } + + public void initUI(final RolesUI ui) { + if (ui.getStep() != null) { + ui.setDescriptionText(t(ui.getStep().getDescription())); + } + + ui.getSecurityModel().addPropertyChangeListener(evt -> { + if (log.isDebugEnabled()) { + log.debug("Security model changed [" + evt.getPropertyName() + "] <" + evt.getOldValue() + " : " + evt.getNewValue() + ">"); + } + ui.getModel().validate(); + }); + + JTable table = ui.getRoles(); + table.setRowHeight(24); + + UIHelper.fixTableColumnWidth(table, 1, 100); + UIHelper.fixTableColumnWidth(table, 2, 100); + UIHelper.fixTableColumnWidth(table, 3, 100); + UIHelper.fixTableColumnWidth(table, 4, 100); + + DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); + + UIHelper.setI18nTableHeaderRenderer( + table, + RolesTableModel.COLUMN_NAMES[0], + RolesTableModel.COLUMN_NAME_TIPS[0], + RolesTableModel.COLUMN_NAMES[1], + RolesTableModel.COLUMN_NAME_TIPS[1], + RolesTableModel.COLUMN_NAMES[2], + RolesTableModel.COLUMN_NAME_TIPS[2], + RolesTableModel.COLUMN_NAMES[3], + RolesTableModel.COLUMN_NAME_TIPS[3], + RolesTableModel.COLUMN_NAMES[4], + RolesTableModel.COLUMN_NAME_TIPS[4] + ); + + UIHelper.setTableColumnRenderer(table, 0, UIHelper.newStringTableCellRenderer(renderer, 50, true)); + UIHelper.setTableColumnRenderer(table, 1, UIHelper.newBooleanTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 2, UIHelper.newBooleanTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 3, UIHelper.newBooleanTableCellRenderer(renderer)); + UIHelper.setTableColumnRenderer(table, 4, UIHelper.newBooleanTableCellRenderer(renderer)); + + UIHelper.setTableColumnEditor(table, 1, MyDefaultCellEditor.newBooleanEditor()); + UIHelper.setTableColumnEditor(table, 2, MyDefaultCellEditor.newBooleanEditor()); + UIHelper.setTableColumnEditor(table, 3, MyDefaultCellEditor.newBooleanEditor()); + UIHelper.setTableColumnEditor(table, 4, MyDefaultCellEditor.newBooleanEditor()); + + } + + public void initUI(SelectDataUI ui) { + if (ui.getStep() != null) { + ui.setDescriptionText(t(ui.getStep().getDescription())); + } + + // customize tree selection colors + UIHelper.initUI(ui.getSelectedTreePane(), ui.getSelectTree()); + } + + public void initUI(BackupUI ui) { + if (ui.getStep() != null) { + ui.setDescriptionText(t(ui.getStep().getDescription())); + } + } + + public void initUI(ConfirmUI ui) { + if (ui.getStep() != null) { + ui.setDescriptionText(t(ui.getStep().getDescription())); + } + } + + public void chooseBackupFile(BackupUI ui) { + File f = UIHelper.chooseDirectory( + ui, + t("observe.title.choose.db.dump.directory"), + t("observe.action.choose.db.dump.directory"), + new File(ui.getDirectoryText().getText()) + ); + changeDirectory(ui, f); + } + + public void changeDirectory(BackupUI ui, File f) { + ui.getModel().setBackupFile(new File(f, ui.getFilenameText().getText())); + } + + public void changeFilename(BackupUI ui, String filename) { + ui.getModel().setBackupFile(new File(ui.getDirectoryText().getText(), filename)); + } + + public void refreshConfig(ConfigUI ui, String configId) { + JComponent c = (JComponent) ui.getObjectById(configId); + if (c != null) { + if (log.isDebugEnabled()) { + log.debug(configId); + } + ui.configLayout.show(ui.configContent, configId); + String text = (String) c.getClientProperty("description"); + ui.setDescriptionText(t(text)); + if (c.equals(ui.IMPORT_REMOTE_STORAGE)) { + ui.IMPORT_REMOTE_STORAGE_content.add(ui.remoteConfig, BorderLayout.CENTER); + } else if (c.equals(ui.IMPORT_SERVER_STORAGE)) { + ui.IMPORT_SERVER_STORAGE_content.add(ui.remoteConfig, BorderLayout.CENTER); + } else if (c.equals(ui.USE_REMOTE)) { + ui.USE_REMOTE_content.add(ui.remoteConfig, BorderLayout.CENTER); + } else if (c.equals(ui.USE_SERVER)) { + ui.USE_SERVER_content.add(ui.remoteConfig, BorderLayout.CENTER); + } + } + } + + public void refreshConfig(ConfigReferentielUI ui, String configId) { + JComponent c = (JComponent) ui.getObjectById(configId); + if (c != null) { + if (log.isDebugEnabled()) { + log.debug(configId); + } + ui.configLayout.show(ui.configContent, configId); + } + } + + public void refreshConfig(ConfigDataUI ui, String configId) { + JComponent c = (JComponent) ui.getObjectById(configId); + if (c != null) { + if (log.isDebugEnabled()) { + log.debug(configId); + } + ui.configLayout.show(ui.configContent, configId); + } + } + + public Icon updateConnexionStatutIcon(ConfigUI ui, ConnexionStatus status) { + Icon icon = (Icon) ui.getConnexionStatus().getClientProperty(status.name().toLowerCase() + "Icon"); + return icon; + } + + public Color updateConnexionStatutColor(ConfigUI ui, ConnexionStatus status) { + Color color = (Color) ui.getConnexionStatus().getClientProperty(status.name().toLowerCase() + "Color"); + return color; + } + + public String updateConnexionStatutText(ConfigUI ui, ConnexionStatus status) { + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ObserveTextGenerator textGenerator = applicationContext.getTextGenerator(); + String text = textGenerator.getConnexionTestResultMessage(ui.getModel()); + return text; + } + + public void chooseDumpFile(ConfigUI ui) { + File f = UIHelper.chooseFile( + ui, + t("observe.title.choose.db.dump"), + t("observe.action.choose.db.dump"), + ui.getModel().getDumpFile(), + "^.+\\.sql\\.gz$", + t("observe.action.choose.db.dump.description")); + ui.getModel().setDumpFile(f); + } + + public void chooseDumpFile(ConfigReferentielUI ui) { + File f = UIHelper.chooseFile( + ui, + t("observe.title.choose.db.dump"), + t("observe.action.choose.db.dump"), + ui.getModel().getDumpFile(), + "^.+\\.sql\\.gz$", + t("observe.action.choose.db.dump.description")); + ui.getCentralSourceModel().setDumpFile(f); + ui.getModel().validate(); + } + + public void chooseDumpFile(ConfigDataUI ui) { + File f = UIHelper.chooseFile( + ui, + t("observe.title.choose.db.dump"), + t("observe.action.choose.db.dump"), + ui.getModel().getDumpFile(), + "^.+\\.sql\\.gz$", + t("observe.action.choose.db.dump.description")); + ui.getCentralSourceModel().setDumpFile(f); + ui.getModel().validate(); + } + +// public void chooseSslCertificatFile(ConfigUI ui) { +// File f = UIHelper.chooseFile( +// ui, +// t("observe.title.choose.ssl.cert"), +// t("observe.action.choose.ssl.cert"), +// ui.getModel().getSslCertificatFile(), +// "^.+\\.jks$", +// t("observe.action.choose.ssl.cert.description")); +// ui.getModel().setSslCertificatFile(f); +// } + + public void initTree(SelectDataUI ui, ObserveSwingDataSource source) { + StorageUIModel model = ui.getModel(); + if (model.isUseSelectData()) { + + DataSelectionModel dataModel = model.getSelectDataModel(); + ObserveTreeHelper helper = new ObserveTreeHelper(); + JTree tree = ui.selectTree; + helper.setUI(tree, false, null); + + tree.setModel(helper.createModel(ui, dataModel, source)); + DataSelectionTreeSelectionModel selectionModel = + ui.getSelectionModel(); + selectionModel.initUI(tree); + selectionModel.setDataModel(dataModel); + } + } + + protected String updateInternalDumpModeLabel(ChooseDbModeUI ui, + boolean dumpExist) { + File f = ObserveSwingApplicationContext.get().getConfig().getInitialDbDump(); + String text; + if (f.exists()) { + text = t("observe.storage.internalDump.last.modified", new Date(f.lastModified())); + } else { + text = t("observe.storage.internalDump.not.exist"); + } + return t(CreationMode.IMPORT_INTERNAL_DUMP.getLabel()) + text; + } + + protected String updateCanMigrateLabel(ChooseDbModeUI ui, + boolean canMigrate) { + String text = t("observe.storage.action.canMigrate", ui.getModel().getModelVersion()); + return text; + } + + public void obtainRemoteConnexion(ConfigReferentielUI ui) { + StorageUIModel sourceModel = ui.getCentralSourceModel(); + StorageUILauncher.obtainRemoteConnexion( + ui.getDelegateContext(), + ui.getParentContainer(Window.class), + sourceModel + ); + + sourceModel.validate(StorageStep.CONFIG); + + ui.getModel().validate(); + } + + public void obtainServerConnexion(ConfigReferentielUI ui) { + StorageUIModel sourceModel = ui.getCentralSourceModel(); + StorageUILauncher.obtainServerConnexion( + ui.getDelegateContext(), + ui.getParentContainer(Window.class), + sourceModel + ); + + sourceModel.validate(StorageStep.CONFIG); + + ui.getModel().validate(); + } + + public void obtainRemoteConnexion(ConfigDataUI ui) { + StorageUIModel sourceModel = ui.getCentralSourceModel(); + StorageUILauncher.obtainRemoteConnexion( + ui.getDelegateContext(), + ui.getParentContainer(Window.class), + sourceModel + ); + + sourceModel.validate(StorageStep.CONFIG); + + ui.getModel().validate(); + } + + + public void obtainServerConnexion(ConfigDataUI ui) { + StorageUIModel sourceModel = ui.getCentralSourceModel(); + StorageUILauncher.obtainServerConnexion( + ui.getDelegateContext(), + ui.getParentContainer(Window.class), + sourceModel + ); + + sourceModel.validate(StorageStep.CONFIG); + + ui.getModel().validate(); + } + + public String updateStorageLabel(StorageUIModel service, + boolean serviceValid, + JLabel label, + boolean remote) { + String text; + if (serviceValid && remote == service.isRemote()) { + + // on recupere le label du service + text = service.getLabel(); + } else { + + // aucun service configuré + text = t((String) label.getClientProperty("no")); + } + return text; + } + + protected String updateDataSourcePolicy(StorageUIModel sourceModel, + boolean valid, + boolean remote) { + String text = null; + if (valid && remote == sourceModel.isRemote()) { + ObserveDataSourceInformation dataSourceInformation = sourceModel.getDataSourceInformation(); + + if (dataSourceInformation != null) { + + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ObserveTextGenerator textGenerator = applicationContext.getTextGenerator(); + text = textGenerator.getDataSourcePolicy(dataSourceInformation); + } + + } else { + + text = t("observe.common.storage.not.valid"); + + } + + return text; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/package.html b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/package.html similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/package.html rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/storage/tabs/package.html diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/AbstractObserveTreeCellRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/AbstractObserveTreeCellRenderer.java new file mode 100644 index 0000000..6a83c8b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/AbstractObserveTreeCellRenderer.java @@ -0,0 +1,432 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.tree; + +import com.google.common.base.Preconditions; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.OpenableDto; +import fr.ird.observe.services.dto.longline.ActivityLonglineDto; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.ui.content.impl.seine.FloatingObjectUI; +import fr.ird.observe.application.swing.ui.content.impl.seine.SetSeineUI; +import fr.ird.observe.application.swing.ui.content.open.impl.longline.ActivityLonglineUI; +import fr.ird.observe.application.swing.ui.content.open.impl.longline.TripLonglineUI; +import fr.ird.observe.application.swing.ui.content.open.impl.seine.ActivitySeineUI; +import fr.ird.observe.application.swing.ui.content.open.impl.seine.RouteUI; +import fr.ird.observe.application.swing.ui.content.open.impl.seine.TripSeineUI; +import jaxx.runtime.swing.nav.tree.AbstractNavTreeCellRenderer; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.decorator.Decorator; + +import javax.swing.Icon; +import javax.swing.UIManager; +import javax.swing.tree.DefaultTreeModel; +import java.awt.Color; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.nuiton.i18n.I18n.t; + +/** + * Le renderer abstrait (qui a toutes les methodes qui aident) pour implanter de + * vrai renderer pour les différents cas d'utilisation de l'abre de navigation. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.2 + */ +public abstract class AbstractObserveTreeCellRenderer extends AbstractNavTreeCellRenderer<DefaultTreeModel, ObserveNode> { + + /** Logger */ + protected static final Log log = + LogFactory.getLog(AbstractObserveTreeCellRenderer.class); + + /** la liste des ui qui peuvent être en mode création */ + public static final List<Class<?>> CREATION_UI = + Collections.unmodifiableList( + Arrays.<Class<?>>asList( + TripSeineUI.class, + RouteUI.class, + ActivitySeineUI.class, + FloatingObjectUI.class, + SetSeineUI.class, + TripLonglineUI.class, + ActivityLonglineUI.class) + ); + + private static final long serialVersionUID = 1L; + + /** la couleur des noeuds fermés */ + protected Color closeColor; + + /** la couleur des noeuds de données ouverts */ + protected Color openColor; + + /** la couleur pour indiquer que la données est non valide ou non sauvée */ + protected Color redColor; + + /** service de décoration */ + protected transient DecoratorService decoratorService; + + public DecoratorService getDecoratorService() { + if (decoratorService == null) { + + // on récupère le service commun + decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); + } + return decoratorService; + } + + @Override + public ObserveDataProvider getDataProvider() { + ObserveDataProvider provider = (ObserveDataProvider) + super.getDataProvider(); + if (provider == null) { + ObserveSwingDataSource source = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); + if (source != null) { + provider = new ObserveDataProvider(source); + setDataProvider(provider); + } + } + return provider; + } + + public AbstractObserveTreeCellRenderer() { + init(); + } + + protected void init() { + closeColor = Color.LIGHT_GRAY; + openColor = getForeground(); + redColor = Color.RED; + } + + /** + * Positionne dans le renderer delege l'icone a utiliser. + * + * @param node le noeud passé au renderer + */ + public void setIcon(ObserveNode node) { + Icon icon = getNavigationIcon(node); + setDefaultIcons(icon); + } + + /** + * Récupère l'icon adequate pour le noeud donnes. + * + * @param node le noeud passé au renderer + * @return l'icone du noeud (ou null si non trouve) + */ + public Icon getNavigationIcon(ObserveNode node) { + Icon icon = getNavigationIcon(node, null); + return icon; + + } + + @Override + public Color getBackgroundSelectionColor() { + return null; + } + + @Override + public Color getBackgroundNonSelectionColor() { + // Fixes http://forge.codelutin.com/issues/830 for jdk 7 + return Color.WHITE; + } + + /** + * Récupère l'icon adequate pour le noeud donnes. + * + * @param node le noeud passé au renderer + * @param suffix un suffix a ajouter a la clef qui identifie l'icone + * @return l'icone du noeud (ou null si non trouve) + */ + public Icon getNavigationIcon(ObserveNode node, String suffix) { + if (node == null || node.isRoot()) { + return null; + } + if (suffix == null) { + suffix = ""; + } + + Icon icon; + + if (node.isReferentielNode()) { + + // referentiel root node + + if (node.isStringNode()) { + icon = UIManager.getIcon("navigation.referentiel" + suffix); + } else { + icon = UIManager.getIcon("navigation.sub.referentiel" + suffix); + } + return icon; + } + + if (!node.isStringNode()) { + + // on est sur un noeud de donnees, rien a calculer + String path = "navigation." + node.getInternalClass().getName() + suffix; + icon = UIManager.getIcon(path); + return icon; + } + + // dernier cas, on est sur un noeud intermediaire sans donnee + // on doit se baser sur le container node + + ObserveNode containerNode = node.getContainerNode(); + + Class<?> containerClass = containerNode.getInternalClass(); + String path; + if (TripSeineDto.class.equals(containerClass)) { + // remonte sur une maree : donc routes + path = RouteDto.class.getName(); + } else if (TripLonglineDto.class.equals(containerClass)) { + // remonte sur une maree : donc activités + path = ActivityLonglineDto.class.getName(); + } else if (RouteDto.class.equals(containerClass)) { + // remonte sur une route : donc activitys + path = ActivitySeineDto.class.getName(); + } +// else if (ActivitySeine.class.equals(containerClass)) { +// // remonte sur une activity : donc observedSystem +// path = ObservedSystemDto.class.getName(); +// } + else { + // dans le cas d'un sub, il n'y a pas de suffixe possible + suffix = ""; + path = containerClass.getName() + ".sub"; + } + icon = UIManager.getIcon("navigation." + path + suffix); + return icon; + } + + public void setDefaultIcons(Icon icon) { + if (icon == null) { + // the icon is not customized for this node + setOpenIcon(getDefaultOpenIcon()); + setClosedIcon(getDefaultClosedIcon()); + setLeafIcon(getDefaultLeafIcon()); + } else { + // replace all possible icons for this node + setOpenIcon(icon); + setClosedIcon(icon); + setLeafIcon(icon); + } + } + + protected String computeNodeText(ObserveNode node) { + + if (node.isStringNode()) { + String text = t(node.getId()); + return text; + } + + Class<?> beanType = node.getInternalClass(); + + if (node.isReferentielNode()) { + + String text = t(DecoratorService.getEntityLabel(ObserveTreeHelper.TREE_NODE_PREFIX, beanType)); + return text; + } + + // noeud de donnée + + String id = node.getId(); + + if (id == null) { + + // noeud d'un objet en cours de création + + String text = t(node.getContext()); + return text; + } + + // noeud de donnée connue en base + + if (getDataProvider() == null) { + // data provider non utilisable + String text = "No data provider opened to render " + id; + return text; + } + + if (node instanceof SetLonglineNode) { + String text = t("observe.tree.setLongline"); + return text; + } + + if (node instanceof SetSeineNode) { + String text = t("observe.tree.setSeine"); + return text; + } + + if (node instanceof DataReferenceNodeSupport) { + DataReferenceNodeSupport<?> entityNodeSupport = (DataReferenceNodeSupport) node; + + DataReference entity = entityNodeSupport.getEntity(); + + Preconditions.checkNotNull(entity, "L'entité doit être chargée dans le noeud: " + node); + + Decorator<?> decorator = getDecoratorService().getDataReferenceDecorator((Class) beanType); + String text = decorator.toString(entity); + + return text; + } + + if (node instanceof ReferentialReferenceNodeSupport) { + ReferentialReferenceNodeSupport<?> entityNodeSupport = (ReferentialReferenceNodeSupport) node; + + ReferentialReference entity = entityNodeSupport.getEntity(); + + Preconditions.checkNotNull(entity, "L'entité doit être chargée dans le noeud: " + node); + + Decorator<?> decorator = getDecoratorService().getReferentialReferenceDecorator((Class) beanType); + String text = decorator.toString(entity); + + return text; + } + + throw new IllegalStateException("Don't know how to render node: " + node); + + } + + public Color getNavigationTextColor(ObserveNode node) { + + if (node == null) { + return openColor; + } + + if (node.isRoot() || node.isReferentielNode()) { + return openColor; + } + + // le noeud pointe sur un objet ouvert + + Class<?> contentClass = node.getInternalClass(); + ObserveNode parentNode = node.getParent(); + Class<?> parentContentClass = parentNode == null ? null : parentNode.getInternalClass(); + + if (log.isTraceEnabled()) { + log.trace("[" + node + "] Content class to use : " + contentClass); + log.trace("[" + node + "] Parent Content class to use : " + parentContentClass); + } + DataContext dataContext = ObserveSwingApplicationContext.get().getDataContext(); + String nodeId = node.getId(); + + if (ProgramDto.class.equals(contentClass)) { + + // on grise le program si aucune marée ouverte sur ce programme + String p = dataContext.getOpenProgramId(); + if (p != null && p.equals(nodeId)) { + return openColor; + } + return closeColor; + } + + boolean nodeIsOpen = isOpenNode(node); + + if (!nodeIsOpen) { + if (log.isDebugEnabled()) { + log.debug("[" + node + "] is not open, use closeColor"); + } + // l'objet pointé n'est pas ouvert + return closeColor; + } + + if (CREATION_UI.contains(contentClass)) { + + // un noeud de creation + if (nodeId == null) { + // mode creation + return redColor; + } + return openColor; + } + + return openColor; + } + + public boolean isOpenNode(ObserveNode node) { + + if (node.isRoot() || node.isReferentielNode()) { + return false; + } + + boolean nodeIsOpen = false; + + ObserveNode openableNode; + openableNode = getFirstOpenableNode(node); + if (log.isDebugEnabled()) { + log.debug("openable node " + + Arrays.toString(openableNode.getPath()) + " for " + + Arrays.toString(node.getPath())); + } + if (openableNode != null) { + Boolean open = openableNode.isOpen(); + nodeIsOpen = open != null && open; + } + + return nodeIsOpen; + } + + /** + * @param value the value which should be a node + * @return the cast {@link ObserveNode}, or {@code null} if + * value is null. + */ + public static ObserveNode getNode(Object value) { + ObserveNode node = null; + if (value instanceof ObserveNode) { + node = (ObserveNode) value; + } + return node; + } + + public ObserveNode getFirstOpenableNode(ObserveNode node) { + + if (OpenableDto.class.isAssignableFrom(node.getInternalClass())) { + return node; + } + + if (ProgramDto.class.isAssignableFrom(node.getInternalClass())) { + return node; + } + + // this is not a openable node, go to parent node + ObserveNode parentNode = node.getParent(); + if (parentNode != null) { + return getFirstOpenableNode(parentNode); + } + return null; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/AbstrctReferenceNodeSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/AbstrctReferenceNodeSupport.java new file mode 100644 index 0000000..869ce2f --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/AbstrctReferenceNodeSupport.java @@ -0,0 +1,115 @@ +package fr.ird.observe.application.swing.ui.tree; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.AbstractReference; +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.application.swing.ui.tree.loadors.AbstractNodeChildLoador; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Created on 4/9/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 4.0 + */ +public abstract class AbstrctReferenceNodeSupport<E extends IdDto, R extends AbstractReference<E>> extends ObserveNode { + + /** Logger. */ + private static final Log log = LogFactory.getLog(AbstrctReferenceNodeSupport.class); + + private static final long serialVersionUID = 1L; + + /** + * Pour cacher l'entité attachée au noeud. + * Elle pourra être directement injectée pour éviter de la recharger (lors de la création d'un modèle initiale). + * + * @since 4.0 + */ + protected transient R entity; + + protected boolean reloadEntity; + + protected abstract R fetchEntity(); + + protected AbstrctReferenceNodeSupport(Class<E> internalClass, R entity) { + this(internalClass, entity, null); + } + + protected AbstrctReferenceNodeSupport(Class<E> type, R entity, AbstractNodeChildLoador<?, ?> childLoador) { + this(type, entity, null, childLoador); + } + + protected AbstrctReferenceNodeSupport(Class<E> type, R entity, String context, AbstractNodeChildLoador<?, ?> childLoador) { + super(type, entity.getId(), context, childLoador, false); + setEntity(entity); + } + + @Override + public void setDirty(boolean dirty) { + super.setDirty(dirty); + + if (dirty && reloadEntity) { + entity = null; + } + + } + + public R getEntity() { + return entity; + } + + public void setEntity(R entity) { + this.entity = entity; + } + + + protected void loadEntity(ObserveDataProvider oProvider) { + + //FIXME +// if (oProvider.getSelectionModel() != null) { +// +// if (log.isDebugEnabled()) { +// log.debug("try to get entity from selectionModel " + internalClass + " : " + id); +// } +// entity = (ReferenceDto<E>) oProvider.getSelectionModel().getEntityCache(id); +// } + + if (entity == null) { + + if (log.isInfoEnabled()) { + log.info("will load entity " + internalClass.getSimpleName() + " : " + id); + } + + entity = fetchEntity(); + + } + + } + + public void setReloadEntity(boolean reloadEntity) { + this.reloadEntity = reloadEntity; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ActivityLonglineNode.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ActivityLonglineNode.java new file mode 100644 index 0000000..42e2d99 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ActivityLonglineNode.java @@ -0,0 +1,52 @@ +package fr.ird.observe.application.swing.ui.tree; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.longline.ActivityLonglineDto; +import fr.ird.observe.services.service.longline.ActivityLonglineService; +import fr.ird.observe.application.swing.ui.tree.loadors.ActivityLonglineNodeChildLoador; + +/** + * Created on 4/9/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 4.0 + */ +public class ActivityLonglineNode extends DataReferenceNodeSupport<ActivityLonglineDto> { + + private static final long serialVersionUID = 1L; + + public ActivityLonglineNode(DataReference<ActivityLonglineDto> entity) { + super(ActivityLonglineDto.class, entity, ObserveTreeHelper.getChildLoador(ActivityLonglineNodeChildLoador.class)); + } + + @Override + protected DataReference<ActivityLonglineDto> fetchEntity() { + ActivityLonglineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivityLonglineService(); + DataReference<ActivityLonglineDto> referenceDto = service.loadReferenceToRead(getId()); + return referenceDto; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ActivitySeineNode.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ActivitySeineNode.java new file mode 100644 index 0000000..fa3015d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ActivitySeineNode.java @@ -0,0 +1,52 @@ +package fr.ird.observe.application.swing.ui.tree; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.services.service.seine.ActivitySeineService; +import fr.ird.observe.application.swing.ui.tree.loadors.ActivitySeineNodeChildLoador; + +/** + * Created on 4/9/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 4.0 + */ +public class ActivitySeineNode extends DataReferenceNodeSupport<ActivitySeineDto> { + + private static final long serialVersionUID = 1L; + + public ActivitySeineNode(DataReference<ActivitySeineDto> entity) { + super(ActivitySeineDto.class, entity, ObserveTreeHelper.getChildLoador(ActivitySeineNodeChildLoador.class)); + } + + @Override + protected DataReference<ActivitySeineDto> fetchEntity() { + ActivitySeineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivitySeineService(); + DataReference<ActivitySeineDto> referenceDto = service.loadReferenceToRead(getId()); + return referenceDto; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/DataReferenceNodeSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/DataReferenceNodeSupport.java new file mode 100644 index 0000000..3d96284 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/DataReferenceNodeSupport.java @@ -0,0 +1,97 @@ +package fr.ird.observe.application.swing.ui.tree; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveOpenDataManager; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.DataDto; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.OpenableDto; +import fr.ird.observe.application.swing.ui.tree.loadors.AbstractNodeChildLoador; +import jaxx.runtime.swing.nav.NavBridge; +import jaxx.runtime.swing.nav.NavDataProvider; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.tree.DefaultTreeModel; + +/** + * Created on 4/9/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 4.0 + */ +public abstract class DataReferenceNodeSupport<E extends DataDto> extends AbstrctReferenceNodeSupport<E, DataReference<E>> { + + /** Logger. */ + private static final Log log = LogFactory.getLog(DataReferenceNodeSupport.class); + + private static final long serialVersionUID = 1L; + + protected DataReferenceNodeSupport(Class<E> internalClass, DataReference<E> entity) { + super(internalClass, entity, null); + } + + protected DataReferenceNodeSupport(Class<E> type, DataReference<E> entity, AbstractNodeChildLoador<?, ?> childLoador) { + super(type, entity, null, childLoador); + } + + protected DataReferenceNodeSupport(Class<E> type, DataReference<E> entity, String context, AbstractNodeChildLoador<?, ?> childLoador) { + super(type, entity, context, childLoador); + } + + @Override + public void populateNode(NavBridge<DefaultTreeModel, ObserveNode> bridge, + NavDataProvider provider, + boolean populateChilds) { + + + try { + super.populateNode(bridge, provider, populateChilds); + } finally { + reloadEntity = false; + } + + if (provider != null && id != null) { + + if (entity == null) { + + loadEntity((ObserveDataProvider) provider); + + } + + if (OpenableDto.class.isAssignableFrom(entity.getType())) { + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ObserveOpenDataManager openDataManager = applicationContext.getOpenDataManager(); + open = openDataManager.isOpen(entity.getId()); + if (log.isDebugEnabled()) { + log.debug("Set open: " + open + " for entity: " + id); + } + + } + + } + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/DataSelectionTreeCellRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/DataSelectionTreeCellRenderer.java new file mode 100644 index 0000000..aced429 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/DataSelectionTreeCellRenderer.java @@ -0,0 +1,138 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.tree; + +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JComponent; +import javax.swing.JTree; +import java.awt.Color; +import java.awt.Component; +import java.util.List; + +import static org.nuiton.i18n.I18n.t; + +/** + * Le renderer pour décorer l'arbre de sélection des données. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.2 + */ +public class DataSelectionTreeCellRenderer extends AbstractObserveTreeCellRenderer { + + /** Logger */ + private static final Log log = LogFactory.getLog(DataSelectionTreeCellRenderer.class); + + private static final long serialVersionUID = 1L; + + protected List<DataReference<?>> existingTrips; + + public List<DataReference<?>> getExistingTrips() { + return existingTrips; + } + + public void setExistingTrips(List<DataReference<?>> existingTrips) { + this.existingTrips = existingTrips; + } + + public DataSelectionTreeCellRenderer() { + } + + @Override + protected void init() { + super.init(); + setBackgroundNonSelectionColor(null); + setBackgroundSelectionColor(null); + setBackground(null); + + setTextNonSelectionColor(Color.BLACK); + setTextSelectionColor(Color.BLUE); + } + + @Override + public Component getTreeCellRendererComponent( + JTree tree, + Object value, + boolean sel, + boolean expanded, + boolean leaf, + int row, + boolean hasFocus) { + + // get the icon to set for the node + ObserveNode node = getNode(value); + + if (node == null) { + return super.getTreeCellRendererComponent( + tree, + value, + sel, + expanded, + leaf, + row, + hasFocus + ); + } + setIcon(node); + + String text = getNodeText(node); + if (log.isDebugEnabled()) { + text += " (" + row + ')'; + log.debug("repaint node " + text + " (selected:" + sel + + ") for node " + node.getId()); + } + + boolean exist = false; + + if (TripSeineDto.class.equals(node.getInternalClass())) { + + if (existingTrips != null) { + + if (existingTrips.contains(((TripSeineNode) node).getEntity())) { + text = t("observe.comon.exist.on.remote", text); + exist = true; + } + } + } + Component comp = super.getTreeCellRendererComponent( + tree, + text, + sel, + expanded, + leaf, + row, + hasFocus + ); + + //FIXME-TC20100316 can not display tooltiptext... +// delegate.setToolTipText(text); + if (exist) { + text = t("observe.message.warning.will.be.delete", text); + } + ((JComponent) comp).setToolTipText(text); + return comp; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/DataSelectionTreeSelectionModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/DataSelectionTreeSelectionModel.java new file mode 100644 index 0000000..d24274c --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/DataSelectionTreeSelectionModel.java @@ -0,0 +1,706 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.tree; + +import com.google.common.collect.Sets; +import fr.ird.observe.services.dto.AbstractReference; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JTree; +import javax.swing.event.EventListenerList; +import javax.swing.event.TreeSelectionEvent; +import javax.swing.event.TreeSelectionListener; +import javax.swing.tree.RowMapper; +import javax.swing.tree.TreePath; +import javax.swing.tree.TreeSelectionModel; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.beans.PropertyChangeSupport; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Enumeration; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Modèle de sélection dans un arbre de navigation prévu pour sélectionner des + * données. + * + * La sélection se fait en cliquant (reclic pour supprimer). + * + * Si on sélectionne un program, alors ses marée sont aussi sélectionnées. + * + * Un program est sélectionné uniquement si toutes ses marées le sont. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.2 + */ +public class DataSelectionTreeSelectionModel implements TreeSelectionModel, PropertyChangeListener, Serializable { + + /** Logger */ + private static final Log log = + LogFactory.getLog(DataSelectionTreeSelectionModel.class); + + private static final long serialVersionUID = -1L; + + protected DataSelectionModel dataModel; + + /** + * Paths that are currently selected. Will be null if nothing is currently + * selected. + */ + protected TreePath[] selection; + + /** Event listener list. */ + protected final EventListenerList listenerList = new EventListenerList(); + + /** Last path that was added. */ + protected TreePath leadPath; + + /** Index of the lead path in selection. */ + protected int leadIndex; + + /** Lead row. */ + protected int leadRow; + + protected int minSelectionRow; + + protected int maxSelectionRow; + + protected int[] selectionRows; + + /** Provides a row for a given path. */ + transient protected RowMapper rowMapper; + + protected Set<TreePath> universe; + + private PropertyChangeSupport changeSupport; + + private static final PropertyChangeListener[] + EMPTY_PROPERTY_CHANGE_LISTENERS = new PropertyChangeListener[]{}; + + public void initUI(JTree tree) { + clearSelection(); + if (universe != null) { + universe.clear(); + } + // expand tree + int i = 0; + while (i < tree.getRowCount()) { + tree.expandRow(i++); + } + // build universe of path : position of path in universe is + // exactly the row of the path + int count = tree.getRowCount(); + universe = new HashSet<>(count); + for (i = 0; i < count; i++) { + TreePath path = tree.getPathForRow(i); + universe.add(path); + if (log.isDebugEnabled()) { + log.debug("init path : " + path.getLastPathComponent()); + } + } + } + + public void setDataModel(DataSelectionModel dataModel) { + DataSelectionModel oldModel = this.dataModel; + if (oldModel != null) { + oldModel.removePropertyChangeListener(this); + oldModel.destroy(); + //TODO Should destroy all other listeners ? + //TODO this means model is dead... + } + this.dataModel = dataModel; + if (dataModel != null) { + this.dataModel.addPropertyChangeListener(this); + } + updateModel(); + } + + @Override + public void setSelectionMode(int mode) { + // pas utilise + } + + @Override + public int getSelectionMode() { + return DISCONTIGUOUS_TREE_SELECTION; + } + + @Override + public void setSelectionPath(TreePath path) { + if (dataModel == null) { + return; + } + Object o = path.getLastPathComponent(); + ObserveNode node = AbstractObserveTreeCellRenderer.getNode(o); + if (node == null) { + return; + } + Class<?> internalClass = node.getInternalClass(); + + boolean referentiel = node.isReferentielNode(); + + if (!universe.contains(path)) { + // new path + universe.add(path); + if (log.isDebugEnabled()) { + log.debug("add new path to universe " + + path.getLastPathComponent()); + } + if (!referentiel && ProgramDto.class.equals(internalClass)) { + if (log.isDebugEnabled()) { + log.debug("Adding program childs path (" + + node.getChildCount() + ")"); + } + // on ajoute toutes les marees du program + Enumeration<?> childs = node.children(); + while (childs.hasMoreElements()) { + Object o1 = childs.nextElement(); + TreePath path1 = path.pathByAddingChild(o1); + if (!universe.contains(path1)) { + if (log.isDebugEnabled()) { + log.debug("adding path for node " + o1); + } + universe.add(path1); + } + } + } + if (TripSeineDto.class.equals(internalClass)) { + TreePath parentPath = path.getParentPath(); + + if (!universe.contains(parentPath)) { + // on ajoute son parent (et tous ses freres) + universe.add(parentPath); + ObserveNode parentNode = node.getParent(); + if (log.isDebugEnabled()) { + log.debug("Adding program with his childs (" + + parentNode.getChildCount() + ")"); + } + Enumeration<?> childs = parentNode.children(); + while (childs.hasMoreElements()) { + Object o1 = childs.nextElement(); + TreePath path1 = parentPath.pathByAddingChild(o1); + if (!universe.contains(path1)) { + if (log.isDebugEnabled()) { + log.debug("adding path for node " + o1); + } + universe.add(path1); + } + } + } + } + } + + boolean pathSelected = isPathSelected(path); + + if (log.isDebugEnabled()) { + log.debug("node " + node + ", path selected ? " + pathSelected); + } + + if (referentiel && node.isStringNode()) { + + Set<Class<? extends ReferentialDto>> subClasses = Sets.newHashSet(); + + for (Enumeration<ObserveNode> children = node.children(); children.hasMoreElements(); ) { + subClasses.add((Class<? extends ReferentialDto>) children.nextElement().getInternalClass()); + } + + if (pathSelected) { + if (log.isDebugEnabled()) { + log.debug("Will remove all referentiels on " + node); + } + dataModel.removeAllReferentiel(subClasses); + } else { + if (log.isDebugEnabled()) { + log.debug("Will add all referentiels on " + node); + } + dataModel.addAllReferentiel(subClasses); + } + return; + } + + if (referentiel) { + + if (pathSelected) { + if (log.isDebugEnabled()) { + log.debug("Will remove referentiel " + internalClass + " to model"); + } + dataModel.removeSelectedReferentiel(internalClass); + } else { + if (log.isDebugEnabled()) { + log.debug("Will add referentiel " + internalClass + " to model"); + } + dataModel.addSelectedReferentiel((Class<? extends ReferentialDto>) internalClass); + } + return; + } + + if (node instanceof AbstrctReferenceNodeSupport) { + AbstractReference dto = ((AbstrctReferenceNodeSupport) node).getEntity(); + if (log.isDebugEnabled()) { + log.debug("bean " + dto.getId()); + } + if (pathSelected) { + if (log.isDebugEnabled()) { + log.debug("Already add ? remove it."); + } + removeFromDataModel(dto); + } else { + if (log.isDebugEnabled()) { + log.debug("Will add selection to model"); + } + addToDataModel(dto); + } + } + } + + @Override + public void setSelectionPaths(TreePath[] paths) { + // do nothing + } + + @Override + public void addSelectionPath(TreePath path) { + // do nothing + } + + @Override + public void addSelectionPaths(TreePath[] paths) { + // do nothing + } + + @Override + public void removeSelectionPath(TreePath path) { + // do nothing + } + + @Override + public void removeSelectionPaths(TreePath[] paths) { + // do nothing + } + + @Override + public TreePath getSelectionPath() { + return selection == null ? null : selection[0]; + } + + @Override + public TreePath[] getSelectionPaths() { + return selection; + } + + @Override + public int getSelectionCount() { + return selection == null ? 0 : selection.length; + } + + @Override + public boolean isPathSelected(TreePath path) { + if (dataModel == null) { + return false; + } + Object o = path.getLastPathComponent(); + ObserveNode node = AbstractObserveTreeCellRenderer.getNode(o); + if (node != null) { + + Class<?> internalClass = node.getInternalClass(); + if (node.isReferentielNode() && node.isStringNode()) { + Set<Class<? extends ReferentialDto>> subClasses = Sets.newHashSet(); + + for (Enumeration<ObserveNode> children = node.children(); children.hasMoreElements(); ) { + subClasses.add((Class<? extends ReferentialDto>) children.nextElement().getInternalClass()); + } + + boolean result = dataModel.isReferentielSelectAll(subClasses); + if (log.isTraceEnabled()) { + log.trace("selectModel use full referentiel " + + internalClass + " ? " + result); + } + return result; + } + if (node.isReferentielNode()) { + boolean result = dataModel.isSelectedReferentiel(internalClass); + if (log.isTraceEnabled()) { + log.trace("selectModel use referentiel " + + internalClass + " ? " + result); + } + return result; + } + + if (log.isTraceEnabled()) { + log.trace("begin data node " + node); + } + + if (node instanceof AbstrctReferenceNodeSupport) { + boolean result = dataModel.isSelectedData(((AbstrctReferenceNodeSupport) node).getEntity()); + if (log.isTraceEnabled()) { + log.trace("selectModel contains the program ? " + result); + } + return result; + } + + + } + return false; + } + + @Override + public boolean isSelectionEmpty() { + return selection == null || selection.length == 0; + } + + @Override + public void clearSelection() { + if (dataModel == null) { + return; + } + selection = null; + dataModel.removeAll(); + } + + @Override + public RowMapper getRowMapper() { + return rowMapper; + } + + @Override + public void setRowMapper(RowMapper newMapper) { + rowMapper = newMapper; + } + + @Override + public int[] getSelectionRows() { + // on doit recalcule cette valeur a chaque fois + //This is currently rather expensive.Needs + // to be better support from ListSelectionModel to speed this up. + return selectionRows; + } + + @Override + public int getMinSelectionRow() { + return minSelectionRow; + } + + @Override + public int getMaxSelectionRow() { + return maxSelectionRow; + } + + @Override + public int getLeadSelectionRow() { + return leadRow; + } + + @Override + public TreePath getLeadSelectionPath() { + return leadPath; + } + + @Override + public boolean isRowSelected(int row) { + if (!isSelectionEmpty()) { + for (int i : selectionRows) { + if (row == i) { + return true; + } + } + } + return false; + } + + @Override + public void resetRowSelection() { + if (log.isDebugEnabled()) { + log.debug("start rebuild row values..."); + } + leadRow = minSelectionRow = maxSelectionRow = -1; + selectionRows = null; + if (rowMapper == null || selection == null || selection.length == 0) { + return; + } + + int[] rows = rowMapper.getRowsForPaths(selection); + + if (rows != null) { + int invisCount = 0; + + for (int counter = rows.length - 1; counter >= 0; counter--) { + if (rows[counter] == -1) { + invisCount++; + } + } + if (invisCount > 0) { + if (invisCount == rows.length) { + rows = null; + } else { + int[] tempRows = new int[rows.length - invisCount]; + + for (int counter = rows.length - 1, visCounter = 0; + counter >= 0; counter--) { + if (rows[counter] != -1) { + tempRows[visCounter++] = rows[counter]; + } + } + rows = tempRows; + } + } + } + + selectionRows = rows; + + if (isSelectionEmpty()) { + leadPath = null; + leadIndex = -1; + leadRow = -1; + } else { + leadPath = selection[0]; + leadIndex = 0; + leadRow = selectionRows[0]; + } + + int selectionLength = selectionRows.length; + + minSelectionRow = -1; + maxSelectionRow = 0; + for (int i = 0; i < selectionLength; i++) { + int row = selectionRows[i]; + if (row > maxSelectionRow) { + maxSelectionRow = row; + } + if (row < minSelectionRow) { + minSelectionRow = row; + } + } + } + + /** + * Adds x to the list of listeners that are notified each time the set of + * selected TreePaths changes. + * + * @param x the new listener to be added + */ + @Override + public void addTreeSelectionListener(TreeSelectionListener x) { + listenerList.add(TreeSelectionListener.class, x); + } + + /** + * Removes x from the list of listeners that are notified each time the set + * of selected TreePaths changes. + * + * @param x the listener to remove + */ + @Override + public void removeTreeSelectionListener(TreeSelectionListener x) { + listenerList.remove(TreeSelectionListener.class, x); + } + + /** + * Returns an array of all the tree selection listeners registered on this + * model. + * + * @return all of this model's {@code TreeSelectionListener}s or an + * empty array if no tree selection listeners are currently + * registered + * @see #addTreeSelectionListener + * @see #removeTreeSelectionListener + * @since 1.4 + */ + public TreeSelectionListener[] getTreeSelectionListeners() { + return listenerList.getListeners(TreeSelectionListener.class); + } + + /** + * Adds a PropertyChangeListener to the listener list. The listener is + * registered for all properties. + * + * A PropertyChangeEvent will get fired when the selection mode changes. + * + * @param listener the PropertyChangeListener to be added + */ + @Override + public void addPropertyChangeListener(PropertyChangeListener listener) { + if (changeSupport == null) { + changeSupport = new PropertyChangeSupport(this); + } + changeSupport.addPropertyChangeListener(listener); + } + + /** + * Removes a PropertyChangeListener from the listener list. This removes a + * PropertyChangeListener that was registered for all properties. + * + * @param listener the PropertyChangeListener to be removed + */ + + @Override + public void removePropertyChangeListener(PropertyChangeListener listener) { + if (changeSupport == null) { + return; + } + changeSupport.removePropertyChangeListener(listener); + } + + /** + * Returns an array of all the property change listeners registered on this + * {@code DefaultTreeSelectionModel}. + * + * @return all of this model's {@code PropertyChangeListener}s or an + * empty array if no property change listeners are currently + * registered + * @see #addPropertyChangeListener + * @see #removePropertyChangeListener + * @since 1.4 + */ + public PropertyChangeListener[] getPropertyChangeListeners() { + if (changeSupport == null) { + return EMPTY_PROPERTY_CHANGE_LISTENERS; + } + return changeSupport.getPropertyChangeListeners(); + } + + protected void fireValueChanged(TreeSelectionEvent e) { + // Guaranteed to return a non-null array + Object[] listeners = listenerList.getListenerList(); + // TreeSelectionEvent e = null; + // Process the listeners last to first, notifying + // those that are interested in this event + for (int i = listeners.length - 2; i >= 0; i -= 2) { + if (TreeSelectionListener.class.equals(listeners[i])) { + // Lazily create the event: + // if (e == null) + // e = new ListSelectionEvent(this, firstIndex, lastIndex); + ((TreeSelectionListener) listeners[i + 1]).valueChanged(e); + } + } + } + + protected void addToDataModel(AbstractReference dto) { + + if (log.isTraceEnabled()) { + log.trace("selectModel add " + dto.getId()); + } + dataModel.addSelectedData(dto); + + } + + protected void removeFromDataModel(AbstractReference dto) { + if (log.isTraceEnabled()) { + log.trace("selectModel remove " + dto.getId()); + } + dataModel.removeSelectedData(dto); + } + + @Override + public void propertyChange(PropertyChangeEvent evt) { + String propertyName = evt.getPropertyName(); + if (DataSelectionModel.PROPERTY_SELECTED_DATA.equals(propertyName) || + DataSelectionModel.PROPERTY_SELECTED_REFERENTIEL.equals(propertyName)) { + // la selection a changee + Object value = evt.getNewValue(); + if (log.isDebugEnabled()) { + log.debug("selection data changed " + value); + } + } + updateModel(); + } + + protected void updateModel() { + if (rowMapper == null || universe == null) { + return; + } + + // recalcule de la selection + + List<TreePath> oldSelection = isSelectionEmpty() ? + Collections.emptyList() : + Arrays.asList(selection); + + List<TreePath> newSelection = new ArrayList<>(); + + for (TreePath p : universe) { + if (isPathSelected(p)) { + newSelection.add(p); + } + } + + int selectionLength = newSelection.size(); + + selection = newSelection.toArray(new TreePath[selectionLength]); + + // calcul du leadPath + + TreePath oldLeadPath = leadPath; + + if (isSelectionEmpty()) { + leadPath = null; + leadIndex = -1; + } else { + leadPath = selectionLength > 0 ? selection[0] : null; + leadIndex = 0; + } + + if (log.isDebugEnabled()) { + log.debug("new selection length = " + selectionLength); + } + + // recalcule des donnees de rows + resetRowSelection(); + + if (log.isDebugEnabled()) { + log.debug("new selection length = " + + (selectionRows == null ? 0 : selectionRows.length)); + if (log.isDebugEnabled()) { + log.debug("selected rows = " + Arrays.toString(selectionRows)); + } + } + + // calcule des paths qui ont changés + List<TreePath> obsoleteSelection = new ArrayList<>(oldSelection); + obsoleteSelection.removeAll(newSelection); + + List<TreePath> changedPaths = new ArrayList<>(oldSelection); + changedPaths.addAll(newSelection); + + TreePath[] treePaths = changedPaths.toArray(new TreePath[changedPaths.size()]); + + // notification des modifications sur la selection + TreeSelectionEvent event = new TreeSelectionEvent( + this, + treePaths, + new boolean[treePaths.length], + oldLeadPath, + leadPath + ); + fireValueChanged(event); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/FloatingObjectSeineNode.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/FloatingObjectSeineNode.java new file mode 100644 index 0000000..8fe8191 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/FloatingObjectSeineNode.java @@ -0,0 +1,52 @@ +package fr.ird.observe.application.swing.ui.tree; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.seine.FloatingObjectDto; +import fr.ird.observe.services.service.seine.FloatingObjectService; +import fr.ird.observe.application.swing.ui.tree.loadors.FloatingObjectNodeChildLoador; + +/** + * Created on 4/9/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 4.0 + */ +public class FloatingObjectSeineNode extends DataReferenceNodeSupport<FloatingObjectDto> { + + private static final long serialVersionUID = 1L; + + public FloatingObjectSeineNode(DataReference<FloatingObjectDto> entity) { + super(FloatingObjectDto.class, entity, ObserveTreeHelper.getChildLoador(FloatingObjectNodeChildLoador.class)); + } + + @Override + protected DataReference<FloatingObjectDto> fetchEntity() { + FloatingObjectService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newFloatingObjectService(); + DataReference<FloatingObjectDto> referenceDto = service.loadReferenceToRead(getId()); + return referenceDto; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/NavigationTreeCellRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/NavigationTreeCellRenderer.java new file mode 100644 index 0000000..02d159a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/NavigationTreeCellRenderer.java @@ -0,0 +1,99 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.tree; + +import javax.swing.JComponent; +import javax.swing.JTree; +import javax.swing.tree.DefaultTreeModel; +import java.awt.Color; +import java.awt.Component; + +/** + * Un renderer pour modifier l'apparence des noeuds de l'arbre de navigation. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class NavigationTreeCellRenderer extends AbstractObserveTreeCellRenderer { + + private static final long serialVersionUID = 1L; + + public NavigationTreeCellRenderer() { + } + + @Override + public Component getTreeCellRendererComponent(JTree tree, + Object value, + boolean sel, + boolean expanded, + boolean leaf, + int row, + boolean hasFocus) { + + if (!(tree.getModel() instanceof DefaultTreeModel)) { + Component rendererComponent; + rendererComponent = super.getTreeCellRendererComponent( + tree, + value, + sel, + expanded, + leaf, + row, + hasFocus + ); + return rendererComponent; + } + + // get the icon to set for the node + ObserveNode node = getNode(value); + + setIcon(node); + + if (!sel) { + + Color color = getNavigationTextColor(node); + if (log.isTraceEnabled()) { + log.trace("===" + color + " for node " + + node.getInternalClass() + " - " + node.getId()); + } + setTextNonSelectionColor(color); + } + + String text = getNodeText(node); + if (log.isTraceEnabled()) { + log.trace("===" + text + " for node " + + node.getInternalClass() + " - " + node.getId()); + } + Component comp = super.getTreeCellRendererComponent( + tree, + text, + sel, + expanded, + leaf, + row, + hasFocus + ); + ((JComponent) comp).setToolTipText(text); + return comp; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/NavigationTreeSelectionModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/NavigationTreeSelectionModel.java new file mode 100644 index 0000000..5e3cff5 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/NavigationTreeSelectionModel.java @@ -0,0 +1,118 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.tree; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.ui.UIHelper; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.tree.DefaultTreeSelectionModel; +import javax.swing.tree.TreePath; + +/** + * Le modèle de sélection de l'abre de navigation. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class NavigationTreeSelectionModel extends DefaultTreeSelectionModel { + + /** Logger */ + static private final Log log = + LogFactory.getLog(NavigationTreeSelectionModel.class); + + private static final long serialVersionUID = 1L; + + @Override + public void addSelectionPath(TreePath newPath) { + TreePath oldPath = getSelectionPath(); + if (log.isDebugEnabled()) { + log.debug(">------------------------------------------------------------------------------"); + log.debug("Try to change selection"); + log.debug("old path " + oldPath); + log.debug("new path " + newPath); + } + boolean canChange = beforeSelectionPath(oldPath, newPath); + if (log.isDebugEnabled()) { + log.debug("Can change path ? " + canChange); + log.debug("<------------------------------------------------------------------------------"); + } + if (!canChange) { + return; + } + + // ok can safely select the new path + if (log.isTraceEnabled()) { + log.trace("will select path " + newPath); + } + super.addSelectionPath(newPath); + } + + @Override + public void setSelectionPath(TreePath newPath) { + TreePath oldPath = getSelectionPath(); + if (log.isDebugEnabled()) { + log.debug(">------------------------------------------------------------------------------"); + log.debug("Try to change selection"); + log.debug("old path " + oldPath); + log.debug("new path " + newPath); + } + boolean canChange = beforeSelectionPath(oldPath, newPath); + if (log.isDebugEnabled()) { + log.debug("Can change path ? " + canChange); + log.debug("<------------------------------------------------------------------------------"); + } + if (!canChange) { + return; + } + + // ok can safely select the new path + if (log.isTraceEnabled()) { + log.trace("will select path " + newPath); + } + try { + super.setSelectionPath(newPath); + } catch (Exception e) { + UIHelper.handlingError(e); + } + } + + protected boolean beforeSelectionPath(TreePath oldPath, TreePath newPath) { + + boolean canChange = true; + + if (newPath.equals(oldPath)) { + // stay on same node, can skip + if (log.isDebugEnabled()) { + log.debug("skip stay on path " + newPath); + } + canChange = false; + } + + if (canChange && !isSelectionEmpty()) { + canChange = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); + } + + return canChange; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ObserveDataProvider.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ObserveDataProvider.java new file mode 100644 index 0000000..c3e890c --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ObserveDataProvider.java @@ -0,0 +1,83 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.tree; + +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel; +import jaxx.runtime.swing.nav.NavDataProvider; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Provider de données pour les noeuds des arbres. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ObserveDataProvider implements NavDataProvider { + + /** Logger */ + static private final Log log = LogFactory.getLog(ObserveDataProvider.class); + + protected ObserveSwingDataSource dataSource; + + protected DataSelectionModel selectionModel; + + private boolean creating; + + public ObserveDataProvider(ObserveSwingDataSource dataSource) { + this.dataSource = dataSource; + } + + public void setSource(ObserveSwingDataSource dataSource) { + this.dataSource = dataSource; + } + + public void setSelectionModel(DataSelectionModel selectionModel) { + if (log.isDebugEnabled()) { + log.debug("Set selection model : " + selectionModel); + } + this.selectionModel = selectionModel; + } + + @Override + public boolean isEnabled() { + return dataSource != null && dataSource.isOpen() || selectionModel != null; + } + + public ObserveSwingDataSource getDataSource() { + return dataSource; + } + + public DataSelectionModel getSelectionModel() { + return selectionModel; + } + + public boolean isCreating() { + return creating; + } + + public void setCreating(boolean creating) { + this.creating = creating; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ObserveNavigationTreeShowPopupAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ObserveNavigationTreeShowPopupAction.java new file mode 100644 index 0000000..6bc2ac0 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ObserveNavigationTreeShowPopupAction.java @@ -0,0 +1,392 @@ +package fr.ird.observe.application.swing.ui.tree; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.base.Preconditions; +import com.google.common.collect.ImmutableMap; +import fr.ird.observe.application.swing.ObserveOpenDataManager; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.ui.content.ContentUI; +import fr.ird.observe.application.swing.ui.content.open.ContentOpenableUI; +import fr.ird.observe.application.swing.ui.tree.menu.MoveActivityLonglineNodeMenuPopulator; +import fr.ird.observe.application.swing.ui.tree.menu.MoveActivitySeineNodeMenuPopulator; +import fr.ird.observe.application.swing.ui.tree.menu.MoveNodeMenuPopulator; +import fr.ird.observe.application.swing.ui.tree.menu.MoveRouteNodeMenuPopulator; +import fr.ird.observe.application.swing.ui.tree.menu.MoveTripNodeMenuPopulator; +import fr.ird.observe.application.swing.ui.util.DecoratedNodeEntity; +import jaxx.runtime.SwingUtil; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JButton; +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; +import javax.swing.JScrollPane; +import javax.swing.JTree; +import javax.swing.MenuElement; +import javax.swing.SwingUtilities; +import javax.swing.tree.TreePath; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Created on 1/8/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.11 + */ +public class ObserveNavigationTreeShowPopupAction { + + /** Logger. */ + private static final Log log = LogFactory.getLog(ObserveNavigationTreeShowPopupAction.class); + + private static final String TRIP_MENU_ITEMS = "trip"; + private static final String ROUTE_MENU_ITEMS = "route"; + private static final String ACTIVITY_SEINE_MENU_ITEMS = "activitySeine"; + private static final String ACTIVITY_LONGLINE_MENU_ITEMS = "activityLongline"; + + static { + n("observe.navigationMenu.move.trip"); + n("observe.navigationMenu.move.route"); + n("observe.navigationMenu.move.activitySeine"); + n("observe.navigationMenu.move.activityLongline"); + } + + private final ObserveTreeHelper treeHelper; + + private final JScrollPane pane; + + private final JPopupMenu popup; + + private final JTree tree; + + private final JMenuItem noAction; + private final JMenuItem openAction; + private final JMenuItem closeAction; + private final JMenuItem moveAction; + private final JMenuItem deleteAction; + + private final ImmutableMap<String, MoveNodeMenuPopulator> moveNodeDataByNodeType; + + public ObserveNavigationTreeShowPopupAction(final ObserveTreeHelper treeHelper, JScrollPane pane, JPopupMenu popup) { + + this.treeHelper = treeHelper; + this.pane = pane; + this.popup = popup; + this.tree = treeHelper.getUI(); + + JMenuItem noActionComponent = null; + // trip menus + JMenuItem moveComponent = null; + JMenuItem openActionComponent = null; + JMenuItem closeActionComponent = null; + JMenuItem deleteActionComponent = null; + + for (MenuElement menuElement : popup.getSubElements()) { + + if (menuElement.getComponent().getName().equals("navigationNoAction")) { + noActionComponent = (JMenuItem) menuElement.getComponent(); + } + if (menuElement.getComponent().getName().equals("navigationMoveAction")) { + moveComponent = (JMenuItem) menuElement.getComponent(); + } + if (menuElement.getComponent().getName().equals("navigationOpenAction")) { + openActionComponent = (JMenuItem) menuElement.getComponent(); + } + if (menuElement.getComponent().getName().equals("navigationCloseAction")) { + closeActionComponent = (JMenuItem) menuElement.getComponent(); + } + if (menuElement.getComponent().getName().equals("navigationDeleteAction")) { + deleteActionComponent = (JMenuItem) menuElement.getComponent(); + } + } + + this.noAction = noActionComponent; + this.openAction = openActionComponent; + this.closeAction = closeActionComponent; + this.moveAction = moveComponent; + this.deleteAction = deleteActionComponent; + + moveNodeDataByNodeType = ImmutableMap.of(TRIP_MENU_ITEMS, new MoveTripNodeMenuPopulator(), + ROUTE_MENU_ITEMS, new MoveRouteNodeMenuPopulator(), + ACTIVITY_SEINE_MENU_ITEMS, new MoveActivitySeineNodeMenuPopulator(), + ACTIVITY_LONGLINE_MENU_ITEMS, new MoveActivityLonglineNodeMenuPopulator()); + + KeyAdapter keyAdapter = new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + if (tree.isEnabled()) { + openNodeMenu(e); + } + } + }; + tree.addKeyListener(keyAdapter); + pane.addKeyListener(keyAdapter); + + MouseAdapter mouseAdapter = new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (tree.isEnabled()) { + autoSelectNodeInTree(e); + } + } + }; + tree.addMouseListener(mouseAdapter); + pane.addMouseListener(mouseAdapter); + } + + protected void autoSelectNodeInTree(MouseEvent e) { + + boolean rightClick = SwingUtilities.isRightMouseButton(e); + + if (rightClick) { + + // get the coordinates of the mouse click + Point p = e.getPoint(); + + int closestRowForLocation = tree.getClosestRowForLocation(e.getX(), e.getY()); + + int rowToSelect = -1; + + if (isRowSelected(closestRowForLocation)) { + + rowToSelect = closestRowForLocation; + } + + if (rowToSelect == -1) { + + // try to change selection + + TreePath pathForRow = tree.getPathForRow(closestRowForLocation); + tree.setSelectionPath(pathForRow); + + if (isRowSelected(closestRowForLocation)) { + + rowToSelect = closestRowForLocation; + } + + } + + if (rowToSelect != -1) { + + showPopup(rowToSelect, p); + + } + + } + } + + public void openNodeMenu(KeyEvent e) { + + if (e.getKeyCode() == KeyEvent.VK_CONTEXT_MENU && !tree.isSelectionEmpty()) { + + // get the lowest selected row + int lowestRow = getLowestSelectedRowCount(); + + // get the selected column + Rectangle r = tree.getRowBounds(lowestRow); + + // get the point in the middle lower of the cell + Point p = new Point(r.x + r.width / 2, r.y + r.height); + + if (log.isDebugEnabled()) { + log.debug("Row " + lowestRow + " found t point [" + p + "]"); + } + + showPopup(lowestRow, p); + + } + } + + protected void showPopup(int row, Point p) { + + if (log.isInfoEnabled()) { + log.info("Will show popup from row: " + row); + } + + ObserveNode selectedNode = (ObserveNode) tree.getPathForRow(row).getLastPathComponent(); + + if (log.isInfoEnabled()) { + log.info("Found selected node: " + selectedNode); + } + + beforeOpenPopup(selectedNode); + + popup.show(tree, p.x, p.y); + + } + + protected void beforeOpenPopup(ObserveNode selectedNode) { + + // clean popup + popup.removeAll(); + + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + DataContext dataContext = applicationContext.getDataContext(); + ContentUI<?> selectedContentUI = applicationContext.getContentUIManager().getSelectedContentUI(); + ObserveOpenDataManager openDataManager = applicationContext.getOpenDataManager(); + + boolean closeActionEnabled = false; + + if (selectedContentUI instanceof ContentOpenableUI) { + JButton closeButton = ((ContentOpenableUI) selectedContentUI).getClose(); + closeActionEnabled = closeButton.isEnabled(); + } + + if (selectedNode.isTripNode()) { + + beforeOpenMenu(selectedNode, TRIP_MENU_ITEMS); + + openAction.setEnabled(!dataContext.isOpenTrip()); + closeAction.setEnabled(closeActionEnabled); + + } else if (selectedNode.isRouteNode()) { + + beforeOpenMenu(selectedNode, ROUTE_MENU_ITEMS); + + openAction.setEnabled(openDataManager.canOpenRoute(dataContext.getSelectedTripSeineId())); + closeAction.setEnabled(closeActionEnabled); + + } else if (selectedNode.isActivitySeineNode()) { + + beforeOpenMenu(selectedNode, ACTIVITY_SEINE_MENU_ITEMS); + + openAction.setEnabled(openDataManager.canOpenActivitySeine(dataContext.getSelectedRouteId())); + closeAction.setEnabled(closeActionEnabled); + + } else if (selectedNode.isActivityLonglineNode()) { + + beforeOpenMenu(selectedNode, ACTIVITY_LONGLINE_MENU_ITEMS); + + openAction.setEnabled(openDataManager.canOpenActivityLongline(dataContext.getSelectedTripLonglineId())); + closeAction.setEnabled(closeActionEnabled); + + } else { + + popup.add(noAction); + } + } + + protected void beforeOpenMenu(ObserveNode selectedNode, String nodeType) { + if (log.isInfoEnabled()) { + log.info("Will load popup for " + nodeType + " node."); + } + + MoveNodeMenuPopulator moveNodeData = moveNodeDataByNodeType.get(nodeType); + + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + + if (selectedNode.isOpen()) { + + closeAction.putClientProperty("ui", applicationContext.getContentUIManager().getSelectedContentUI()); + popup.add(closeAction); + + + } else { + + openAction.putClientProperty("ui", applicationContext.getContentUIManager().getSelectedContentUI()); + popup.add(openAction); + + } + + moveAction.setText(t("observe.navigationMenu.move." + nodeType)); + moveAction.setToolTipText(t("observe.navigationMenu.move." + nodeType)); + moveAction.setIcon(SwingUtil.getUIManagerActionIcon("move-" + nodeType)); + popup.add(moveAction); + + moveAction.removeAll(); + + // get the available program for the trip + + String id = selectedNode.getId(); + + ObserveSwingDataSource dataSource = treeHelper.getDataProvider().getDataSource(); + + List<DecoratedNodeEntity> possibleParentNodes = moveNodeData.getPossibleParentNodes(selectedNode, treeHelper); + + for (DecoratedNodeEntity possibleParent : possibleParentNodes) { + + String possibleParentId = possibleParent.getId(); + JMenuItem item = new JMenuItem(possibleParent.toString()); + item.setName(possibleParentId); + + + item.addActionListener(moveNodeData.createChangeActionListener(treeHelper, + dataSource, + id, + possibleParentId)); + + moveAction.add(item); + } + + deleteAction.putClientProperty("ui", applicationContext.getContentUIManager().getSelectedContentUI()); + deleteAction.setEnabled(selectedNode.isOpen()); + popup.add(deleteAction); + } + + protected boolean isRowSelected(int requiredRow) { + + boolean result = false; + + int[] selectedRows = tree.getSelectionRows(); + if (selectedRows != null) { + for (int selectedRow : selectedRows) { + if (requiredRow == selectedRow) { + + // match + result = true; + break; + } + } + } + + return result; + + } + + protected int getLowestSelectedRowCount() { + + Preconditions.checkState(!tree.isSelectionEmpty()); + + int[] selectedRows = tree.getSelectionRows(); + int lowestRow = -1; + if (selectedRows != null) { + for (int row : selectedRows) { + lowestRow = Math.max(lowestRow, row); + } + } + return lowestRow; + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ObserveNode.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ObserveNode.java new file mode 100644 index 0000000..5086216 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ObserveNode.java @@ -0,0 +1,119 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.tree; + +import fr.ird.observe.services.dto.OpenableDto; +import fr.ird.observe.services.dto.longline.ActivityLonglineDto; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import jaxx.runtime.swing.nav.tree.NavTreeNode; +import jaxx.runtime.swing.nav.tree.NavTreeNodeChildLoador; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Le modèle d'une noeud. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ObserveNode extends NavTreeNode<ObserveNode> { + + /** Logger */ + static private final Log log = LogFactory.getLog(ObserveNode.class); + + public static long count; + + private static final long serialVersionUID = 1L; + + /** un drapeau pour savoir si le noeud fait parti du referentiel */ + protected final boolean referentiel; + + /** + * Un etat pour savoir si l'objet (de donnee) encapsule est ouvert. + * + * <b>Note:</b> Il faut que l'objet soit de type {@link OpenableDto}. + */ + protected Boolean open; + + public ObserveNode(String id, boolean referentiel) { + this(String.class, id, null, null, referentiel); + } + + public ObserveNode(Class<?> internalClass, + String id, + boolean referentiel) { + this(internalClass, id, null, null, referentiel); + } + + public ObserveNode(Class<?> internalClass, + String id, + NavTreeNodeChildLoador<?, ?, ObserveNode> childLoador, + boolean referentiel) { + this(internalClass, id, null, childLoador, referentiel); + } + + public ObserveNode(Class<?> internalClass, + String id, + String context, + NavTreeNodeChildLoador<?, ?, ObserveNode> childLoador, + boolean referentiel) { + super(internalClass, id, context, childLoador); + this.referentiel = referentiel; + count++; + if (log.isDebugEnabled()) { + log.debug("Creates a new node [" + count + "] " + this); + } + } + + public boolean isDataNode() { + return !referentiel; + } + + public boolean isReferentielNode() { + return referentiel; + } + + public Boolean isOpen() { + return open; + } + + public boolean isTripNode() { + return isDataNode() && + (TripSeineDto.class.isAssignableFrom(internalClass) + || TripLonglineDto.class.isAssignableFrom(internalClass)); + } + + public boolean isRouteNode() { + return isDataNode() && RouteDto.class.isAssignableFrom(internalClass); + } + + public boolean isActivitySeineNode() { + return isDataNode() && ActivitySeineDto.class.isAssignableFrom(internalClass); + } + + public boolean isActivityLonglineNode() { + return isDataNode() && ActivityLonglineDto.class.isAssignableFrom(internalClass); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ObserveTreeBridge.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ObserveTreeBridge.java new file mode 100644 index 0000000..398089e --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ObserveTreeBridge.java @@ -0,0 +1,141 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2011 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.tree; + +import jaxx.runtime.swing.nav.tree.NavTreeBridge; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JTree; +import javax.swing.tree.TreeNode; +import javax.swing.tree.TreePath; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +/** + * Bridge specialise pour reduire le count de chargements de noeuds non visibles. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 2.0 + */ +public class ObserveTreeBridge extends NavTreeBridge<ObserveNode> { + + /** Logger. */ + static private final Log log = LogFactory.getLog(ObserveTreeBridge.class); + + protected JTree ui; + + protected final List<String> pathToSelect; + + public ObserveTreeBridge() { + pathToSelect = new ArrayList<>(); + } + + public void setUi(JTree ui) { + this.ui = ui; + } + + @Override + public boolean canLoadChild(ObserveNode node) { + + ObserveNode root = getRoot(); + if (node.equals(root)) { + + // always allow to load childs from level 0 + return true; + } + ObserveNode parent = node.getParent(); + if (parent.equals(root)) { + + // always allow to load childs from level 0 + return true; + } + + TreeNode[] pathToRoot = getPathToRoot(node); + TreePath path = new TreePath(pathToRoot); + if (CollectionUtils.isNotEmpty(pathToSelect)) { + + // select mode is on + if (log.isDebugEnabled()) { + log.debug("There is a selected path, try to use it for " + node); + } + String nodeId = node.getId(); + + ObserveNode containerNode; + if (nodeId.startsWith(ObserveTreeHelper.TREE_NODE_PREFIX)) { + containerNode = node.getParent(); + } else { + containerNode = node; + } + + String containerNodeId = containerNode.getId(); + if (log.isDebugEnabled()) { + log.debug("Test if data node is in path ? " + + containerNodeId + " : " + + pathToSelect.contains(containerNodeId)); + } + + if (pathToSelect.contains(containerNodeId)) { + + // ok on the good way... + return true; + } + + // not on a good way, skip loading of childs... + return false; + } + + if (ui == null) { + if (log.isDebugEnabled()) { + log.debug("No ui in bridge!!!"); + } + + // no ui, and no path to select : so no need to restrict + return true; + } + + boolean visible = ui.isVisible(path); + + if (!visible) { + + // only visible node can be loaded + return false; + } + + TreePath selected = ui.getSelectionPath(); + if (!path.equals(selected)) { + + // only selected node can be loaded + return false; + } + + // ok childs can be loaded + return true; + } + + public void setPathToSelect(String... pathToSelect) { + this.pathToSelect.clear(); + this.pathToSelect.addAll(Arrays.asList(pathToSelect)); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ObserveTreeHelper.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ObserveTreeHelper.java new file mode 100644 index 0000000..c36cf48 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ObserveTreeHelper.java @@ -0,0 +1,669 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.tree; + +import com.google.common.base.Preconditions; +import com.google.common.collect.Lists; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.services.dto.constants.ReferentialLocale; +import fr.ird.observe.services.dto.longline.ActivityLonglineDto; +import fr.ird.observe.services.dto.longline.SetLonglineDto; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.dto.reference.ReferenceBinderEngine; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.services.dto.seine.FloatingObjectDto; +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.services.dto.seine.SetSeineDto; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.application.swing.ui.ObserveMainUI; +import fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel; +import fr.ird.observe.application.swing.ui.tree.loadors.AbstractNodeChildLoador; +import fr.ird.observe.application.swing.ui.tree.loadors.ActivityLonglineNodeChildLoador; +import fr.ird.observe.application.swing.ui.tree.loadors.ActivityLonglinesNodeChildLoador; +import fr.ird.observe.application.swing.ui.tree.loadors.ActivitySeineNodeChildLoador; +import fr.ird.observe.application.swing.ui.tree.loadors.ActivitySeinesNodeChildLoador; +import fr.ird.observe.application.swing.ui.tree.loadors.ProgramLonglineNodeChildLoador; +import fr.ird.observe.application.swing.ui.tree.loadors.ProgramSeineNodeChildLoador; +import fr.ird.observe.application.swing.ui.tree.loadors.RootNodeChildLoador; +import fr.ird.observe.application.swing.ui.tree.loadors.RoutesNodeChildLoador; +import jaxx.runtime.JAXXContext; +import jaxx.runtime.swing.nav.NavDataProvider; +import jaxx.runtime.swing.nav.tree.NavTreeHelper; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JTree; +import javax.swing.tree.DefaultTreeModel; +import javax.swing.tree.TreeCellRenderer; +import javax.swing.tree.TreeModel; +import javax.swing.tree.TreePath; +import javax.swing.tree.TreeSelectionModel; +import java.util.Arrays; +import java.util.Collections; +import java.util.Comparator; +import java.util.List; +import java.util.Set; + +import static org.nuiton.i18n.I18n.n; + +/** + * Class utilitaire pour la bestion de l'arbre de navigation. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ObserveTreeHelper extends NavTreeHelper<ObserveNode> { + + public static final String TREE_NODE_PREFIX = "observe.tree."; + + /** Logger. */ + static private final Log log = LogFactory.getLog(ObserveTreeHelper.class); + + private boolean createUnsaved; + + public static ObserveNode createStringNode(String context) { + + ObserveNode result = createStringNode(context, null); + return result; + + } + + public static <L extends AbstractNodeChildLoador> ObserveNode createStringNode(String context, Class<L> loadorType) { + + L childLoador = loadorType == null ? null : ObserveTreeHelper.getChildLoador(loadorType); + + String propertyLabel = DecoratorService.getPropertyLabel(TREE_NODE_PREFIX, context); + ObserveNode result = new ObserveNode(String.class, + propertyLabel, + context, + childLoador, + false); + return result; + + } + + public static void sortPrograms(List<ReferentialReference<ProgramDto>> data) { + Collections.sort(data, new Comparator<ReferentialReference<ProgramDto>>() { + + ReferentialReferenceDecorator<ProgramDto> decorator = ObserveSwingApplicationContext.get().getDecoratorService().getReferentialReferenceDecorator(ProgramDto.class); + + @Override + public int compare(ReferentialReference<ProgramDto> o1, ReferentialReference<ProgramDto> o2) { + + + return this.decorator.toString(o1).compareTo(this.decorator.toString(o2)); + } + }); + } + + public ObserveTreeHelper() { + super(new ObserveTreeBridge()); + } + + public NavigationTreeSelectionModel newNavigationSelectionModel() { + NavigationTreeSelectionModel model = new NavigationTreeSelectionModel(); + model.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); + return model; + } + + public AbstractObserveTreeCellRenderer getTreeCellRenderer() { + JTree t = getUI(); + if (t == null) { + return null; + } + TreeCellRenderer r = t.getCellRenderer(); + return (AbstractObserveTreeCellRenderer) + (r instanceof AbstractObserveTreeCellRenderer ? r : null); + } + + public TreeModel createEmptyModel() { + + setDataSource(null); + + ObserveNode node = + new ObserveNode(n("observe.message.db.none.loaded"), false); + + DefaultTreeModel model = createModel(node); + return model; + } + + public TreeModel createModel(ObserveSwingDataSource source) { + + setDataSource(source); + + ObserveDataProvider provider = getDataProvider(); + provider.setCreating(true); + + try { + + RootNodeChildLoador loador = new RootNodeChildLoador(source.canReadData(), true); + ObserveNode node = new ObserveNode(String.class, "Root node", null, loador, false); + + DefaultTreeModel model = createModel(node); + node.populateChilds(getBridge(), provider); + return model; + + } finally { + + provider.setCreating(false); + + } + } + + public DefaultTreeModel createModel(JAXXContext context, + DataSelectionModel dataModel, + ObserveSwingDataSource source) { + + setDataSource(source); + context.setContextValue(dataModel); + + if (log.isDebugEnabled()) { + log.debug("create tree model " + this); + } + + ObserveDataProvider provider = getDataProvider(); + provider.setSelectionModel(dataModel); + provider.setCreating(true); + + if (getTreeCellRenderer() != null) { + getTreeCellRenderer().setDataProvider(provider); + } + + try { + + RootNodeChildLoador loador = getChildLoador(RootNodeChildLoador.class); + loador.setAddData(dataModel.isUseData()); + loador.setAddReferentiel(dataModel.isUseReferentiel()); + ObserveNode node = new ObserveNode(String.class, "Root node", loador, false); + + DefaultTreeModel model = createModel(node); + loadAllNodes(node, provider); + return model; + + } finally { + + provider.setCreating(false); + + } + + } + + /** + * Charge dans l'ui un nouveau modèle de navigation. + * + * <b>Note:</b> cette méthode doit être appelée après tout rechargement de + * modèle de naivgation. + * + * @param source la source de données + */ + public void loadNavigationUI(ObserveSwingDataSource source) { + + ObserveNode.count = 0; + + // propagate ui in observe bridge to control which nodes can be loads + // from ui state + getBridge().setUi(getUI()); + + // build navigation model + createModel(source); + + // select initial node + selectInitialNode(); + + getUI().setVisible(true); + } + + /** + * Nettoye des ui tout ce qui concerne un modèle de navigation. + * + * <b>Note:</b> cette méthode doit être appelée avant tout rechargement de + * modèle de naivgation. + * + * @param mainUI l'ui principale + */ + public void cleanNavigationUI(ObserveMainUI mainUI) { + + // invalidate provider + setDataSource(null); + + // reset content uis + mainUI.getContentLayout().reset(mainUI.getContent()); + + // clean messages + mainUI.getContextValue(SwingValidatorMessageTableModel.class).clear(); + + // clean tree model + + JTree tree = getUI(); + + // remove tree from bridge to disable propagation of any node + getBridge().setUi(null); + + ObserveNode root = getBridge().getRoot(); + root.removeAllChildren(); + createEmptyModel(); + + // no tree navigation view + tree.setVisible(false); + } + + public void selectOpenNode(Class<?> type) { + + DataContext context = ObserveSwingApplicationContext.get().getDataContext(); + + String[] ids = context.getOpenIds(type); + + if (log.isDebugEnabled()) { + log.debug("using open ids = " + Arrays.toString(ids)); + } + if (ids == null) { + + // rien n'est ouvert, rien à selectionner + return; + } + + selectNode(ids); + } + + /** + * Sélectionne le noeud dans l'arbre de navigation. + * + * <b>Note:</b> cette méthode doit être appelée après un rechargement du + * modèle de navigation. + * + */ + public void selectInitialNode() { + + if (log.isDebugEnabled()) { + log.debug("Will select initial node..."); + } + DataContext context = ObserveSwingApplicationContext.get().getDataContext(); + + String[] path; + + JTree tree = getUI(); + + List<String> selectedIds = ObserveSwingApplicationContext.get().getNodesToReselect(); + if (CollectionUtils.isNotEmpty(selectedIds)) { + if (log.isDebugEnabled()) { + log.debug("will select previous ids " + selectedIds); + } + path = selectedIds.toArray(new String[selectedIds.size()]); + } else { + + // on trouve le meilleur noeud a selectionner. + + String id = context.getHigherOpenId(); + + if (id != null) { + + // on se positionne sur la donnée la plus haute ouverte + path = context.getOpenIds(); + if (log.isDebugEnabled()) { + log.debug("will select open ids " + Arrays.toString(path)); + } + } else { + + // on selectionne le premier noeud de $root + + ObserveNode node = (ObserveNode) tree.getModel().getRoot(); + if (!node.isLeaf()) { + node = node.getFirstChild(); + } + path = new String[]{node.getId()}; + if (log.isDebugEnabled()) { + log.debug("will select first program " + Arrays.toString(path)); + } + } + } + + if (log.isDebugEnabled()) { + log.debug("Selected path : " + Arrays.toString(path)); + } + + try { + + selectNode(path); + } finally { + + // nettoyage du context + ObserveSwingApplicationContext.get().setNodesToReselect(null); + } + + // navigation tree should acquire focus + tree.requestFocus(); + } + + @Override + public void selectNode(String... path) { + long count = ObserveNode.count; + if (log.isDebugEnabled()) { + log.debug("Will select path : " + Arrays.toString(path)); + } + getBridge().setPathToSelect(path); + try { + super.selectNode(path); + } finally { + getBridge().setPathToSelect(); + if (log.isInfoEnabled()) { + log.info("Creates " + (ObserveNode.count - count) + " nodes to select path " + Arrays.toString(path)); + } + } + } + + public ObserveNode addUnsavedNode(ObserveNode parentNode, Class<?> type) { + + // noeud en mode creation + String label = DecoratorService.getEntityLabel(TREE_NODE_PREFIX, type) + ".unsaved"; + ObserveNode result = new ObserveNode(type, null, label, null, false); + insertNode(parentNode, result); + + // refresh parent node (render of parent can have changed) + refreshNode(parentNode, true); + + // Fix bug (if no child in parent node, it will not expand...) + getUI().fireTreeExpanded(new TreePath(result.getPath())); + + createUnsaved = true; + + try { + // Select new node + selectNode(result); + } finally { + createUnsaved = false; + } + + return result; + } + + public <E extends IdDto> ObserveNode addOpenable(ObserveNode parentNode, E bean) { + + ReferenceBinderEngine referenceBinderEngine = ObserveSwingApplicationContext.get().getReferenceBinderEngine(); + ReferentialLocale referentialLocale = ObserveSwingApplicationContext.get().getDecoratorService().getReferentialLocale(); + if (bean instanceof TripSeineDto) { + + DataReference<TripSeineDto> ref = referenceBinderEngine.transformDataDtoToReference(referentialLocale, (TripSeineDto) bean); + return addTripSeine(parentNode, ref); + + } else if (bean instanceof TripLonglineDto) { + + DataReference<TripLonglineDto> ref = referenceBinderEngine.transformDataDtoToReference(referentialLocale, (TripLonglineDto) bean); + return addTripLongline(parentNode, ref); + + } else if (bean instanceof RouteDto) { + + DataReference<RouteDto> ref = referenceBinderEngine.transformDataDtoToReference(referentialLocale, (RouteDto) bean); + return addRoute(parentNode, ref); + + } else if (bean instanceof ActivitySeineDto) { + + DataReference<ActivitySeineDto> ref = referenceBinderEngine.transformDataDtoToReference(referentialLocale, (ActivitySeineDto) bean); + return addActivitySeine(parentNode, ref); + + } else if (bean instanceof ActivityLonglineDto) { + + DataReference<ActivityLonglineDto> ref = referenceBinderEngine.transformDataDtoToReference(referentialLocale, (ActivityLonglineDto) bean); + return addActivityLongline(parentNode, ref); + + } + throw new IllegalStateException("Can not come here!"); + } + + public ObserveNode addTripSeine(ObserveNode parentNode, DataReference<TripSeineDto> bean) { + ProgramSeineNodeChildLoador loador = + getChildLoador(ProgramSeineNodeChildLoador.class); + ObserveNode result = loador.createNode(bean, dataProvider); + insertNode(parentNode, result); + return result; + } + + public ObserveNode addTripLongline(ObserveNode parentNode, DataReference<TripLonglineDto> bean) { + ProgramLonglineNodeChildLoador loador = + getChildLoador(ProgramLonglineNodeChildLoador.class); + ObserveNode result = loador.createNode(bean, dataProvider); + insertNode(parentNode, result); + return result; + } + + public ObserveNode addSimpleTrip(ObserveNode parentNode, DataReference<?> bean) { + ObserveNode result; + + if (bean.getType().isAssignableFrom(TripSeineDto.class)) { + + ProgramSeineNodeChildLoador loador = getChildLoador(ProgramSeineNodeChildLoador.class); + boolean addChilds = loador.isAddChilds(); + loador.setAddChilds(false); + try { + result = loador.createNode((DataReference<TripSeineDto>) bean, dataProvider); + insertNode(parentNode, result); + } finally { + loador.setAddChilds(addChilds); + } + } else { + + ProgramLonglineNodeChildLoador loador = getChildLoador(ProgramLonglineNodeChildLoador.class); + boolean addChilds = loador.isAddChilds(); + loador.setAddChilds(false); + try { + result = loador.createNode((DataReference<TripLonglineDto>) bean, dataProvider); + insertNode(parentNode, result); + } finally { + loador.setAddChilds(addChilds); + } + } + return result; + } + + public ObserveNode addRoute(ObserveNode parentNode, DataReference<RouteDto> bean) { + RoutesNodeChildLoador loador = + getChildLoador(RoutesNodeChildLoador.class); + ObserveNode result = loador.createNode(bean, dataProvider); + insertNode(parentNode, result); + return result; + } + + public ObserveNode addActivitySeine(ObserveNode parentNode, DataReference<ActivitySeineDto> bean) { + ActivitySeinesNodeChildLoador loador = + getChildLoador(ActivitySeinesNodeChildLoador.class); + ObserveNode result = loador.createNode(bean, dataProvider); + insertNode(parentNode, result); + return result; + } + + public ObserveNode addActivityLongline(ObserveNode parentNode, DataReference<ActivityLonglineDto> bean) { + ActivityLonglinesNodeChildLoador loador = + getChildLoador(ActivityLonglinesNodeChildLoador.class); + ObserveNode result = loador.createNode(bean, dataProvider); + insertNode(parentNode, result); + return result; + } + + public ObserveNode addFloatingObject(ObserveNode parentNode, DataReference<FloatingObjectDto> bean) { + ActivitySeineNodeChildLoador loador = + getChildLoador(ActivitySeineNodeChildLoador.class); + ObserveNode result = loador.createNode(bean, dataProvider); + insertNode(parentNode, result); + return result; + } + + public ObserveNode addSetSeine(ObserveNode parentNode, DataReference<SetSeineDto> bean) { + ActivitySeineNodeChildLoador loador = + getChildLoador(ActivitySeineNodeChildLoador.class); + ObserveNode result = loador.createSetNode(bean); + insertNode(parentNode, result); + return result; + } + + public ObserveNode addSetLongline(ObserveNode parentNode, DataReference<SetLonglineDto> bean) { + ActivityLonglineNodeChildLoador loador = + getChildLoador(ActivityLonglineNodeChildLoador.class); + ObserveNode result = loador.createSetNode(bean); + insertNode(parentNode, result); + return result; + } + + public ObserveNode addProgram(ReferentialReference<ProgramDto> bean) { + + Set<ReferentialReference<ProgramDto>> programs = getDataProvider().getDataSource().getReferentialReferences(ProgramDto.class); + List<ReferentialReference<ProgramDto>> data = Lists.newArrayList(programs); + int newIndex = 0; + if (CollectionUtils.isNotEmpty(data)) { + sortPrograms(data); +// Programs.sort(data); + newIndex = data.indexOf(bean); + } + RootNodeChildLoador loador = getChildLoador(RootNodeChildLoador.class); + ObserveNode result = loador.createNode(bean, dataProvider); + insertNode(getRootNode(), result, newIndex); + return result; + } + + public void removeProgram(String programId) { + ObserveNode rootNode = getRootNode(); + ObserveNode result = rootNode.getChild(programId, getBridge(), dataProvider); + Preconditions.checkNotNull(result, "Could not find program node with id: " + programId); + removeNode(result); + } + + public void updateProgram(ProgramDto bean) { + ObserveNode rootNode = getRootNode(); + ObserveNode result = rootNode.getChild(bean.getId(), getBridge(), dataProvider); + Preconditions.checkNotNull(result, "Could not find program node with id: " + bean.getId()); + reloadNode(result, false); + refreshNode(result, false); + } + + public ObserveNode addProgram(Set<ReferentialReference<ProgramDto>> existingPrograms, ReferentialReference<ProgramDto> bean) { + + List<ReferentialReference<ProgramDto>> data = Lists.newArrayList(existingPrograms); + data.add(bean); + int newIndex = 0; + if (CollectionUtils.isNotEmpty(data)) { + sortPrograms(data); + newIndex = data.indexOf(bean); + } + RootNodeChildLoador loador = getChildLoador(RootNodeChildLoador.class); + ObserveNode result = loador.createNode(bean, dataProvider); + insertNode(getRootNode(), result, newIndex); + return result; + } + + public void removeTrip(ReferentialReference<ProgramDto> program, DataReference trip) { + + ObserveNode rootNode = getRootNode(); + ObserveNode programNode = rootNode.getChild(program.getId(), getBridge(), dataProvider); + Preconditions.checkNotNull(programNode, "Could not find program node with id: " + program); + ObserveNode tripNode = programNode.getChild(trip.getId(), getBridge(), dataProvider); + Preconditions.checkNotNull(tripNode, "Could not find program node with id: " + trip); + removeNode(tripNode); + + if (programNode.isLeaf()) { + removeProgram(program.getId()); + } + } + + public void reloadSelectedNode(boolean refreshFromParent, boolean refreshChilds) { + ObserveNode node = getSelectedNode(); + ((AbstrctReferenceNodeSupport) node).setReloadEntity(true); + + if (refreshFromParent) { + node = node.getParent(); + } + refreshNode(node, refreshChilds); + } + + public void reloadNode(ObserveNode node, boolean refreshChilds) { + ((AbstrctReferenceNodeSupport) node).setReloadEntity(true); + refreshNode(node, refreshChilds); + } + + public boolean isCreateUnsaved() { + return createUnsaved; + } + + @Override + protected ObserveDataProvider getDataProvider() { + ObserveDataProvider provider = (ObserveDataProvider) super.getDataProvider(); + if (provider == null) { + ObserveSwingDataSource source = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); + if (source != null) { + provider = new ObserveDataProvider(source); + setDataProvider(provider); + } + } + return provider; + } + + @Override + protected ObserveTreeBridge getBridge() { + return (ObserveTreeBridge) super.getBridge(); + } + + void setDataSource(ObserveSwingDataSource source) { + NavDataProvider provider = null; + if (source != null) { + provider = new ObserveDataProvider(source); + } + setDataProvider(provider); + } + + public void reloadNodeSubTree(ObserveNode node, boolean expandNode) { + Preconditions.checkNotNull(node, "node is null, we can not reload its structure"); + ObserveTreeBridge bridge = getBridge(); + + // 1. Let's clear node structure + while (node.getChildCount() > 0) { + removeNode(node.getFirstChild()); + } + + // 2. We add the node and its parent to the select path in order to force the call to the child loadors when populating the node. + // see fr.ird.observe.application.swing.ui.tree.ObserveTreeBridge.canLoadChild + bridge.setPathToSelect(node.getId(), node.getParent().getId()); + + try { + + // 3. Let's re-generate node's children by populating the node : this will call the child loaders. + node.populateNode(bridge, getDataProvider(), true); + + } finally { + // Clean the path to select + bridge.setPathToSelect(); + } + + if (expandNode) { + + // Fix bug (if no child in parent node, it will not expand...) + getUI().fireTreeExpanded(new TreePath(node.getPath())); + + } + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ProgramLonglineNode.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ProgramLonglineNode.java new file mode 100644 index 0000000..e7d21bb --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ProgramLonglineNode.java @@ -0,0 +1,57 @@ +package fr.ird.observe.application.swing.ui.tree; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.constants.GearType; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.service.ReferentialService; +import fr.ird.observe.application.swing.ui.tree.loadors.ProgramLonglineNodeChildLoador; + +/** + * Created on 4/9/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 4.0 + */ +public class ProgramLonglineNode extends ReferentialReferenceNodeSupport<ProgramDto> { + + private static final long serialVersionUID = 1L; + + public ProgramLonglineNode(ReferentialReference<ProgramDto> entity) { + super(ProgramDto.class, + entity, + ((GearType) entity.getPropertyValue(ProgramDto.PROPERTY_GEAR_TYPE)).name(), + ObserveTreeHelper.getChildLoador(ProgramLonglineNodeChildLoador.class)); + // FIXME kmorin 20151012 pkoi refaire un setEntity alors qu'il est fait dans le super ? + setEntity(entity); + } + + @Override + protected ReferentialReference<ProgramDto> fetchEntity() { + ReferentialService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newReferentialService(); + ReferentialReference<ProgramDto> referenceDto = service.loadReference(ProgramDto.class, getId()); + return referenceDto; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ProgramSeineNode.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ProgramSeineNode.java new file mode 100644 index 0000000..01e79b4 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ProgramSeineNode.java @@ -0,0 +1,56 @@ +package fr.ird.observe.application.swing.ui.tree; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.constants.GearType; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.services.service.ReferentialService; +import fr.ird.observe.application.swing.ui.tree.loadors.ProgramSeineNodeChildLoador; + +/** + * Created on 4/9/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 4.0 + */ +public class ProgramSeineNode extends ReferentialReferenceNodeSupport<ProgramDto> { + + private static final long serialVersionUID = 1L; + + public ProgramSeineNode(ReferentialReference<ProgramDto> entity) { + super(ProgramDto.class, + entity, + ((GearType) entity.getPropertyValue(ProgramDto.PROPERTY_GEAR_TYPE)).name(), + ObserveTreeHelper.getChildLoador(ProgramSeineNodeChildLoador.class)); + } + + @Override + protected ReferentialReference<ProgramDto> fetchEntity() { + ReferentialService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newReferentialService(); + ReferentialReference<ProgramDto> referenceDto = service.loadReference(ProgramDto.class, getId()); + return referenceDto; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ReferentialReferenceNodeSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ReferentialReferenceNodeSupport.java new file mode 100644 index 0000000..59ae9f2 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/ReferentialReferenceNodeSupport.java @@ -0,0 +1,84 @@ +package fr.ird.observe.application.swing.ui.tree; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.tree.loadors.AbstractNodeChildLoador; +import jaxx.runtime.swing.nav.NavBridge; +import jaxx.runtime.swing.nav.NavDataProvider; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.tree.DefaultTreeModel; + +/** + * Created on 4/9/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 4.0 + */ +public abstract class ReferentialReferenceNodeSupport<E extends ReferentialDto> extends AbstrctReferenceNodeSupport<E, ReferentialReference<E>> { + + /** Logger. */ + private static final Log log = LogFactory.getLog(ReferentialReferenceNodeSupport.class); + + private static final long serialVersionUID = 1L; + + protected ReferentialReferenceNodeSupport(Class<E> internalClass, ReferentialReference<E> entity) { + super(internalClass, entity, null); + } + + protected ReferentialReferenceNodeSupport(Class<E> type, ReferentialReference<E> entity, AbstractNodeChildLoador<?, ?> childLoador) { + super(type, entity, null, childLoador); + } + + protected ReferentialReferenceNodeSupport(Class<E> type, ReferentialReference<E> entity, String context, AbstractNodeChildLoador<?, ?> childLoador) { + super(type, entity, context, childLoador); + } + + @Override + public void populateNode(NavBridge<DefaultTreeModel, ObserveNode> bridge, + NavDataProvider provider, + boolean populateChilds) { + + + try { + super.populateNode(bridge, provider, populateChilds); + } finally { + reloadEntity = false; + } + + if (provider != null && id != null) { + + if (entity == null) { + + loadEntity((ObserveDataProvider) provider); + + } + + } + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/RouteSeineNode.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/RouteSeineNode.java new file mode 100644 index 0000000..52ae005 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/RouteSeineNode.java @@ -0,0 +1,50 @@ +package fr.ird.observe.application.swing.ui.tree; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.services.service.seine.RouteService; + +/** + * Created on 4/9/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 4.0 + */ +public class RouteSeineNode extends DataReferenceNodeSupport<RouteDto> { + + private static final long serialVersionUID = 1L; + + public RouteSeineNode(DataReference<RouteDto> entity) { + super(RouteDto.class, entity); + } + + @Override + protected DataReference<RouteDto> fetchEntity() { + RouteService routeService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newRouteService(); + DataReference<RouteDto> referenceDto = routeService.loadReferenceToRead(getId()); + return referenceDto; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/SetLonglineNode.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/SetLonglineNode.java new file mode 100644 index 0000000..278c5b1 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/SetLonglineNode.java @@ -0,0 +1,52 @@ +package fr.ird.observe.application.swing.ui.tree; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.longline.SetLonglineDto; +import fr.ird.observe.services.service.longline.SetLonglineService; +import fr.ird.observe.application.swing.ui.tree.loadors.SetLonglineNodeChildLoador; + +/** + * Created on 4/9/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 4.0 + */ +public class SetLonglineNode extends DataReferenceNodeSupport<SetLonglineDto> { + + private static final long serialVersionUID = 1L; + + public SetLonglineNode(DataReference<SetLonglineDto> entity) { + super(SetLonglineDto.class, entity, ObserveTreeHelper.getChildLoador(SetLonglineNodeChildLoador.class)); + } + + @Override + protected DataReference<SetLonglineDto> fetchEntity() { + SetLonglineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newSetLonglineService(); + DataReference<SetLonglineDto> referenceDto = service.loadReferenceToRead(getId()); + return referenceDto; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/SetSeineNode.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/SetSeineNode.java new file mode 100644 index 0000000..3e11639 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/SetSeineNode.java @@ -0,0 +1,52 @@ +package fr.ird.observe.application.swing.ui.tree; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.seine.SetSeineDto; +import fr.ird.observe.services.service.seine.SetSeineService; +import fr.ird.observe.application.swing.ui.tree.loadors.SetSeineNodeChildLoador; + +/** + * Created on 4/9/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 4.0 + */ +public class SetSeineNode extends DataReferenceNodeSupport<SetSeineDto> { + + private static final long serialVersionUID = 1L; + + public SetSeineNode(DataReference<SetSeineDto> entity) { + super(SetSeineDto.class, entity, ObserveTreeHelper.getChildLoador(SetSeineNodeChildLoador.class)); + } + + @Override + protected DataReference<SetSeineDto> fetchEntity() { + SetSeineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newSetSeineService(); + DataReference<SetSeineDto> referenceDto = service.loadReferenceToRead(getId()); + return referenceDto; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/TripLonglineNode.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/TripLonglineNode.java new file mode 100644 index 0000000..7a5c966 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/TripLonglineNode.java @@ -0,0 +1,51 @@ +package fr.ird.observe.application.swing.ui.tree; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.service.longline.TripLonglineService; + +/** + * Created on 4/9/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 4.0 + */ +public class TripLonglineNode extends DataReferenceNodeSupport<TripLonglineDto> { + + private static final long serialVersionUID = 1L; + + public TripLonglineNode(DataReference<TripLonglineDto> entity) { + super(TripLonglineDto.class, entity); + } + + @Override + protected DataReference<TripLonglineDto> fetchEntity() { + TripLonglineService tripLonglineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripLonglineService(); + DataReference<TripLonglineDto> referenceDto = tripLonglineService.loadReferenceToRead(getId()); + return referenceDto; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/TripSeineNode.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/TripSeineNode.java new file mode 100644 index 0000000..2eb21c6 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/TripSeineNode.java @@ -0,0 +1,51 @@ +package fr.ird.observe.application.swing.ui.tree; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.services.service.seine.TripSeineService; + +/** + * Created on 4/9/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 4.0 + */ +public class TripSeineNode extends DataReferenceNodeSupport<TripSeineDto> { + + private static final long serialVersionUID = 1L; + + public TripSeineNode(DataReference<TripSeineDto> entity) { + super(TripSeineDto.class, entity); + } + + + @Override + protected DataReference<TripSeineDto> fetchEntity() { + TripSeineService tripSeineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripSeineService(); + DataReference<TripSeineDto> referenceDto = tripSeineService.loadReferenceToRead(getId()); + return referenceDto; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/actions/ChangeActivityRouteActionListener.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/actions/ChangeActivityRouteActionListener.java new file mode 100644 index 0000000..ad41752 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/actions/ChangeActivityRouteActionListener.java @@ -0,0 +1,89 @@ +package fr.ird.observe.application.swing.ui.tree.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + + +import fr.ird.observe.application.swing.ObserveOpenDataManager; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.services.service.seine.ActivitySeineService; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Created on 1/9/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.11 + */ +public class ChangeActivityRouteActionListener extends NodeChangeActionListener { + + /** Logger. */ + private static final Log log = LogFactory.getLog(ChangeActivityRouteActionListener.class); + + public ChangeActivityRouteActionListener(ObserveTreeHelper treeHelper, + ObserveSwingDataSource dataSource, + String activityId, + String routeId) { + super(treeHelper, dataSource, activityId, routeId); + } + + @Override + protected void closeNode(String activityId) { + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ObserveOpenDataManager openDataManager = applicationContext.getOpenDataManager(); + + if (openDataManager.isOpenActivitySeine(activityId)) { + openDataManager.closeActivitySeine(activityId); + } + } + + @Override + protected ObserveNode getParentNode(ObserveNode node) { + return node.getParent().getParent(); + } + + @Override + protected ObserveNode getNewParentNode(ObserveNode grandParentNode, String parentNodeId) { + ObserveNode routeNode = getTreeHelper().getChild(grandParentNode, parentNodeId); + String activitiesNodeId = DecoratorService.getPropertyLabel(ObserveTreeHelper.TREE_NODE_PREFIX, + RouteDto.PROPERTY_ACTIVITY_SEINE); + ObserveNode activities = getTreeHelper().getChild(routeNode, activitiesNodeId); + return activities; + } + + @Override + protected int moveNodeToParent(String nodeId, String parentNodeId, String oldParentNodeId) { + int position; + + ActivitySeineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivitySeineService(); + position = service.moveActivitySeineToRoute(nodeId, parentNodeId); + + return position; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/actions/ChangeActivityTripActionListener.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/actions/ChangeActivityTripActionListener.java new file mode 100644 index 0000000..56bd4cf --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/actions/ChangeActivityTripActionListener.java @@ -0,0 +1,91 @@ +package fr.ird.observe.application.swing.ui.tree.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + + +import fr.ird.observe.application.swing.ObserveOpenDataManager; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.service.longline.ActivityLonglineService; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Created on 1/9/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.11 + */ +public class ChangeActivityTripActionListener extends NodeChangeActionListener { + + /** Logger. */ + private static final Log log = LogFactory.getLog(ChangeActivityTripActionListener.class); + + public ChangeActivityTripActionListener(ObserveTreeHelper treeHelper, + ObserveSwingDataSource dataSource, + String activityId, + String tripLonglineId) { + super(treeHelper, dataSource, activityId, tripLonglineId); + } + + @Override + protected void closeNode(String activityId) { + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ObserveOpenDataManager openDataManager = applicationContext.getOpenDataManager(); + + if (openDataManager.isOpenActivityLongline(activityId)) { + openDataManager.closeActivityLongline(activityId); + } + } + + @Override + protected ObserveNode getParentNode(ObserveNode node) { + return node.getParent().getParent(); + } + + @Override + protected ObserveNode getNewParentNode(ObserveNode grandParentNode, String parentNodeId) { + ObserveNode tripLonglineNode = getTreeHelper().getChild(grandParentNode, parentNodeId); + String activitiesNodeId = DecoratorService.getPropertyLabel(ObserveTreeHelper.TREE_NODE_PREFIX, + TripLonglineDto.PROPERTY_ACTIVITY_LONGLINE); + ObserveNode activities = getTreeHelper().getChild(tripLonglineNode, activitiesNodeId); + return activities; + } + + @Override + protected int moveNodeToParent(String nodeId, String parentNodeId, String oldParentNodeId) { + int position; + + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + + ActivityLonglineService service = applicationContext.getMainDataSourceServicesProvider().newActivityLonglineService(); + position = service.moveActivityLonglineToTripLongline(nodeId, parentNodeId); + + return position; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/actions/ChangeRouteTripActionListener.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/actions/ChangeRouteTripActionListener.java new file mode 100644 index 0000000..9777254 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/actions/ChangeRouteTripActionListener.java @@ -0,0 +1,88 @@ +package fr.ird.observe.application.swing.ui.tree.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + + +import fr.ird.observe.application.swing.ObserveOpenDataManager; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.services.service.seine.RouteService; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Created on 1/9/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.11 + */ +public class ChangeRouteTripActionListener extends NodeChangeActionListener { + + /** Logger. */ + private static final Log log = LogFactory.getLog(ChangeRouteTripActionListener.class); + + public ChangeRouteTripActionListener(ObserveTreeHelper treeHelper, + ObserveSwingDataSource dataSource, + String routeId, + String tripId) { + super(treeHelper, dataSource, routeId, tripId); + } + + @Override + protected void closeNode(String routeId) { + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ObserveOpenDataManager openDataManager = applicationContext.getOpenDataManager(); + + if (openDataManager.isOpenRoute(routeId)) { + openDataManager.closeRoute(routeId); + } + } + + @Override + protected ObserveNode getParentNode(ObserveNode node) { + return node.getParent().getParent(); + } + + @Override + protected ObserveNode getNewParentNode(ObserveNode grandParentNode, String parentNodeId) { + ObserveNode tripNode = getTreeHelper().getChild(grandParentNode, parentNodeId); + String routesNodeId = DecoratorService.getPropertyLabel(ObserveTreeHelper.TREE_NODE_PREFIX, + TripSeineDto.PROPERTY_ROUTE); + ObserveNode routesNode = getTreeHelper().getChild(tripNode, routesNodeId); + return routesNode; + } + + @Override + protected int moveNodeToParent(String nodeId, String parentNodeId, String oldParentNodeId) { + int position; + + RouteService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newRouteService(); + position = service.moveRouteToTripSeine(nodeId, parentNodeId); + + return position; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/actions/ChangeTripProgramActionListener.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/actions/ChangeTripProgramActionListener.java new file mode 100644 index 0000000..e395039 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/actions/ChangeTripProgramActionListener.java @@ -0,0 +1,95 @@ +package fr.ird.observe.application.swing.ui.tree.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + + +import fr.ird.observe.application.swing.ObserveOpenDataManager; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.ObserveServicesProvider; +import fr.ird.observe.services.dto.IdDtos; +import fr.ird.observe.services.service.longline.TripLonglineService; +import fr.ird.observe.services.service.seine.TripSeineService; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +/** + * Created on 1/9/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.11 + */ +public class ChangeTripProgramActionListener extends NodeChangeActionListener { + + /** Logger. */ + private static final Log log = LogFactory.getLog(ChangeTripProgramActionListener.class); + + public ChangeTripProgramActionListener(ObserveTreeHelper treeHelper, + ObserveSwingDataSource dataSource, + String tripId, + String programId) { + super(treeHelper, dataSource, tripId, programId); + } + + @Override + protected void closeNode(String tripId) { + // Don't do anything : trip should stay open when being transferred + } + + @Override + protected ObserveNode getParentNode(ObserveNode node) { + return node.getParent(); + } + + @Override + protected ObserveNode getNewParentNode(ObserveNode grandParentNode, String parentNodeId) { + return getTreeHelper().getChild(grandParentNode, parentNodeId); + } + + @Override + protected int moveNodeToParent(String nodeId, String parentNodeId, String oldParentNodeId) { + int position; + + ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); + ObserveServicesProvider servicesProvider = applicationContext.getMainDataSourceServicesProvider(); + if (IdDtos.isTripLonglineId(nodeId)) { + TripLonglineService service = servicesProvider.newTripLonglineService(); + position = service.moveTripLonglineToProgram(nodeId, parentNodeId); + + } else { + TripSeineService service = servicesProvider.newTripSeineService(); + position = service.moveTripSeineToProgram(nodeId, parentNodeId); + } + + // Close old program and open new program + ObserveOpenDataManager openDataManager = applicationContext.getOpenDataManager(); + if (openDataManager.isOpen(nodeId)) { + openDataManager.closeProgram(oldParentNodeId); + openDataManager.openProgram(parentNodeId); + } + + return position; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/actions/NodeChangeActionListener.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/actions/NodeChangeActionListener.java new file mode 100644 index 0000000..9217ff3 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/actions/NodeChangeActionListener.java @@ -0,0 +1,107 @@ +package fr.ird.observe.application.swing.ui.tree.actions; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + + +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + +/** + * Created on 1/9/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.11 + */ +public abstract class NodeChangeActionListener implements ActionListener { + + /** Logger. */ + private static final Log log = LogFactory.getLog(NodeChangeActionListener.class); + + private final String nodeId; + + private final String parentNodeId; + + private final ObserveTreeHelper treeHelper; + + private final ObserveSwingDataSource dataSource; + + public NodeChangeActionListener(ObserveTreeHelper treeHelper, + ObserveSwingDataSource dataSource, + String nodeId, + String parentNodeId) { + this.nodeId = nodeId; + this.parentNodeId = parentNodeId; + this.treeHelper = treeHelper; + this.dataSource = dataSource; + } + + @Override + public void actionPerformed(ActionEvent event) { + + ObserveNode node = treeHelper.getSelectedNode(); + ObserveNode oldParentNode = getParentNode(node); + ObserveNode grandParentNode = oldParentNode.getParent(); + ObserveNode newParentNode = getNewParentNode(grandParentNode, parentNodeId); + + closeNode(node.getId()); + + int position = moveNodeToParent(nodeId, parentNodeId, oldParentNode.getId()); + + treeHelper.selectNode(newParentNode); + + treeHelper.removeNode(node); + + ObserveNode newNode = treeHelper.getChild(newParentNode, nodeId); + + if (newNode == null) { + + // create it + if (log.isInfoEnabled()) { + log.info("Insert node: "); + } + treeHelper.insertNode(newParentNode, node, position); + newNode = node; + } + + treeHelper.selectNode(newNode); + + } + + protected ObserveTreeHelper getTreeHelper() { + return treeHelper; + } + + protected abstract void closeNode(String nodeId); + + protected abstract ObserveNode getParentNode(ObserveNode node); + + protected abstract ObserveNode getNewParentNode(ObserveNode grandParentNode, String parentNodeId); + + protected abstract int moveNodeToParent(String nodeId, String parentNodeId, String oldParentNodeId); +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/AbstractDataReferenceChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/AbstractDataReferenceChildLoador.java new file mode 100644 index 0000000..831d915 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/AbstractDataReferenceChildLoador.java @@ -0,0 +1,39 @@ +package fr.ird.observe.application.swing.ui.tree.loadors; + +/*- + * #%L + * ObServe :: Application Swing + * %% + * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.DataDto; +import fr.ird.observe.services.dto.DataReference; + +/** + * @author Kevin Morin (Code Lutin) + * @since x.x + */ +public abstract class AbstractDataReferenceChildLoador<O extends DataDto> extends AbstractNodeChildLoador<DataReference<O>, O> { + + private static final long serialVersionUID = 1L; + + protected AbstractDataReferenceChildLoador(Class<O> beanType) { + super(beanType); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/AbstractNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/AbstractNodeChildLoador.java new file mode 100644 index 0000000..f960806 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/AbstractNodeChildLoador.java @@ -0,0 +1,57 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.tree.loadors; + +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel; +import fr.ird.observe.application.swing.ui.tree.ObserveDataProvider; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import jaxx.runtime.swing.nav.NavDataProvider; +import jaxx.runtime.swing.nav.tree.NavTreeNodeChildLoador; + +/** + * Un object pour charger les fils d'un noeud. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public abstract class AbstractNodeChildLoador<T, O> extends NavTreeNodeChildLoador<T, O, ObserveNode> { + + private static final long serialVersionUID = 1L; + + protected AbstractNodeChildLoador(Class<O> beanType) { + super(beanType); + } + + protected ObserveSwingDataSource getDataSource(NavDataProvider dataProvider) { + ObserveDataProvider provider = (ObserveDataProvider) dataProvider; + ObserveSwingDataSource result = provider.getDataSource(); + return result; + } + + protected DataSelectionModel getSelectionModel(NavDataProvider dataProvider) { + ObserveDataProvider provider = (ObserveDataProvider) dataProvider; + DataSelectionModel result = provider.getSelectionModel(); + return result; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ActivityLonglineNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ActivityLonglineNodeChildLoador.java new file mode 100644 index 0000000..79ef810 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ActivityLonglineNodeChildLoador.java @@ -0,0 +1,121 @@ +package fr.ird.observe.application.swing.ui.tree.loadors; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.longline.ActivityLonglineDto; +import fr.ird.observe.services.dto.longline.ActivityLonglineEncounterDto; +import fr.ird.observe.services.dto.longline.ActivityLonglineSensorUsedDto; +import fr.ird.observe.services.dto.longline.SetLonglineDto; +import fr.ird.observe.application.swing.ui.tree.ActivityLonglineNode; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import fr.ird.observe.application.swing.ui.tree.SetLonglineNode; +import jaxx.runtime.swing.nav.NavDataProvider; +import jaxx.runtime.swing.nav.tree.NavTreeBridge; + +import java.util.ArrayList; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; + +/** + * Created on 8/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.7 + */ +public class ActivityLonglineNodeChildLoador extends AbstractNodeChildLoador<String, String> { + + private static final long serialVersionUID = 1L; + + static { + n("observe.tree.encounter"); + n("observe.tree.sensorUsed"); + n("observe.tree.setLongline"); + } + + public ActivityLonglineNodeChildLoador() { + super(String.class); + } + + @Override + public void loadChilds(NavTreeBridge<ObserveNode> model, + ObserveNode parentNode, + NavDataProvider dataProvider) throws Exception { + + ObserveNode containerNode = parentNode.getContainerNode(); + + if (containerNode == null) { + throw new IllegalStateException("Could not find containerNode of " + parentNode); + } + + { + + DataReference<ActivityLonglineDto> activityLonglineRef = ((ActivityLonglineNode) parentNode).getEntity(); + + DataReference<SetLonglineDto> setLonglineRef = (DataReference<SetLonglineDto>) activityLonglineRef.getPropertyValue(ActivityLonglineDto.PROPERTY_SET_LONGLINE); + if (setLonglineRef != null) { + + // si set present, ajout d'un noeud + ObserveNode child = createSetNode(setLonglineRef); + parentNode.add(child); + + } + } + + // ajout des autres fils avant la calée + super.loadChilds(model, parentNode, dataProvider); + + } + + @Override + public List<String> getData(Class<?> parentClass, + String parentId, + NavDataProvider dataService) { + + List<String> result = new ArrayList<>(); + result.add(ActivityLonglineEncounterDto.PROPERTY_ENCOUNTER); + result.add(ActivityLonglineSensorUsedDto.PROPERTY_SENSOR_USED); + return result; + + } + + @Override + public ObserveNode createNode(String data, NavDataProvider dataProvider) { + + ObserveNode result = ObserveTreeHelper.createStringNode(data); + return result; + + } + + public ObserveNode createSetNode(DataReference<SetLonglineDto> data) { + if (data == null) { + throw new NullPointerException("Ne peut pas ajouter un objet null"); + } + + ObserveNode child = new SetLonglineNode(data); + return child; + + } +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ActivityLonglinesNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ActivityLonglinesNodeChildLoador.java new file mode 100644 index 0000000..a701a4f --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ActivityLonglinesNodeChildLoador.java @@ -0,0 +1,73 @@ +package fr.ird.observe.application.swing.ui.tree.loadors; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.DataReferenceSet; +import fr.ird.observe.services.dto.longline.ActivityLonglineDto; +import fr.ird.observe.services.service.longline.ActivityLonglineService; +import fr.ird.observe.application.swing.ui.tree.ActivityLonglineNode; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import jaxx.runtime.swing.nav.NavDataProvider; + +import java.util.ArrayList; +import java.util.List; + +/** + * Created on 8/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.7 + */ +public class ActivityLonglinesNodeChildLoador extends AbstractDataReferenceChildLoador<ActivityLonglineDto> { + + private static final long serialVersionUID = 1L; + + public ActivityLonglinesNodeChildLoador() { + super(ActivityLonglineDto.class); + } + + @Override + public List<DataReference<ActivityLonglineDto>> getData(Class<?> parentClass, + String parentId, + NavDataProvider dataProvider) throws Exception { + + ActivityLonglineService activityLonglineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivityLonglineService(); + DataReferenceSet<ActivityLonglineDto> activityLonglineByTripLongline = activityLonglineService.getActivityLonglineByTripLongline(parentId); + + return new ArrayList<>(activityLonglineByTripLongline.getReferences()); + + } + + @Override + public ObserveNode createNode(DataReference<ActivityLonglineDto> data, NavDataProvider dataProvider) { + if (data == null) { + throw new NullPointerException("Ne peut pas ajouter un objet null"); + } + + ObserveNode result = new ActivityLonglineNode(data); + return result; + + } +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ActivitySeineNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ActivitySeineNodeChildLoador.java new file mode 100644 index 0000000..f8411b6 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ActivitySeineNodeChildLoador.java @@ -0,0 +1,125 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.tree.loadors; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.DataReferenceSet; +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.services.dto.seine.ActivitySeineObservedSystemDto; +import fr.ird.observe.services.dto.seine.FloatingObjectDto; +import fr.ird.observe.services.dto.seine.SetSeineDto; +import fr.ird.observe.services.service.seine.FloatingObjectService; +import fr.ird.observe.application.swing.ui.tree.ActivitySeineNode; +import fr.ird.observe.application.swing.ui.tree.FloatingObjectSeineNode; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import fr.ird.observe.application.swing.ui.tree.SetSeineNode; +import jaxx.runtime.swing.nav.NavDataProvider; +import jaxx.runtime.swing.nav.tree.NavTreeBridge; + +import java.util.ArrayList; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; + +/** + * Le chargeur des noeuds de marees. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ActivitySeineNodeChildLoador extends AbstractDataReferenceChildLoador<FloatingObjectDto> { + + private static final long serialVersionUID = 1L; + + static { + n("observe.common.observedSystem"); + n("observe.tree.setSeine"); + } + + public ActivitySeineNodeChildLoador() { + super(FloatingObjectDto.class); + } + + @Override + public void loadChilds(NavTreeBridge<ObserveNode> model, + ObserveNode parentNode, + NavDataProvider dataProvider) throws Exception { + + ObserveNode containerNode = parentNode.getContainerNode(); + + if (containerNode == null) { + throw new IllegalStateException( + "Could not find containerNode of " + parentNode); + } + + // Creation d'un node systeme observe + ObserveNode child = ObserveTreeHelper.createStringNode(ActivitySeineObservedSystemDto.PROPERTY_OBSERVED_SYSTEM); + + parentNode.add(child); + + DataReference<ActivitySeineDto> activitySeineRef = ((ActivitySeineNode) parentNode).getEntity(); + DataReference<SetSeineDto> setSeineRef = (DataReference<SetSeineDto>) activitySeineRef.getPropertyValue(ActivitySeineDto.PROPERTY_SET_SEINE); + if (setSeineRef != null) { + + // si set present, ajout d'un noeud + child = createSetNode(setSeineRef); + parentNode.add(child); + } + + // ajout des objets flottants + super.loadChilds(model, parentNode, dataProvider); + } + + public ObserveNode createSetNode(DataReference<SetSeineDto> data) { + if (data == null) { + throw new NullPointerException("Ne peut pas ajouter un objet null"); + } + + SetSeineNode child = new SetSeineNode(data); + return child; + + } + + @Override + public ObserveNode createNode(DataReference<FloatingObjectDto> data, NavDataProvider dataProvider) { + if (data == null) { + throw new NullPointerException("Ne peut pas ajouter un objet null"); + } + + FloatingObjectSeineNode result = new FloatingObjectSeineNode(data); + return result; + + } + + @Override + public List<DataReference<FloatingObjectDto>> getData(Class<?> parentClass, + String parentId, + NavDataProvider dataProvider) throws Exception { + + FloatingObjectService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newFloatingObjectService(); + DataReferenceSet<FloatingObjectDto> floatingObjectByActivitySeine = service.getFloatingObjectByActivitySeine(parentId); + return new ArrayList<>(floatingObjectByActivitySeine.getReferences()); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ActivitySeinesNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ActivitySeinesNodeChildLoador.java new file mode 100644 index 0000000..79cdce1 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ActivitySeinesNodeChildLoador.java @@ -0,0 +1,71 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.tree.loadors; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.DataReferenceSet; +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.services.service.seine.ActivitySeineService; +import fr.ird.observe.application.swing.ui.tree.ActivitySeineNode; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import jaxx.runtime.swing.nav.NavDataProvider; + +import java.util.ArrayList; +import java.util.List; + +/** + * Le chargeur des noeuds des activités d'une route. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ActivitySeinesNodeChildLoador extends AbstractDataReferenceChildLoador<ActivitySeineDto> { + + private static final long serialVersionUID = 1L; + + public ActivitySeinesNodeChildLoador() { + super(ActivitySeineDto.class); + } + + @Override + public List<DataReference<ActivitySeineDto>> getData(Class<?> parentClass, + String parentId, + NavDataProvider dataProvider) throws Exception { + + ActivitySeineService activitySeineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivitySeineService(); + DataReferenceSet<ActivitySeineDto> activitySeineStubByRoute = activitySeineService.getActivitySeineByRoute(parentId); + return new ArrayList<>(activitySeineStubByRoute.getReferences()); + + } + + @Override + public ObserveNode createNode(DataReference<ActivitySeineDto> data, NavDataProvider dataProvider) { + if (data == null) { + throw new NullPointerException("Ne peut pas ajouter un objet null"); + } + + ActivitySeineNode result = new ActivitySeineNode(data); + return result; + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/FloatingObjectNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/FloatingObjectNodeChildLoador.java new file mode 100644 index 0000000..858ef5d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/FloatingObjectNodeChildLoador.java @@ -0,0 +1,77 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.tree.loadors; + + +import fr.ird.observe.services.dto.seine.FloatingObjectDto; +import fr.ird.observe.services.dto.seine.FloatingObjectObservedSpeciesDto; +import fr.ird.observe.services.dto.seine.FloatingObjectSchoolEstimateDto; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import jaxx.runtime.swing.nav.NavDataProvider; + +import java.util.ArrayList; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; + +/** + * Le chargeur des noeuds de marees. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class FloatingObjectNodeChildLoador extends AbstractNodeChildLoador<String, String> { + + private static final long serialVersionUID = 1L; + + public FloatingObjectNodeChildLoador() { + super(String.class); + } + + static { + n("observe.tree.objectOperation"); + n("observe.tree.objectSchoolEstimate"); + n("observe.tree.objectObservedSpecies"); + } + + @Override + public List<String> getData(Class<?> parentClass, + String parentId, + NavDataProvider dataService) { + + List<String> result = new ArrayList<>(); + result.add(FloatingObjectDto.PROPERTY_OBJECT_OPERATION); + result.add(FloatingObjectSchoolEstimateDto.PROPERTY_OBJECT_SCHOOL_ESTIMATE); + result.add(FloatingObjectObservedSpeciesDto.PROPERTY_OBJECT_OBSERVED_SPECIES); + return result; + } + + @Override + public ObserveNode createNode(String data, NavDataProvider dataProvider) { + + ObserveNode result = ObserveTreeHelper.createStringNode(data); + return result; + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ProgramLonglineNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ProgramLonglineNodeChildLoador.java new file mode 100644 index 0000000..9ecf8f5 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ProgramLonglineNodeChildLoador.java @@ -0,0 +1,145 @@ +package fr.ird.observe.application.swing.ui.tree.loadors; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.DataReferenceSet; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.service.longline.TripLonglineService; +import fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import fr.ird.observe.application.swing.ui.tree.TripLonglineNode; +import jaxx.runtime.swing.nav.NavDataProvider; +import jaxx.runtime.swing.nav.tree.NavTreeBridge; + +import java.util.Collection; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; + +/** + * Created on 8/28/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.7 + */ +public class ProgramLonglineNodeChildLoador extends AbstractNodeChildLoador<DataReference<TripLonglineDto>, TripLonglineDto> { + + private static final long serialVersionUID = 1L; + + static { + n("observe.tree.gearUseFeaturesLongline"); + n("observe.tree.activityLongline"); + } + + public ProgramLonglineNodeChildLoador() { + super(TripLonglineDto.class); + } + + protected boolean addChilds; + + @Override + public void loadChilds(NavTreeBridge<ObserveNode> model, + ObserveNode parentNode, + NavDataProvider dataProvider) throws Exception { + + DataSelectionModel selectionModel = getSelectionModel(dataProvider); + addChilds = selectionModel == null; + + try { + super.loadChilds(model, parentNode, dataProvider); + } finally { + addChilds = true; + } + + } + + @Override + public List<DataReference<TripLonglineDto>> getData(Class<?> parentClass, + String parentId, + NavDataProvider dataProvider) throws Exception { + + DataSelectionModel selectionModel = getSelectionModel(dataProvider); + + List<DataReference<TripLonglineDto>> result; + + if (selectionModel != null) { + + result = Lists.newArrayList((Collection) selectionModel.getDatas(parentId)); + + } else { + + TripLonglineService tripLonglineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripLonglineService(); + DataReferenceSet<TripLonglineDto> tripLonglineByProgram = tripLonglineService.getTripLonglineByProgram(parentId); + + result = Lists.newArrayList(tripLonglineByProgram.getReferences()); + + } + + + return result; + } + + @Override + public ObserveNode createNode(DataReference<TripLonglineDto> data, NavDataProvider dataProvider) { + + if (data == null) { + throw new NullPointerException("Ne peut pas ajouter un objet null"); + } + + ObserveNode result = new TripLonglineNode(data); + + if (addChilds) { + + { + // Add gears + //FIXME + ObserveNode child = ObserveTreeHelper.createStringNode("gearUseFeaturesLongline"); + result.add(child); + } + + { + // Add activities + ObserveNode child = ObserveTreeHelper.createStringNode(TripLonglineDto.PROPERTY_ACTIVITY_LONGLINE, + ActivityLonglinesNodeChildLoador.class); + result.add(child); + } + + } + + return result; + + } + + public void setAddChilds(boolean addChilds) { + this.addChilds = addChilds; + } + + public boolean isAddChilds() { + return addChilds; + } +} + diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ProgramSeineNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ProgramSeineNodeChildLoador.java new file mode 100644 index 0000000..56d6386 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ProgramSeineNodeChildLoador.java @@ -0,0 +1,139 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.tree.loadors; + +import com.google.common.collect.Lists; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.DataReferenceSet; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.services.service.seine.TripSeineService; +import fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import fr.ird.observe.application.swing.ui.tree.TripSeineNode; +import jaxx.runtime.swing.nav.NavDataProvider; +import jaxx.runtime.swing.nav.tree.NavTreeBridge; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; + +/** + * Le chargeur des noeuds fils d'un program (les marees du programme). + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ProgramSeineNodeChildLoador extends AbstractNodeChildLoador<DataReference<TripSeineDto>, TripSeineDto> { + + private static final long serialVersionUID = 1L; + + static { + n("observe.tree.gearUseFeaturesSeine"); + n("observe.tree.route"); + } + + public ProgramSeineNodeChildLoador() { + super(TripSeineDto.class); + } + + protected boolean addChilds; + + @Override + public void loadChilds(NavTreeBridge<ObserveNode> model, + ObserveNode parentNode, + NavDataProvider dataProvider) throws Exception { + DataSelectionModel selectionModel = getSelectionModel(dataProvider); + addChilds = selectionModel == null; + + try { + super.loadChilds(model, parentNode, dataProvider); + } finally { + addChilds = true; + } + } + + @Override + public List<DataReference<TripSeineDto>> getData(Class<?> parentClass, + String parentId, + NavDataProvider dataProvider) throws Exception { + + DataSelectionModel selectionModel = getSelectionModel(dataProvider); + + List<DataReference<TripSeineDto>> result; + + if (selectionModel != null) { + + result = Lists.newArrayList((Collection) selectionModel.getDatas(parentId)); + + } else { + + TripSeineService tripSeineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripSeineService(); + DataReferenceSet<TripSeineDto> tripSeineByProgram = tripSeineService.getTripSeineByProgram(parentId); + + result = new ArrayList<>(tripSeineByProgram.getReferences()); + + } + return result; + + } + + @Override + public ObserveNode createNode(DataReference<TripSeineDto> data, NavDataProvider dataProvider) { + + if (data == null) { + throw new NullPointerException("Ne peut pas ajouter un objet null"); + } + + ObserveNode result = new TripSeineNode(data); + + if (addChilds) { + + { + // Add gears + ObserveNode child = ObserveTreeHelper.createStringNode("gearUseFeaturesSeine"); + result.add(child); + } + + { + // Add routes + ObserveNode child = ObserveTreeHelper.createStringNode(TripSeineDto.PROPERTY_ROUTE, RoutesNodeChildLoador.class); + result.add(child); + } + + } + + return result; + + } + + public boolean isAddChilds() { + return addChilds; + } + + public void setAddChilds(boolean addChilds) { + this.addChilds = addChilds; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ReferenceCommonNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ReferenceCommonNodeChildLoador.java new file mode 100644 index 0000000..310f372 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ReferenceCommonNodeChildLoador.java @@ -0,0 +1,95 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.tree.loadors; + + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialDtos; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import jaxx.runtime.swing.nav.NavDataProvider; + +import java.util.ArrayList; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; + +/** + * Le chargeur des noeuds du referentiel. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ReferenceCommonNodeChildLoador extends AbstractNodeChildLoador<Class, Class> { + + private static final long serialVersionUID = 1L; + + static { + + n("observe.tree.vesselSizeCategory"); + n("observe.tree.country"); + n("observe.tree.harbour"); + n("observe.tree.vesselType"); + n("observe.tree.vessel"); + n("observe.tree.speciesGroup"); + n("observe.tree.species"); + n("observe.tree.sex"); + n("observe.tree.fpaZone"); + n("observe.tree.speciesList"); + n("observe.tree.person"); + n("observe.tree.ocean"); + n("observe.tree.organism"); + n("observe.tree.lengthWeightParameter"); + n("observe.tree.program"); + n("observe.tree.gearCaracteristicType"); + n("observe.tree.gearCaracteristic"); + n("observe.tree.gear"); + + } + + public ReferenceCommonNodeChildLoador() { + super(Class.class); + } + + @Override + public List<Class> getData(Class<?> parentClass, String parentId, NavDataProvider dataProvider) { + + List<Class> result = new ArrayList<>(); + for (Class<? extends ReferentialDto> referenceCommonDto : ReferentialDtos.REFERENCE_COMMON_DTOS) { + result.add(referenceCommonDto); + } + UIHelper.sortReferentiel(result); + return result; + } + + @Override + public ObserveNode createNode(Class data, NavDataProvider dataProvider) { + + ObserveNode result = new ObserveNode( + data, + data.getSimpleName(), + null, + true + ); + return result; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ReferenceLonglineNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ReferenceLonglineNodeChildLoador.java new file mode 100644 index 0000000..8c4be10 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ReferenceLonglineNodeChildLoador.java @@ -0,0 +1,101 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.tree.loadors; + + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialDtos; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import jaxx.runtime.swing.nav.NavDataProvider; + +import java.util.ArrayList; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; + +/** + * Le chargeur des noeuds du referentiel. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ReferenceLonglineNodeChildLoador extends AbstractNodeChildLoador<Class, Class> { + + private static final long serialVersionUID = 1L; + + static { + n("observe.tree.baitHaulingStatus"); + n("observe.tree.baitSettingStatus"); + n("observe.tree.baitType"); + n("observe.tree.catchFateLongline"); + n("observe.tree.encounterType"); + n("observe.tree.healthness"); + n("observe.tree.hookPosition"); + n("observe.tree.hookSize"); + n("observe.tree.hookType"); + n("observe.tree.itemVerticalPosition"); + n("observe.tree.itemHorizontalPosition"); + n("observe.tree.lightsticksColor"); + n("observe.tree.lightsticksType"); + n("observe.tree.lineType"); + n("observe.tree.maturityStatus"); + n("observe.tree.mitigationType"); + n("observe.tree.sensorBrand"); + n("observe.tree.sensorDataFormat"); + n("observe.tree.sensorType"); + n("observe.tree.settingShape"); + n("observe.tree.sizeMeasureType"); + n("observe.tree.stomacFullness"); + n("observe.tree.tripType"); + n("observe.tree.vesselActivityLongline"); + n("observe.tree.weightMeasureType"); + + } + + public ReferenceLonglineNodeChildLoador() { + super(Class.class); + } + + @Override + public List<Class> getData(Class<?> parentClass, String parentId, NavDataProvider dataProvider) { + + List<Class> result = new ArrayList<>(); + for (Class<? extends ReferentialDto> referenceCommonDto : ReferentialDtos.REFERENCE_LONGLINE_DTOS) { + result.add(referenceCommonDto); + } + UIHelper.sortReferentiel(result); + return result; + } + + @Override + public ObserveNode createNode(Class data, NavDataProvider dataProvider) { + + ObserveNode result = new ObserveNode( + data, + data.getSimpleName(), + null, + true + ); + return result; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ReferenceSeineNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ReferenceSeineNodeChildLoador.java new file mode 100644 index 0000000..f31ddaf --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/ReferenceSeineNodeChildLoador.java @@ -0,0 +1,92 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.tree.loadors; + + +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialDtos; +import fr.ird.observe.application.swing.ui.UIHelper; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import jaxx.runtime.swing.nav.NavDataProvider; + +import java.util.ArrayList; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; + +/** + * Le chargeur des noeuds du referentiel. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ReferenceSeineNodeChildLoador extends AbstractNodeChildLoador<Class, Class> { + + private static final long serialVersionUID = 1L; + + static { + + n("observe.tree.vesselActivitySeine"); + n("observe.tree.surroundingActivity"); + n("observe.tree.reasonForNullSet"); + n("observe.tree.reasonForNoFishing"); + n("observe.tree.speciesFate"); + n("observe.tree.objectFate"); + n("observe.tree.weightCategory"); + n("observe.tree.detectionMode"); + n("observe.tree.transmittingBuoyOperation"); + n("observe.tree.objectOperation"); + n("observe.tree.reasonForDiscard"); + n("observe.tree.speciesStatus"); + n("observe.tree.observedSystem"); + n("observe.tree.transmittingBuoyType"); + n("observe.tree.objectType"); + n("observe.tree.wind"); + + } + + public ReferenceSeineNodeChildLoador() { + super(Class.class); + } + + @Override + public List<Class> getData(Class<?> parentClass, String parentId, NavDataProvider dataProvider) { + + List<Class> result = new ArrayList<>(); + for (Class<? extends ReferentialDto> referenceCommonDto : ReferentialDtos.REFERENCE_SEINE_DTOS) { + result.add(referenceCommonDto); + } + UIHelper.sortReferentiel(result); + return result; + } + + @Override + public ObserveNode createNode(Class data, NavDataProvider dataProvider) { + ObserveNode result = new ObserveNode( + data, + data.getSimpleName(), + null, + true + ); + return result; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/RootNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/RootNodeChildLoador.java new file mode 100644 index 0000000..74caa4a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/RootNodeChildLoador.java @@ -0,0 +1,160 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.tree.loadors; + +import com.google.common.collect.Lists; +import fr.ird.observe.services.dto.constants.GearType; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.ui.storage.tabs.DataSelectionModel; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import fr.ird.observe.application.swing.ui.tree.ProgramLonglineNode; +import fr.ird.observe.application.swing.ui.tree.ProgramSeineNode; +import jaxx.runtime.swing.nav.NavDataProvider; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Set; + +import static org.nuiton.i18n.I18n.n; + +/** + * Le chargeur des noeuds fils d'un program (les marees du programme). + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class RootNodeChildLoador extends AbstractNodeChildLoador<ReferentialReference<ProgramDto>, ProgramDto> { + + private static final long serialVersionUID = 1L; + + protected boolean addData; + + protected boolean addReferentiel; + + public RootNodeChildLoador() { + super(ProgramDto.class); + } + + public RootNodeChildLoador(boolean addData, boolean addReferentiel) { + this(); + this.addData = addData; + this.addReferentiel = addReferentiel; + } + + public void setAddData(boolean addData) { + this.addData = addData; + } + + public void setAddReferentiel(boolean addReferentiel) { + this.addReferentiel = addReferentiel; + } + + @Override + public List<ReferentialReference<ProgramDto>> getData(Class<?> parentClass, String parentId, NavDataProvider dataProvider) { + + DataSelectionModel selectionModel = getSelectionModel(dataProvider); + + List<ReferentialReference<ProgramDto>> data = Collections.emptyList(); + + if (addData) { + + if (selectionModel != null) { + data = Lists.newArrayList(selectionModel.getDatas().keySet()); + } else { + Set<ReferentialReference<ProgramDto>> referentialReferenceSet = getDataSource(dataProvider).getReferentialReferences(ProgramDto.class); + data = new ArrayList<>(referentialReferenceSet); + } + + ObserveTreeHelper.sortPrograms(data); + } + + return data; + + } + + @Override + public void addChildNodes(ObserveNode parentNode, List<ReferentialReference<ProgramDto>> datas, NavDataProvider dataProvider) { + super.addChildNodes(parentNode, datas, dataProvider); + if (addReferentiel) { + + { // ajout du referentiel commun + ObserveNode child = new ObserveNode( + String.class, + n("observe.tree.reference.common"), + ObserveTreeHelper.getChildLoador(ReferenceCommonNodeChildLoador.class), + true + ); + parentNode.add(child); + } + { // ajout du referentiel seine + ObserveNode child = new ObserveNode( + String.class, + n("observe.tree.reference.seine"), + ObserveTreeHelper.getChildLoador(ReferenceSeineNodeChildLoador.class), + true + ); + parentNode.add(child); + } + { // ajout du referentiel longline + ObserveNode child = new ObserveNode( + String.class, + n("observe.tree.reference.longline"), + ObserveTreeHelper.getChildLoador(ReferenceLonglineNodeChildLoador.class), + true + ); + parentNode.add(child); + } + + } + } + + @Override + public ObserveNode createNode(ReferentialReference<ProgramDto> data, NavDataProvider dataProvider) { + + GearType gearType = (GearType) data.getPropertyValue(ProgramDto.PROPERTY_GEAR_TYPE); + + ObserveNode result; + + switch (gearType) { + + case seine: + + result = new ProgramSeineNode(data); + break; + + case longline: + + result = new ProgramLonglineNode(data); + break; + + default: + throw new IllegalStateException("The program has a gearType " + gearType + " we can't deal with"); + + } + + return result; + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/RoutesNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/RoutesNodeChildLoador.java new file mode 100644 index 0000000..c4cd109 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/RoutesNodeChildLoador.java @@ -0,0 +1,86 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.tree.loadors; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.DataReferenceSet; +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.services.service.seine.RouteService; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import fr.ird.observe.application.swing.ui.tree.RouteSeineNode; +import jaxx.runtime.swing.nav.NavDataProvider; + +import java.util.ArrayList; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; + +/** + * Le chargeur des noeuds de routes d'une marée. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class RoutesNodeChildLoador extends AbstractDataReferenceChildLoador<RouteDto> { + + private static final long serialVersionUID = 1L; + + static { + n("observe.tree.activitySeine"); + } + + public RoutesNodeChildLoador() { + super(RouteDto.class); + } + + @Override + public List<DataReference<RouteDto>> getData(Class<?> parentClass, + String parentId, + NavDataProvider dataProvider) throws Exception { + + RouteService routeService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newRouteService(); + DataReferenceSet<RouteDto> routeByTripSeine = routeService.getRouteByTripSeine(parentId); + + return new ArrayList<>(routeByTripSeine.getReferences()); + } + + + + @Override + public ObserveNode createNode(DataReference<RouteDto> data, NavDataProvider dataProvider) { + + if (data == null) { + throw new NullPointerException("Ne peut pas ajouter un objet null"); + } + + ObserveNode result = new RouteSeineNode(data); + + // Creation d'un node activites + ObserveNode child = ObserveTreeHelper.createStringNode("activitySeine", ActivitySeinesNodeChildLoador.class); + result.add(child); + return result; + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/SetLonglineNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/SetLonglineNodeChildLoador.java new file mode 100644 index 0000000..c43731b --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/SetLonglineNodeChildLoador.java @@ -0,0 +1,79 @@ +package fr.ird.observe.application.swing.ui.tree.loadors; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + + +import fr.ird.observe.services.dto.longline.SetLonglineCatchDto; +import fr.ird.observe.services.dto.longline.SetLonglineTdrDto; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import jaxx.runtime.swing.nav.NavDataProvider; + +import java.util.ArrayList; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; + +/** + * Created on 8/30/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.7 + */ +public class SetLonglineNodeChildLoador extends AbstractNodeChildLoador<String, String> { + + private static final long serialVersionUID = 1L; + + static { + n("observe.tree.longlineGlobalComposition"); + n("observe.tree.longlineDetailComposition"); + n("observe.tree.catchLongline"); + n("observe.tree.tdr"); + } + + public SetLonglineNodeChildLoador() { + super(String.class); + } + + @Override + public List<String> getData(Class<?> parentClass, + String parentId, + NavDataProvider dataProvider) { + + List<String> result = new ArrayList<>(); + result.add("longlineGlobalComposition"); + result.add("longlineDetailComposition"); + result.add(SetLonglineCatchDto.PROPERTY_CATCH_LONGLINE); + result.add(SetLonglineTdrDto.PROPERTY_TDR); +// + return result; + } + + @Override + public ObserveNode createNode(String data, NavDataProvider dataProvider) { + + ObserveNode result = ObserveTreeHelper.createStringNode(data); + return result; + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/SetSeineNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/SetSeineNodeChildLoador.java new file mode 100644 index 0000000..93df389 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/loadors/SetSeineNodeChildLoador.java @@ -0,0 +1,85 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.tree.loadors; + + +import fr.ird.observe.services.dto.seine.SetSeineDto; +import fr.ird.observe.services.dto.seine.SetSeineNonTargetCatchDto; +import fr.ird.observe.services.dto.seine.SetSeineSchoolEstimateDto; +import fr.ird.observe.services.dto.seine.SetSeineTargetCatchDto; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import jaxx.runtime.swing.nav.NavDataProvider; + +import java.util.ArrayList; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; + +/** + * Le chargeur des noeuds de marees. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class SetSeineNodeChildLoador extends AbstractNodeChildLoador<String, String> { + + private static final long serialVersionUID = 1L; + + static { + n("observe.tree.schoolEstimate"); + n("observe.tree.targetCatch"); + n("observe.tree.targetDiscarded"); + n("observe.tree.targetSample"); + n("observe.tree.targetSampleCapture"); + n("observe.tree.nonTargetCatch"); + n("observe.tree.nonTargetSample"); + } + + public SetSeineNodeChildLoador() { + super(String.class); + } + + @Override + public List<String> getData(Class<?> parentClass, + String parentId, + NavDataProvider dataProvider) { + + List<String> result = new ArrayList<>(); + result.add(SetSeineSchoolEstimateDto.PROPERTY_SCHOOL_ESTIMATE); + result.add(SetSeineTargetCatchDto.PROPERTY_TARGET_CATCH); + result.add(SetSeineDto.PROPERTY_TARGET_DISCARDED); + result.add("targetSample"); + result.add(SetSeineDto.PROPERTY_TARGET_SAMPLE_CAPTURE); + result.add(SetSeineNonTargetCatchDto.PROPERTY_NON_TARGET_CATCH); + result.add("nonTargetSample"); + return result; + + } + + @Override + public ObserveNode createNode(String data, NavDataProvider dataProvider) { + + ObserveNode result = ObserveTreeHelper.createStringNode(data); + return result; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/menu/MoveActivityLonglineNodeMenuPopulator.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/menu/MoveActivityLonglineNodeMenuPopulator.java new file mode 100644 index 0000000..2918b24 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/menu/MoveActivityLonglineNodeMenuPopulator.java @@ -0,0 +1,85 @@ +package fr.ird.observe.application.swing.ui.tree.menu; + +/*- + * #%L + * ObServe :: Application Swing + * %% + * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.IdDtos; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import fr.ird.observe.application.swing.ui.tree.TripLonglineNode; +import fr.ird.observe.application.swing.ui.tree.actions.ChangeActivityTripActionListener; +import fr.ird.observe.application.swing.ui.tree.actions.NodeChangeActionListener; +import fr.ird.observe.application.swing.ui.util.DecoratedNodeEntity; +import fr.ird.observe.application.swing.decoration.decorators.DataReferenceDecorator; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Kevin Morin (Code Lutin) + * @since 5.0 + */ +public class MoveActivityLonglineNodeMenuPopulator extends MoveNodeMenuPopulator { + + @Override + public NodeChangeActionListener createChangeActionListener(ObserveTreeHelper treeHelper, + ObserveSwingDataSource dataSource, + String id, + String parentId) { + return new ChangeActivityTripActionListener(treeHelper, dataSource, id, parentId); + } + + @Override + public List<DecoratedNodeEntity> getPossibleParentNodes(ObserveNode activityLonglineNode, ObserveTreeHelper treeHelper) { + + // noeud de marée parent + ObserveNode parentNode = activityLonglineNode.getParent().getParent(); + + // noeud de route de la marée sans le parent actuel + List<DecoratedNodeEntity> possibleParents = new ArrayList<>(); + + // noeud du programme + ObserveNode programNode = parentNode.getParent(); + + DecoratorService decoratorService = treeHelper.getTreeCellRenderer().getDecoratorService(); + DataReferenceDecorator<TripLonglineDto> tripDecorator = decoratorService.getDataReferenceDecorator(TripLonglineDto.class); + + for (int i = 0, n = programNode.getChildCount(); i < n; i++) { + + TripLonglineNode tripNode = (TripLonglineNode) programNode.getChildAt(i); + String tripId = tripNode.getId(); + + // si le noeud de marée n'est pas le même que le parent actuel + // si le noeud est bien un noeud de marée longline + if (!parentNode.equals(tripNode) && IdDtos.isTripLonglineId(tripId)) { + + possibleParents.add(DecoratedNodeEntity.newDecoratedNodeEntity(tripNode, tripDecorator)); + + } + } + + return possibleParents; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/menu/MoveActivitySeineNodeMenuPopulator.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/menu/MoveActivitySeineNodeMenuPopulator.java new file mode 100644 index 0000000..3cd4936 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/menu/MoveActivitySeineNodeMenuPopulator.java @@ -0,0 +1,85 @@ +package fr.ird.observe.application.swing.ui.tree.menu; + +/*- + * #%L + * ObServe :: Application Swing + * %% + * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.IdDtos; +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import fr.ird.observe.application.swing.ui.tree.RouteSeineNode; +import fr.ird.observe.application.swing.ui.tree.actions.ChangeActivityRouteActionListener; +import fr.ird.observe.application.swing.ui.tree.actions.NodeChangeActionListener; +import fr.ird.observe.application.swing.ui.util.DecoratedNodeEntity; +import fr.ird.observe.application.swing.decoration.decorators.DataReferenceDecorator; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Kevin Morin (Code Lutin) + * @since 5.0 + */ +public class MoveActivitySeineNodeMenuPopulator extends MoveNodeMenuPopulator { + + @Override + public NodeChangeActionListener createChangeActionListener(ObserveTreeHelper treeHelper, + ObserveSwingDataSource dataSource, + String id, + String parentId) { + return new ChangeActivityRouteActionListener(treeHelper, dataSource, id, parentId); + } + + @Override + public List<DecoratedNodeEntity> getPossibleParentNodes(ObserveNode activitySeineNode, ObserveTreeHelper treeHelper) { + + // noeud de route parent + ObserveNode parentNode = activitySeineNode.getParent().getParent(); + + // noeud de route de la marée sans le parent actuel + List<DecoratedNodeEntity> possibleParents = new ArrayList<>(); + + // noeud des routes de la marée + ObserveNode routesNode = parentNode.getParent(); + + DecoratorService decoratorService = treeHelper.getTreeCellRenderer().getDecoratorService(); + DataReferenceDecorator<RouteDto> routeDecorator = decoratorService.getDataReferenceDecorator(RouteDto.class); + + for (int i = 0, n = routesNode.getChildCount(); i < n; i++) { + + RouteSeineNode routeNode = (RouteSeineNode) routesNode.getChildAt(i); + String routeId = routeNode.getId(); + + // si le noeud de marée n'est pas le même que le parent actuel + // si le noeud est bien un noeud de marée seine + if (!parentNode.equals(routeNode) && IdDtos.isRouteId(routeId)) { + + possibleParents.add(DecoratedNodeEntity.newDecoratedNodeEntity(routeNode, routeDecorator)); + + } + } + + return possibleParents; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/menu/MoveNodeMenuPopulator.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/menu/MoveNodeMenuPopulator.java new file mode 100644 index 0000000..9db1c7c --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/menu/MoveNodeMenuPopulator.java @@ -0,0 +1,62 @@ +package fr.ird.observe.application.swing.ui.tree.menu; + +/*- + * #%L + * ObServe :: Application Swing + * %% + * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import fr.ird.observe.application.swing.ui.tree.actions.NodeChangeActionListener; +import fr.ird.observe.application.swing.ui.util.DecoratedNodeEntity; + +import java.util.List; + +/** + * Objets pour créer les items du menu déplacer dans le menu contextuel de l'arbre + * + * @author Kevin Morin (Code Lutin) + * @since 5.0 + */ +public abstract class MoveNodeMenuPopulator { + + /** + * Crée une action pour déplacer le noeud quand on sélectionne le menu du nouveau parent + * @param treeHelper + * @param dataSource + * @param id + * @param parentId + * @return + */ + public abstract NodeChangeActionListener createChangeActionListener(ObserveTreeHelper treeHelper, + ObserveSwingDataSource dataSource, + String id, + String parentId); + + /** + * Récupère les parents dans lesquels on peut déplacer le noeud sélectionné + * @param node le noeud sélectionné + * @param treeHelper le treehelper + * @return une liste contenant les ids et les libellés des noeuds + */ + public abstract List<DecoratedNodeEntity> getPossibleParentNodes(ObserveNode node, ObserveTreeHelper treeHelper); + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/menu/MoveRouteNodeMenuPopulator.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/menu/MoveRouteNodeMenuPopulator.java new file mode 100644 index 0000000..eff9dd8 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/menu/MoveRouteNodeMenuPopulator.java @@ -0,0 +1,85 @@ +package fr.ird.observe.application.swing.ui.tree.menu; + +/*- + * #%L + * ObServe :: Application Swing + * %% + * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.IdDtos; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import fr.ird.observe.application.swing.ui.tree.TripSeineNode; +import fr.ird.observe.application.swing.ui.tree.actions.ChangeRouteTripActionListener; +import fr.ird.observe.application.swing.ui.tree.actions.NodeChangeActionListener; +import fr.ird.observe.application.swing.ui.util.DecoratedNodeEntity; +import fr.ird.observe.application.swing.decoration.decorators.DataReferenceDecorator; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Kevin Morin (Code Lutin) + * @since 5.0 + */ +public class MoveRouteNodeMenuPopulator extends MoveNodeMenuPopulator { + + @Override + public NodeChangeActionListener createChangeActionListener(ObserveTreeHelper treeHelper, + ObserveSwingDataSource dataSource, + String id, + String parentId) { + return new ChangeRouteTripActionListener(treeHelper, dataSource, id, parentId); + } + + @Override + public List<DecoratedNodeEntity> getPossibleParentNodes(ObserveNode routeNode, ObserveTreeHelper treeHelper) { + + // noeud de marée parent + ObserveNode parentNode = routeNode.getParent().getParent(); + + // noeud de marée du programme sans le parent actuel + List<DecoratedNodeEntity> possibleParents = new ArrayList<>(); + + // noeud du programme + ObserveNode programNode = parentNode.getParent(); + + DecoratorService decoratorService = treeHelper.getTreeCellRenderer().getDecoratorService(); + DataReferenceDecorator<TripSeineDto> tripDecorator = decoratorService.getDataReferenceDecorator(TripSeineDto.class); + + for (int i = 0, n = programNode.getChildCount(); i < n; i++) { + + TripSeineNode tripNode = (TripSeineNode) programNode.getChildAt(i); + String tripId = tripNode.getId(); + + // si le noeud de marée n'est pas le même que le parent actuel + // si le noeud est bien un noeud de marée seine + if (!parentNode.equals(tripNode) && IdDtos.isTripSeineId(tripId)) { + + possibleParents.add(DecoratedNodeEntity.newDecoratedNodeEntity(tripNode, tripDecorator)); + + } + } + + return possibleParents; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/menu/MoveTripNodeMenuPopulator.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/menu/MoveTripNodeMenuPopulator.java new file mode 100644 index 0000000..bcb6869 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/tree/menu/MoveTripNodeMenuPopulator.java @@ -0,0 +1,105 @@ +package fr.ird.observe.application.swing.ui.tree.menu; + +/*- + * #%L + * ObServe :: Application Swing + * %% + * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.IdDtos; +import fr.ird.observe.services.dto.constants.GearType; +import fr.ird.observe.services.dto.referential.ProgramDto; +import fr.ird.observe.application.swing.ui.tree.ObserveNode; +import fr.ird.observe.application.swing.ui.tree.ObserveTreeHelper; +import fr.ird.observe.application.swing.ui.tree.ProgramLonglineNode; +import fr.ird.observe.application.swing.ui.tree.ProgramSeineNode; +import fr.ird.observe.application.swing.ui.tree.actions.ChangeTripProgramActionListener; +import fr.ird.observe.application.swing.ui.tree.actions.NodeChangeActionListener; +import fr.ird.observe.application.swing.ui.util.DecoratedNodeEntity; +import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author Kevin Morin (Code Lutin) + * @since 5.0 + */ +public class MoveTripNodeMenuPopulator extends MoveNodeMenuPopulator { + + @Override + public NodeChangeActionListener createChangeActionListener(ObserveTreeHelper treeHelper, + ObserveSwingDataSource dataSource, + String id, + String parentId) { + return new ChangeTripProgramActionListener(treeHelper, dataSource, id, parentId); + } + + @Override + public List<DecoratedNodeEntity> getPossibleParentNodes(ObserveNode tripNode, ObserveTreeHelper treeHelper) { + + // noeud du programme parent + ObserveNode parentNode = tripNode.getParent(); + + // programmes du même type que le noeud de marée, sans le parent actuel + List<DecoratedNodeEntity> possibleParents = new ArrayList<>(); + + // noeud longline ? + GearType gearType = IdDtos.isLonglineId(tripNode.getId()) ? GearType.longline : GearType.seine; + + // racine + ObserveNode rootNode = treeHelper.getRootNode(); + + createPossibleParents(parentNode.getId(), possibleParents, gearType, rootNode); + + return possibleParents; + } + + public static void createPossibleParents(String oldProgramId, List<DecoratedNodeEntity> possibleParents, GearType gearType, ObserveNode rootNode) { + + ReferentialReferenceDecorator<ProgramDto> programDecorator = ObserveSwingApplicationContext.get().getDecoratorService().getReferentialReferenceDecorator(ProgramDto.class); + + for (int i = 0, n = rootNode.getChildCount(); i < n; i++) { + + ObserveNode programNode = rootNode.getChildAt(i); + String programId = programNode.getId(); + + // si le noeud programme n'est pas le même que le parent actuel + // si le noeud est bien un noeud de programme + if (IdDtos.isProgramId(programId) && !oldProgramId.equals(programId)) { + + if (programNode instanceof ProgramSeineNode && GearType.seine == gearType) { + + ProgramSeineNode node = (ProgramSeineNode) programNode; + possibleParents.add(DecoratedNodeEntity.newDecoratedNodeEntity(node, programDecorator)); + + } else if (programNode instanceof ProgramLonglineNode && GearType.longline == gearType) { + + ProgramLonglineNode node = (ProgramLonglineNode) programNode; + possibleParents.add(DecoratedNodeEntity.newDecoratedNodeEntity(node, programDecorator)); + + } + + } + } + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/usage/UsagesUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/usage/UsagesUI.jaxx new file mode 100644 index 0000000..a136aee --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/usage/UsagesUI.jaxx @@ -0,0 +1,91 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> + +<!-- +Interface graphique pour afficher la liste des usages d'une entitee donnee. +--> +<JPanel id='usagePanel' layout='{new BorderLayout()}'> + + <import> + fr.ird.observe.application.swing.ObserveSwingApplicationContext + fr.ird.observe.application.swing.ui.UIHelper + + fr.ird.observe.services.dto.ReferenceMap + + java.awt.Dimension + </import> + + <script><![CDATA[ + +private UsagesUIHandler handler = new UsagesUIHandler(); + +public void init(String message, + String message2, + String message3, + ReferenceMap usages) { + getHandler().initUI(this, message,message2, message3, usages); +} + +public void clean() { + getHandler().cleanUI(this); +} + +protected UsagesUIHandler getHandler() { + return handler; +} + +void $afterCompleteSetup() { + +} + +public void destroy() { + log.info("destroy ui " + getName()); + UIHelper.destroy(this); +} + +@Override +protected void finalize() throws Throwable { + super.finalize(); + destroy(); +} +]]> + </script> + + <JPanel constraints="BorderLayout.NORTH" + layout='{new BorderLayout()}'> + + <JPanel layout='{new BorderLayout()}' constraints="BorderLayout.CENTER"> + <JLabel id="message" constraints="BorderLayout.NORTH"/> + <JLabel id="message2" constraints="BorderLayout.CENTER"/> + <JLabel id="message3" constraints="BorderLayout.SOUTH"/> + </JPanel> + <JPanel constraints="BorderLayout.SOUTH" + minimumSize='{new Dimension(10,30)}'/> + <!--layout='{new BorderLayout()}'--> + <!--<JSeparator constraints="BorderLayout.SOUTH"/>--> + </JPanel> + + <JPanel id="usages" constraints="BorderLayout.CENTER" + layout="{new GridLayout(0, 1)}"/> + + +</JPanel> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/usage/UsagesUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/usage/UsagesUIHandler.java new file mode 100644 index 0000000..de5b5e7 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/usage/UsagesUIHandler.java @@ -0,0 +1,168 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.usage; + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.dto.AbstractReference; +import fr.ird.observe.services.dto.DataDto; +import fr.ird.observe.services.dto.DataReference; +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.services.dto.ReferenceMap; +import fr.ird.observe.services.dto.referential.ReferentialDto; +import fr.ird.observe.services.dto.referential.ReferentialReference; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.decorator.Decorator; + +import javax.swing.JLabel; +import javax.swing.JList; +import javax.swing.JScrollPane; +import java.awt.Dimension; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.stream.Collectors; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * @author Tony Chemit - chemit@codelutin.com + * @since 1.2 + */ +public class UsagesUIHandler { + + /** Logger */ + private static final Log log = LogFactory.getLog(UsagesUIHandler.class); + + /** + * Afficher les usages d'une entite donnee. + * + * @param ui l'ui + * @param message le message a afficher en haut + * @param message2 message supplementaire a afficher en haut + * @param message3 message supplementaire a afficher en haut + * @param usages les utilisations de l'entite donnee + */ + public void initUI(UsagesUI ui, + String message, + String message2, + String message3, + ReferenceMap usages) { + // toujours nettoyer l'ui avant tout + cleanUI(ui); + + ui.getMessage().setText(t(message)); + if (message2 != null) { + ui.getMessage2().setVisible(true); + ui.getMessage2().setText(message2); + } + if (message3 != null) { + ui.getMessage3().setVisible(true); + ui.getMessage3().setText(message3); + } + if (usages.isEmpty()) { + ui.getUsages().add(new JLabel(t("observe.message.no.usage.for.entity"))); + } else { + + for (Map.Entry<Class<? extends IdDto>, Set<? extends AbstractReference>> entry : usages.entrySet()) { + Class dtoType = entry.getKey(); + Set references = entry.getValue(); + String typeTitle = t(DecoratorService.getEntityLabel(dtoType)); + if (DataDto.class.isAssignableFrom(dtoType)) { + addDataReferenceUsages(ui, dtoType, references, typeTitle); + } else { + addReferentialReferenceUsages(ui, dtoType, references, typeTitle); + } + + } + } + } + + public void cleanUI(UsagesUI ui) { + ui.getUsages().removeAll(); + ui.getMessage().setText(null); + ui.getMessage2().setText(null); + ui.getMessage2().setVisible(false); + ui.getMessage3().setText(null); + ui.getMessage3().setVisible(false); + } + + protected <D extends DataDto> void addDataReferenceUsages(UsagesUI ui, + Class<D> dtoType, + Set<DataReference<D>> references, + String typeTitle) { + + int size = references.size(); + String typetitle = n("observe.content.label.usage.data.title"); + typetitle = t(typetitle, typeTitle, size); + + Decorator<?> decorator = ObserveSwingApplicationContext.get().getDecoratorService().getDataReferenceDecorator(dtoType); + Objects.requireNonNull(decorator, "could not find decorator for type " + dtoType); + + List<String> data = new ArrayList<>(size); + data.addAll(references.stream().map(decorator::toString).collect(Collectors.toList())); + + JList<? super String> l = new JList<>(data.toArray()); + + JScrollPane pane = new JScrollPane(); + pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); + pane.setMinimumSize(new Dimension(300, 30)); +// pane.setMaximumSize(new Dimension(300, 100)); + pane.setColumnHeaderView(new JLabel(typetitle)); + pane.setViewportView(l); + ui.getUsages().add(pane); + } + + + protected <D extends ReferentialDto> void addReferentialReferenceUsages(UsagesUI ui, + Class<D> dtoType, + Set<ReferentialReference<D>> references, + String typeTitle) { + + int size = references.size(); + String typetitle = n("observe.content.label.usage.referentiel.title"); + typetitle = t(typetitle, typeTitle, size); + + Decorator<?> decorator = ObserveSwingApplicationContext.get().getDecoratorService().getReferentialReferenceDecorator(dtoType); + Objects.requireNonNull(decorator, "could not find decorator for type " + dtoType); + + List<String> data = new ArrayList<>(size); + data.addAll(references.stream().map(decorator::toString).collect(Collectors.toList())); + + JList<? super String> l = new JList<>(data.toArray()); + + JScrollPane pane = new JScrollPane(); + pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); + pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); + pane.setMinimumSize(new Dimension(300, 30)); +// pane.setMaximumSize(new Dimension(300, 100)); + pane.setColumnHeaderView(new JLabel(typetitle)); + pane.setViewportView(l); + ui.getUsages().add(pane); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/BooleanEditor.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/BooleanEditor.java new file mode 100644 index 0000000..c3298ea --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/BooleanEditor.java @@ -0,0 +1,180 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.util; + + +import org.apache.commons.lang3.StringUtils; + +import javax.swing.JComboBox; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * Un éditeur de {@link Boolean} avec trois valeurs possibles : + * <ul> + * <li>{@code Null}</li> + * <li>{@code false}</li> + * <li>{@code true}</li> + * </ul> + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.5 + */ +public class BooleanEditor extends JComboBox { + + private static final long serialVersionUID = 1L; + + public enum Value { + NULL(n("observe.common.boolean.null"), null), + FALSE(n("observe.common.boolean.false"), false), + TRUE(n("observe.common.boolean.true"), true); + + private final String defaultLibelle; + + private final Boolean booleanValue; + + Value(String defaultLibelle, Boolean booleanValue) { + this.defaultLibelle = defaultLibelle; + this.booleanValue = booleanValue; + } + + public Boolean getBooleanValue() { + return booleanValue; + } + + public String getDefaultLibelle() { + return defaultLibelle; + } + + public static Value valueOf(Boolean value) { + Value result = null; + for (Value v : values()) { + if (v.getBooleanValue() == value) { + result = v; + break; + } + } + return result; + } + } + + protected static class ValueEntry { + + protected final Value value; + + protected final String text; + + ValueEntry(Value value, String text) { + this.value = value; + this.text = text; + } + + public Value getValue() { + return value; + } + + public String getText() { + return text; + } + + @Override + public boolean equals(Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + + ValueEntry that = (ValueEntry) o; + + if (!text.equals(that.text)) return false; + return value == that.value; + + } + + @Override + public int hashCode() { + int result = value.hashCode(); + result = 31 * result + text.hashCode(); + return result; + } + + @Override + public String toString() { + return text; + } + } + + protected static ValueEntry[] buildModel(String nullLibelle, + String falseLibelle, + String trueLibelle) { + ValueEntry[] result = new ValueEntry[3]; + + String text; + if (StringUtils.isBlank(nullLibelle)) { + text = Value.NULL.getDefaultLibelle(); + } else { + text = nullLibelle; + } + result[0] = new ValueEntry(Value.NULL, t(text)); + + if (StringUtils.isBlank(falseLibelle)) { + text = Value.FALSE.getDefaultLibelle(); + } else { + text = falseLibelle; + } + result[1] = new ValueEntry(Value.FALSE, t(text)); + + if (StringUtils.isBlank(trueLibelle)) { + text = Value.TRUE.getDefaultLibelle(); + } else { + text = trueLibelle; + } + result[2] = new ValueEntry(Value.TRUE, t(text)); + return result; + } + + public BooleanEditor() { + this(null, null, null); + } + + public BooleanEditor(String nullLibelle, + String falseLibelle, + String trueLibelle) { + super(buildModel(nullLibelle, falseLibelle, trueLibelle)); + } + + public void setBooleanValue(Boolean b) { + Value v = Value.valueOf(b); + ValueEntry e = (ValueEntry) dataModel.getElementAt(v.ordinal()); + setSelectedItem(e); + } + + public Boolean getBooleanValue() { + Object o = getSelectedItem(); + if (o == null) { + return null; + } + Boolean result; + ValueEntry v = (ValueEntry) o; + result = v.getValue().getBooleanValue(); + return result; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/DecoratedNodeEntity.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/DecoratedNodeEntity.java new file mode 100644 index 0000000..84c2b68 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/DecoratedNodeEntity.java @@ -0,0 +1,60 @@ +package fr.ird.observe.application.swing.ui.util; + +/*- + * #%L + * ObServe :: Application Swing + * %% + * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.base.Preconditions; +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.application.swing.ui.tree.AbstrctReferenceNodeSupport; +import org.nuiton.decorator.Decorator; + +/** + * @author Kevin Morin (Code Lutin) + * @since 5.0 + */ +public class DecoratedNodeEntity { + + private final String id; + + private final String label; + + public static <E extends IdDto> DecoratedNodeEntity newDecoratedNodeEntity(AbstrctReferenceNodeSupport<E, ?> node, Decorator<?> decorator) { + Preconditions.checkNotNull(node); + Preconditions.checkNotNull(decorator); + return new DecoratedNodeEntity(node.getId(), decorator.toString(node.getEntity())); + } + + public String getId() { + return id; + } + + @Override + public String toString() { + return label; + } + + protected DecoratedNodeEntity(String id, String label) { + this.id = id; + this.label = label; + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/FloatConverter.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/FloatConverter.java new file mode 100644 index 0000000..321f6fd --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/FloatConverter.java @@ -0,0 +1,87 @@ +/* + * #%L + * MS-Access Importer + * + * $Id$ + * $HeadURL$ + * %% + * Copyright (C) 2010 - 2011 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.ui.util; + +import org.apache.commons.beanutils.ConversionException; +import org.nuiton.converter.NuitonConverter; + +import static org.nuiton.i18n.I18n.t; + +/** + * A float converter which is not dependant on user locale to obtain the locale + * {@code dot} representation. + * + * It can transform {@code 0.2} and also {@code 0, 2}. + * + * @author tchemit - chemit@codelutin.com + * @since 1.3 + */ +public class FloatConverter implements NuitonConverter { + + @Override + public Object convert(Class aClass, Object value) { + if (value == null) { + throw new ConversionException( + t("nuitonutil.error.convertor.noValue", this)); + } + if (isEnabled(aClass)) { + Object result; + if (isEnabled(value.getClass())) { + result = value; + return result; + } + if (value instanceof String) { + result = valueOf((String) value); + return result; + } + } + throw new ConversionException( + t("nuitonutil.error.no.convertor", aClass.getName(), value)); + } + + protected Float valueOf(String value) { + try { + if (value.contains(",")) { + value = value.replaceAll(",", "."); + } + Float result; + result = Float.valueOf(value); + return result; + } catch (NumberFormatException e) { + throw new ConversionException( + t("nuitonutil.error.float.convertor", value, this, e.getMessage())); + } + } + + + protected boolean isEnabled(Class<?> aClass) { + return Float.class.equals(aClass); + } + + @Override + public Class<Float> getType() { + return Float.class; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/JVetoableTabbedPane.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/JVetoableTabbedPane.java new file mode 100644 index 0000000..ed8fdbb --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/JVetoableTabbedPane.java @@ -0,0 +1,102 @@ +package fr.ird.observe.application.swing.ui.util; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JTabbedPane; + +/** + * Created on 12/13/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.10 + */ +public class JVetoableTabbedPane extends JTabbedPane { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = LogFactory.getLog(JVetoableTabbedPane.class); + + protected transient ChangeSelectedIndex changeSelectedIndex; + + protected int previousIndex = -1; + + public void setChangeSelectedIndex(ChangeSelectedIndex changeSelectedIndex) { + this.changeSelectedIndex = changeSelectedIndex; + } + + public int getPreviousIndex() { + return previousIndex; + } + + @Override + public void setSelectedIndex(int index) { + + int selectedIndex = getSelectedIndex(); + + boolean canChange = true; + + if (changeSelectedIndex != null) { + + canChange = changeSelectedIndex.canChangeTab(selectedIndex, index); + + } + + if (canChange) { + + previousIndex = selectedIndex; + + if (log.isDebugEnabled()) { + log.debug("User accept to change from " + previousIndex + " tab to " + index + " tab."); + } + + super.setSelectedIndex(index); + + } else { + + if (log.isDebugEnabled()) { + log.debug("User refuse to change from " + selectedIndex + " tab to " + index + " tab."); + } + + } + + } + + public static interface ChangeSelectedIndex { + + /** + * Ask to change tab from {@code selectedIndex} tab to {@code index}. + * + * If response is {@code false}, then we should not quit the current tab. + * + * @param currentSelectedIndex the current index of the selected tab + * @param newSelectedIndex the index of the tab we want to go on + * @return {@code true} if we can do the change, {@code false} otherwise. + */ + boolean canChangeTab(int currentSelectedIndex, int newSelectedIndex); + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/ObserveSwingValidatorMessageTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/ObserveSwingValidatorMessageTableModel.java new file mode 100644 index 0000000..23fa9af --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/ObserveSwingValidatorMessageTableModel.java @@ -0,0 +1,84 @@ +package fr.ird.observe.application.swing.ui.util; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import jaxx.runtime.validator.swing.SwingValidatorMessage; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.JComponent; +import java.util.Collection; +import java.util.Collections; +import java.util.function.Predicate; + +/** + * Created on 3/18/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.15 + */ +public class ObserveSwingValidatorMessageTableModel extends SwingValidatorMessageTableModel { + + private static final long serialVersionUID = 1L; + + @Override + public void removeMessages(JComponent editor, + NuitonValidatorScope scope) { + if (scope == null) { + // on supprime tout sans aucun calcul + int nb = getRowCount(); + if (nb > 0) { + data.clear(); + fireTableRowsDeleted(0, nb - 1); + } + } else { + super.removeMessages(editor, scope); + } + } + + public void removeMessages(Predicate<SwingValidatorMessage> predicate) { + + for (int i = getRowCount() - 1; i > -1; i--) { + SwingValidatorMessage error = data.get(i); + + if (predicate.test(error)) { + // remove the message + data.remove(i); + fireTableRowsDeleted(i, i); + } + } + + } + + public <M extends SwingValidatorMessage> void addMessages(Collection<M> messages) { + + data.addAll(messages); + + // resort datas + Collections.sort(data); + + // notify + fireTableDataChanged(); + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/ObserveValidationMessageTableRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/ObserveValidationMessageTableRenderer.java new file mode 100644 index 0000000..3bad449 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/ObserveValidationMessageTableRenderer.java @@ -0,0 +1,147 @@ +package fr.ird.observe.application.swing.ui.util; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.services.service.actions.validate.ValidationMessage; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.ui.admin.validate.ValidationMessageTableModel; +import jaxx.runtime.validator.swing.SwingValidatorUtil; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.ImageIcon; +import javax.swing.JLabel; +import javax.swing.JTable; +import javax.swing.table.DefaultTableCellRenderer; +import java.awt.Color; +import java.awt.Component; + +import static org.nuiton.i18n.I18n.t; + +/** +* Created on 12/13/14. +* +* @author Tony Chemit - chemit@codelutin.com +* @since XXX +*/ +public class ObserveValidationMessageTableRenderer extends DefaultTableCellRenderer { + + private static final long serialVersionUID = 1L; + + protected transient DecoratorService decoratorService; + + public DecoratorService getDecoratorService() { + if (decoratorService == null) { + decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); + } + return decoratorService; + } + + public String getFieldName(JTable table, String value, int row) { + + String fieldName = value; + DecoratorService dService = getDecoratorService(); + if (!dService.getPropertyMatch(fieldName).matches()) { + fieldName = DecoratorService.getPropertyLabel(fieldName); + } + return t(fieldName); + } + + @Override + public Component getTableCellRendererComponent(JTable table, + Object value, + boolean isSelected, + boolean hasFocus, + int row, + int column) { + JLabel rendererComponent = (JLabel) + super.getTableCellRendererComponent( + table, + value, + isSelected, + hasFocus, + row, + column + ); + + ImageIcon icon = null; + String text = null; + String toolTipText = null; + + column = table.convertColumnIndexToModel(column); + if (table.getRowSorter() != null) { + row = table.getRowSorter().convertRowIndexToModel(row); + } + + switch (column) { + case 0: + // scope + NuitonValidatorScope scope = (NuitonValidatorScope) value; + icon = SwingValidatorUtil.getIcon(scope); + String label = t(scope.getLabel()); + toolTipText = t("validator.scope.tip", label); + break; + + case 1: + // field name + text = getFieldName(table, (String) value, row); + toolTipText = t("validator.field.tip", text); + break; + + case 2: + // message + text = getMessage(table, (String) value, row); + toolTipText = t("validator.message.tip", text); + break; + } + + rendererComponent.setText(text); + rendererComponent.setToolTipText(toolTipText); + rendererComponent.setIcon(icon); + + ValidationMessageTableModel model = (ValidationMessageTableModel) table.getModel(); + + NuitonValidatorScope scope = (NuitonValidatorScope) ( + column == 0 ? value : model.getValueAt(row, 0)); + + Color textColor = scope == NuitonValidatorScope.WARNING ? Color.RED : Color.BLACK; + rendererComponent.setForeground(textColor); + + return rendererComponent; + } + + public ImageIcon getIcon(NuitonValidatorScope scope) { + ImageIcon icon = SwingValidatorUtil.getIcon(scope); + return icon; + } + + public String getMessage(JTable table, String value, int row) { + ValidationMessageTableModel tableModel = + (ValidationMessageTableModel) table.getModel(); + ValidationMessage validationMessage = tableModel.getRow(row); + String text = validationMessage.getMessage(); + return text; + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/ObserveValidatorMessageTableRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/ObserveValidatorMessageTableRenderer.java new file mode 100644 index 0000000..cb5526f --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/ObserveValidatorMessageTableRenderer.java @@ -0,0 +1,104 @@ +package fr.ird.observe.application.swing.ui.util; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import jaxx.runtime.validator.swing.SwingValidatorMessage; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; +import jaxx.runtime.validator.swing.SwingValidatorMessageTableRenderer; +import org.apache.commons.lang3.BooleanUtils; +import org.nuiton.validator.NuitonValidatorScope; + +import javax.swing.JComponent; +import javax.swing.JTable; +import java.awt.Color; +import java.awt.Component; + +import static org.nuiton.i18n.I18n.t; + +/** +* Created on 12/13/14. +* +* @author Tony Chemit - chemit@codelutin.com +* @since XXX +*/ +public class ObserveValidatorMessageTableRenderer extends SwingValidatorMessageTableRenderer { + + private static final long serialVersionUID = 1L; + + protected transient DecoratorService decoratorService; + + public DecoratorService getDecoratorService() { + if (decoratorService == null) { + decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); + } + return decoratorService; + } + + @Override + public String getFieldName(JTable table, String value, int row) { + SwingValidatorMessageTableModel tableModel = (SwingValidatorMessageTableModel) table.getModel(); + SwingValidatorMessage model = tableModel.getRow(row); + JComponent editor = model.getEditor(); + String fieldName = null; + if (editor != null) { + String validatorLabel = (String) editor.getClientProperty("validatorLabel"); + + if (validatorLabel != null) { + fieldName = validatorLabel; + } + + Boolean doNotTranslateFieldName = (Boolean) editor.getClientProperty("doNotTranslateFieldName"); + if (BooleanUtils.isTrue(doNotTranslateFieldName)) { + fieldName = value; + } + } + + if (fieldName == null) { + fieldName = value; + + DecoratorService dService = getDecoratorService(); + if (!dService.getPropertyMatch(fieldName).matches()) { + fieldName = DecoratorService.getPropertyLabel(fieldName); + } + fieldName = t(fieldName); + } + + return fieldName; + } + + @Override + public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + Component result = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); + + SwingValidatorMessageTableModel model = (SwingValidatorMessageTableModel) table.getModel(); + + NuitonValidatorScope scope = (NuitonValidatorScope) ( + column == 0 ? value : model.getValueAt(row, 0)); + + Color textColor = scope == NuitonValidatorScope.WARNING ? Color.RED : Color.BLACK; + result.setForeground(textColor); + return result; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/SpringUtilities.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/SpringUtilities.java new file mode 100644 index 0000000..e78347d --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/SpringUtilities.java @@ -0,0 +1,250 @@ +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +/* + * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Sun Microsystems nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +package fr.ird.observe.application.swing.ui.util; + +import javax.swing.Spring; +import javax.swing.SpringLayout; +import java.awt.Component; +import java.awt.Container; + +/** + * A 1.4 file that provides utility methods for + * creating form- or grid-style layouts with SpringLayout. + * These utilities are used by several programs, such as + * SpringBox and SpringCompactGrid. + * + * @author Tony Chemit - chemit@codelutin.com + */ +public class SpringUtilities { + /** + * A debugging utility that prints to stdout the component's + * minimum, preferred, and maximum sizes. + */ + public static void printSizes(Component c) { + System.out.println("minimumSize = " + c.getMinimumSize()); + System.out.println("preferredSize = " + c.getPreferredSize()); + System.out.println("maximumSize = " + c.getMaximumSize()); + } + + /** + * Aligns the first {@code rows} * {@code cols} + * components of {@code parent} in + * a grid. Each component is as big as the maximum + * preferred width and height of the components. + * The parent is made just big enough to fit them all. + * + * @param rows number of rows + * @param cols number of columns + * @param initialX x location to start the grid at + * @param initialY y location to start the grid at + * @param xPad x padding between cells + * @param yPad y padding between cells + */ + public static void makeGrid(Container parent, + int rows, int cols, + int initialX, int initialY, + int xPad, int yPad) { + SpringLayout layout; + try { + layout = (SpringLayout) parent.getLayout(); + } catch (ClassCastException exc) { + System.err.println("The first argument to makeGrid must use SpringLayout."); + return; + } + + Spring xPadSpring = Spring.constant(xPad); + Spring yPadSpring = Spring.constant(yPad); + Spring initialXSpring = Spring.constant(initialX); + Spring initialYSpring = Spring.constant(initialY); + int max = rows * cols; + + //Calculate Springs that are the max of the width/height so that all + //cells have the same size. + Spring maxWidthSpring = layout.getConstraints(parent.getComponent(0)). + getWidth(); + Spring maxHeightSpring = layout.getConstraints(parent.getComponent(0)). + getWidth(); + for (int i = 1; i < max; i++) { + SpringLayout.Constraints cons = layout.getConstraints( + parent.getComponent(i)); + + maxWidthSpring = Spring.max(maxWidthSpring, cons.getWidth()); + maxHeightSpring = Spring.max(maxHeightSpring, cons.getHeight()); + } + + //Apply the new width/height Spring. This forces all the + //components to have the same size. + for (int i = 0; i < max; i++) { + SpringLayout.Constraints cons = layout.getConstraints( + parent.getComponent(i)); + + cons.setWidth(maxWidthSpring); + cons.setHeight(maxHeightSpring); + } + + //Then adjust the x/y constraints of all the cells so that they + //are aligned in a grid. + SpringLayout.Constraints lastCons = null; + SpringLayout.Constraints lastRowCons = null; + for (int i = 0; i < max; i++) { + SpringLayout.Constraints cons = layout.getConstraints( + parent.getComponent(i)); + if (i % cols == 0) { //start of new row + lastRowCons = lastCons; + cons.setX(initialXSpring); + } else { //x position depends on previous component + cons.setX(Spring.sum(lastCons.getConstraint(SpringLayout.EAST), + xPadSpring)); + } + + if (i / cols == 0) { //first row + cons.setY(initialYSpring); + } else { //y position depends on previous row + cons.setY(Spring.sum(lastRowCons.getConstraint(SpringLayout.SOUTH), + yPadSpring)); + } + lastCons = cons; + } + + //Set the parent's size. + SpringLayout.Constraints pCons = layout.getConstraints(parent); + pCons.setConstraint(SpringLayout.SOUTH, + Spring.sum( + Spring.constant(yPad), + lastCons.getConstraint(SpringLayout.SOUTH))); + pCons.setConstraint(SpringLayout.EAST, + Spring.sum( + Spring.constant(xPad), + lastCons.getConstraint(SpringLayout.EAST))); + } + + /* Used by makeCompactGrid. */ + + private static SpringLayout.Constraints getConstraintsForCell( + int row, int col, + Container parent, + int cols) { + SpringLayout layout = (SpringLayout) parent.getLayout(); + Component c = parent.getComponent(row * cols + col); + return layout.getConstraints(c); + } + + /** + * Aligns the first {@code rows} * {@code cols} + * components of {@code parent} in + * a grid. Each component in a column is as wide as the maximum + * preferred width of the components in that column; + * height is similarly determined for each row. + * The parent is made just big enough to fit them all. + * + * @param rows number of rows + * @param cols number of columns + * @param initialX x location to start the grid at + * @param initialY y location to start the grid at + * @param xPad x padding between cells + * @param yPad y padding between cells + */ + public static void makeCompactGrid(Container parent, + int rows, int cols, + int initialX, int initialY, + int xPad, int yPad) { + SpringLayout layout; + try { + layout = (SpringLayout) parent.getLayout(); + } catch (ClassCastException exc) { + System.err.println("The first argument to makeCompactGrid must use SpringLayout."); + return; + } + + //Align all cells in each column and make them the same width. + Spring x = Spring.constant(initialX); + for (int c = 0; c < cols; c++) { + Spring width = Spring.constant(0); + for (int r = 0; r < rows; r++) { + width = Spring.max(width, + getConstraintsForCell(r, c, parent, cols). + getWidth()); + } + for (int r = 0; r < rows; r++) { + SpringLayout.Constraints constraints = + getConstraintsForCell(r, c, parent, cols); + constraints.setX(x); + constraints.setWidth(width); + } + x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad))); + } + + //Align all cells in each row and make them the same height. + Spring y = Spring.constant(initialY); + for (int r = 0; r < rows; r++) { + Spring height = Spring.constant(0); + for (int c = 0; c < cols; c++) { + height = Spring.max(height, + getConstraintsForCell(r, c, parent, cols). + getHeight()); + } + for (int c = 0; c < cols; c++) { + SpringLayout.Constraints constraints = + getConstraintsForCell(r, c, parent, cols); + constraints.setY(y); + constraints.setHeight(height); + } + y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad))); + } + + //Set the parent's size. + SpringLayout.Constraints pCons = layout.getConstraints(parent); + pCons.setConstraint(SpringLayout.SOUTH, y); + pCons.setConstraint(SpringLayout.EAST, x); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/AbstractSelectTableAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/AbstractSelectTableAction.java new file mode 100644 index 0000000..cbb62fc --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/AbstractSelectTableAction.java @@ -0,0 +1,119 @@ +package fr.ird.observe.application.swing.ui.util.table; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import jaxx.runtime.swing.JTables; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.AbstractAction; +import javax.swing.JTable; + +/** + * Abstract action to select a cell in a table. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.8 + */ +public abstract class AbstractSelectTableAction<M extends EditableTableModelSupport> extends AbstractAction { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = + LogFactory.getLog(AbstractSelectTableAction.class); + + private final M model; + + private final JTable table; + + public AbstractSelectTableAction(M model, JTable table) { + this.model = model; + this.table = table; + } + + protected void doSelectCell(int rowIndex, int columnIndex) { + + if (log.isDebugEnabled()) { + log.debug("Will select cell at " + getCellCoordinate(rowIndex, columnIndex)); + } + JTables.doSelectCell(table, rowIndex, columnIndex); + } + + protected int getSelectedRow() { + int result = table.getSelectedRow(); + return result; + } + + protected int getSelectedColumn() { + int result = table.getSelectedColumn(); + return result; + } + + protected int getRowCount() { + return table.getRowCount(); + } + + protected int getColumnCount() { + return table.getColumnCount(); + } + + protected boolean isCellEditable(int rowIndex, int columnIndex) { + boolean result = rowIndex > -1 && columnIndex > -1 && + table.isCellEditable(rowIndex, columnIndex); + return result; + } + + protected boolean isCreateNewRow(int rowIndex) { + + boolean canCreateNewRow = model.isCanAddRow(); + + if (canCreateNewRow) { + + if (rowIndex == -1 && model.isEmpty()) { + + // model is empty, we surely can add a new row + canCreateNewRow = true; + + } else { + + // ask model if we can add a new row + canCreateNewRow = model.isCanCreateNewRow(rowIndex); + + } + + } + + return canCreateNewRow; + + } + + protected String getCellCoordinate(int rowIndex, int columnIndex) { + return " [" + rowIndex + ", " + columnIndex + "]"; + } + + protected void addNewRow() { + model.addNewRow(); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/AutotSelectRowAndShowPopupActionSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/AutotSelectRowAndShowPopupActionSupport.java new file mode 100644 index 0000000..a7bbf94 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/AutotSelectRowAndShowPopupActionSupport.java @@ -0,0 +1,227 @@ +package fr.ird.observe.application.swing.ui.util.table; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import org.apache.commons.lang3.ArrayUtils; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JPopupMenu; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import javax.swing.SwingUtilities; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; + +/** + * Created on 12/12/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.10 + */ +public abstract class AutotSelectRowAndShowPopupActionSupport { + + /** Logger. */ + private static final Log log = LogFactory.getLog(AutotSelectRowAndShowPopupActionSupport.class); + + private final JScrollPane pane; + + private final JTable table; + + private final JPopupMenu popup; + + protected AutotSelectRowAndShowPopupActionSupport(JScrollPane pane, final JTable table, JPopupMenu popup) { + this.pane = pane; + this.table = table; + this.popup = popup; + + KeyAdapter keyAdapter = new KeyAdapter() { + @Override + public void keyPressed(KeyEvent e) { + if (table.isEnabled()) { + openRowMenu(e); + } + } + }; + this.table.addKeyListener(keyAdapter); + pane.addKeyListener(keyAdapter); + + MouseAdapter mouseAdapter = new MouseAdapter() { + @Override + public void mouseClicked(MouseEvent e) { + if (AutotSelectRowAndShowPopupActionSupport.this.table.isEnabled()) { + + autoSelectRowInTable(e); + + } + } + }; + this.table.addMouseListener(mouseAdapter); + pane.addMouseListener(mouseAdapter); + } + + public JPopupMenu getPopup() { + return popup; + } + + public JTable getTable() { + return table; + } + + protected abstract void beforeOpenPopup(int modelRowIndex, int modelColumnIndex); + + public void autoSelectRowInTable(MouseEvent e) { + + boolean rightClick = SwingUtilities.isRightMouseButton(e); + + if (rightClick || SwingUtilities.isLeftMouseButton(e)) { + + // get the coordinates of the mouse click + Point p = e.getPoint(); + + int[] selectedRows = table.getSelectedRows(); + int[] selectedColumns = table.getSelectedColumns(); + + // get the row index at this point + int rowIndex = table.rowAtPoint(p); + + // get the column index at this point + int columnIndex = table.columnAtPoint(p); + + if (log.isDebugEnabled()) { + log.debug("At point [" + p + "] found Row " + rowIndex + ", Column " + columnIndex); + } + + boolean canContinue = true; + + if (table.isEditing()) { + + // stop editing + boolean stopEdit = table.getCellEditor().stopCellEditing(); + if (!stopEdit) { + if (log.isWarnEnabled()) { + log.warn("Could not stop edit cell..."); + } + canContinue = false; + } + } + + if (canContinue) { + + // select row (could empty selection) + if (rowIndex == -1) { + table.clearSelection(); + } else if (!ArrayUtils.contains(selectedRows, rowIndex)) { + // set selection + table.setRowSelectionInterval(rowIndex, rowIndex); + } + + // select column (could empty selection) + if (columnIndex == -1) { + table.clearSelection(); + } else if (!ArrayUtils.contains(selectedColumns, columnIndex)) { + table.setColumnSelectionInterval(columnIndex, columnIndex); + } + + if (rightClick) { + + showPopup(rowIndex, columnIndex, p); + +// // use now model coordinate +// int modelRowIndex = rowIndex == -1 ? -1 : table.convertRowIndexToModel(rowIndex); +// int modelColumnIndex = columnIndex == -1 ? -1 : table.convertColumnIndexToModel(columnIndex); +// +// beforeOpenPopup(modelRowIndex, modelColumnIndex); +// +// // on right click show popup +// popup.show(table, e.getX(), e.getY()); + } + } + } + } + + public void openRowMenu(KeyEvent e) { + + if (e.getKeyCode() == KeyEvent.VK_CONTEXT_MENU) { + + // get the lowest selected row + int[] selectedRows = table.getSelectedRows(); + int lowestRow = -1; + for (int row : selectedRows) { + lowestRow = Math.max(lowestRow, row); + } + // get the selected column + int selectedColumn = table.getSelectedColumn(); + Rectangle r = table.getCellRect(lowestRow, selectedColumn, true); + + // get the point in the middle lower of the cell + Point p = new Point(r.x + r.width / 2, r.y + r.height); + + if (log.isDebugEnabled()) { + log.debug("Row " + lowestRow + " found t point [" + p + "]"); + } + + boolean canContinue = true; + + if (table.isEditing()) { + + // stop editing + boolean stopEdit = table.getCellEditor().stopCellEditing(); + if (!stopEdit) { + if (log.isWarnEnabled()) { + log.warn("Could not stop edit cell..."); + } + canContinue = false; + } + } + + if (canContinue) { + + showPopup(lowestRow, selectedColumn, p); + +// // use now model coordinate +// int rowIndex = table.convertRowIndexToModel(lowestRow); +// int columnIndex = table.convertColumnIndexToModel(selectedColumn); +// beforeOpenPopup(rowIndex, columnIndex); +// +// popup.show(table, p.x, p.y); + } + } + } + + protected void showPopup(int row, int column, Point p) { + + // use now model coordinate + int rowIndex = row == -1 ? -1 : table.convertRowIndexToModel(row); + int columnIndex = column == -1 ? -1 : table.convertColumnIndexToModel(column); + beforeOpenPopup(rowIndex, columnIndex); + + popup.show(table, p.x, p.y); + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/EditableList.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/EditableList.java new file mode 100644 index 0000000..8291625 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/EditableList.java @@ -0,0 +1,65 @@ +package fr.ird.observe.application.swing.ui.util.table; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +/** + * Created on 12/10/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.9 + */ +public class EditableList<E extends Serializable> implements Serializable { + + private static final long serialVersionUID = 1L; + + final List<E> original = new ArrayList<>(); + + final List<E> data = new ArrayList<>(); + + public List<E> getData() { + return data; + } + + public void setData(List<E> data) { + this.data.clear(); + this.data.addAll(data); + } + + public List<E> getOriginal() { + return original; + } + + public void setOriginal(List<E> data) { + this.original.clear(); + this.original.addAll(data); + } + + public void reset() { + setData(Collections.emptyList()); + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/EditableTableModelSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/EditableTableModelSupport.java new file mode 100644 index 0000000..a1190a1 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/EditableTableModelSupport.java @@ -0,0 +1,629 @@ +package fr.ird.observe.application.swing.ui.util.table; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import fr.ird.observe.application.swing.ui.UIHelper; +import jaxx.runtime.swing.editor.cell.NumberCellEditor; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.jdesktop.swingx.autocomplete.ComboBoxCellEditor; + +import javax.swing.JTable; +import javax.swing.ListSelectionModel; +import javax.swing.event.ListSelectionListener; +import javax.swing.table.AbstractTableModel; +import javax.swing.table.TableCellEditor; +import javax.swing.table.TableColumn; +import javax.swing.table.TableColumnModel; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.beans.PropertyChangeListener; +import java.beans.PropertyChangeSupport; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Enumeration; +import java.util.List; + +/** + * Created on 12/3/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.8 + */ +public abstract class EditableTableModelSupport<E extends Serializable> extends AbstractTableModel { + + /** Logger. */ + private static final Log log = LogFactory.getLog(EditableTableModelSupport.class); + + public static final String EDITABLE_PROPERTY = "editable"; + + public static final String EMPTY_PROPERTY = "empty"; + + public static final String MODIFIED_PROPERTY = "modified"; + + public static final String VALID_PROPERTY = "valid"; + + public static final String SELECTED_ROW_INDEX_PROPERTY = "selectedRowIndex"; + + public static final String SELECTED_ROW_PROPERTY = "selectedRow"; + + public static final String SELECTION_EMPTY_PROPERTY = "selectionEmpty"; + + private static final long serialVersionUID = 1L; + + /** pour la propagation des modifications d'états */ + protected final PropertyChangeSupport pcs = new PropertyChangeSupport(this); + + /** un drapeau pour savoir si le modèle est éditable */ + protected boolean editable; + + /** un drapeau pour savoir si le modèle est valide */ + protected boolean valid; + + /** un drapeau pour savoir si le modèle est modifié */ + protected boolean modified; + + /** la ligne sélectionnée et en cours d'édition. */ + protected int selectedRowIndex = -1; /* -1 = pas de selection */ + + /** la liste des données du modèle */ + protected final List<E> data = new ArrayList<>(); + + private JTable table; + + private transient ListSelectionModel selectionModel; + + private final boolean canAddRow; + + protected transient ListSelectionListener whenSelectionModelChanged; + + protected EditableTableModelSupport(boolean canAddRow) { + this.canAddRow = canAddRow; + } + + public boolean isCanAddRow() { + return canAddRow; + } + + protected abstract E createNewRow(); + + public abstract boolean isRowNotEmpty(E valid); + + protected abstract boolean isRowValid(E valid); + + protected boolean isCanCreateNewRow(int rowIndex) { + + boolean canCreateNewRow = canAddRow; + if (canAddRow) { + E row = getData(rowIndex); + canCreateNewRow = isRowNotEmpty(row) && isRowValid(row); + } + + return canCreateNewRow; + + } + + public List<E> getNotEmptyData() { + List<E> result = new ArrayList<>(); + for (E row : data) { + if (isRowNotEmpty(row)) { + result.add(row); + } + } + return result; + } + + public List<E> getData() { + return data; + } + + public E getData(int rowIndex) { + return data.get(rowIndex); + } + + + @Override + public boolean isCellEditable(int rowIndex, int columnIndex) { + return true; + } + + @Override + public int getRowCount() { + return data.size(); + } + + public void setData(List<E> data) { + this.data.clear(); + this.data.addAll(data); + if (this.data.isEmpty() && editable && canAddRow) { + + // add an empty row (no fire and select: will be done just below) + addNewRow(0, false); + + } + + // reset previous selection + selectedRowIndex = -1; + + fireTableDataChanged(); + + // on selectionne la première ligne (ou supprime la selection si plus de donnes) + setSelectedRowIndex(isEmpty() ? -1 : 0, true); + + fireEmpty(); + + } + + public void removeData(int selectedRow) { + + this.data.remove(selectedRow); + fireTableRowsDeleted(selectedRow, selectedRow); + + // on selectionne la ligne précédente (ou supprime la selection si plus de donnes) + setSelectedRowIndex(isEmpty() ? -1 : selectedRow - 1, true); + + fireEmpty(); + + } + + public void removeSelectedRow() { + + // get selected row + int selectedRowIndex1 = getSelectedRowIndex(); + + // clear selection (to avoid any trouble while trying to access previous selected values which does not exists + // any long in data list) + setSelectedRowIndex(-1, true); + + // safe remove data + removeData(selectedRowIndex1); + + } + + public void addNewRow() { + + int row = getRowCount(); + addNewRow(row, true); + + } + + public void insertBeforeSelectedRow() { + + int currentRow = getSelectedRowIndex(); + + setSelectedRowIndex(-1); // clear selection + + int insertRow = currentRow; + if (insertRow < 0) { + insertRow = 0; + } + if (log.isInfoEnabled()) { + log.info("Insert before selected row: " + currentRow + " :: " + insertRow); + } + + addNewRow(insertRow, true); + } + + public void insertAfterSelectedRow() { + + int currentRow = getSelectedRowIndex(); + + setSelectedRowIndex(-1); // clear selection + + int insertRow = currentRow == getRowCount() ? currentRow : currentRow + 1; + if (log.isInfoEnabled()) { + log.info("Insert after selected row: " + currentRow + " :: " + insertRow); + } + + addNewRow(insertRow, true); + + } + + public void addNewRow(int row, boolean fireAndSelectNewRow) { + + ensureEditable(); + + // on est autorise a ajouter une nouvelle entrée + + E bean = createNewRow(); + + if (row == getRowCount()) { + + // add new row + data.add(bean); + + } else { + + // insert new row (but not at the end) + data.add(row, bean); + + } + + if (fireAndSelectNewRow) { + + fireTableRowsInserted(row, row); + fireEmpty(); + + // la nouvelle ligne est celle en cours d'edition + setSelectedRowIndex(row, true); + + } + + fireEmpty(); + + } + + public void clear() { + + setSelectedRowIndex(-1); + setData(Collections.emptyList()); + validate(); + setModified(false); + fireEmpty(); + + } + + public boolean isEmpty() { + return getRowCount() == 0; + } + + public boolean isSelectionEmpty() { + return getSelectedRowIndex() == -1; + } + + public E getSelectedRow() { + return isSelectionEmpty() ? null : getData(getSelectedRowIndex()); + } + + public int getSelectedRowIndex() { + return selectedRowIndex; + } + + public void setSelectedRowIndex(int selectedRowIndex) { + setSelectedRowIndex(selectedRowIndex, false); + } + + private boolean selectionIsAdjusting; + + public void setSelectedRowIndex(int selectedRowIndex, boolean pushToSelectionModel) { + + if (!selectionIsAdjusting) { + + selectionIsAdjusting = true; + + try { + + int oldSelectedRowIndex = getSelectedRowIndex(); + //boolean oldSelectionEmpty = isSelectionEmpty(); + E oldSelectedRow = getSelectedRow(); + + this.selectedRowIndex = selectedRowIndex; + + if (pushToSelectionModel && getSelectionModel() != null) { + + getSelectionModel().setSelectionInterval(selectedRowIndex, selectedRowIndex); + + } + + firePropertyChange(SELECTED_ROW_INDEX_PROPERTY, oldSelectedRowIndex, selectedRowIndex); + firePropertyChange(SELECTION_EMPTY_PROPERTY, null /* to force fire */, isSelectionEmpty()); + firePropertyChange(SELECTED_ROW_PROPERTY, oldSelectedRow, getSelectedRow()); + + } finally { + + selectionIsAdjusting = false; + + } + + } + + } + + public boolean isModified() { + return modified; + } + + public void setModified(boolean modified) { + this.modified = modified; + firePropertyChange(MODIFIED_PROPERTY, null, modified); + } + + public void addPropertyChangeListener(PropertyChangeListener listener) { + pcs.addPropertyChangeListener(listener); + } + + public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { + pcs.addPropertyChangeListener(propertyName, listener); + } + + public void removePropertyChangeListener(PropertyChangeListener listener) { + pcs.removePropertyChangeListener(listener); + } + + public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { + pcs.removePropertyChangeListener(propertyName, listener); + } + + public void firePropertyChange(String propertyName, Object oldValue, Object newValue) { + pcs.firePropertyChange(propertyName, oldValue, newValue); + } + + public void fireEmpty() { + firePropertyChange(EMPTY_PROPERTY, null, isEmpty()); + } + + protected void ensureEditable() throws IllegalStateException { + if (!editable) { + throw new IllegalStateException("can not edit this model since it is marked as none editable " + this); + } + } + + public void setEditable(Boolean editable) { + this.editable = editable; + } + + public boolean isValid() { + return valid; + } + + public void setValid(boolean valid) { + this.valid = valid; + firePropertyChange(VALID_PROPERTY, null, isValid()); + } + + public void validate() { + + boolean newValidValue = computeValidState(); + setValid(newValidValue); + + } + + protected boolean computeValidState() { + boolean newValidValue = true; + + for (E row : data) { + boolean rowValid = !isRowNotEmpty(row) || isRowValid(row); + if (!rowValid) { + newValidValue = false; + break; + } + } + return newValidValue; + } + + public void installSelectionListener(JTable table) { + + // always try to uninstall it before to avoid any memory leak + uninstallSelectionListener(table); + + this.table = table; + + ListSelectionListener listener = getWhenSelectionModelChanged(); + getSelectionModel().addListSelectionListener(listener); + + } + + public ListSelectionModel getSelectionModel() { + if (selectionModel == null) { + selectionModel = table == null ? null : table.getSelectionModel(); + } + return selectionModel; + } + + public void uninstallSelectionListener(JTable table) { + + ListSelectionListener listener = getWhenSelectionModelChanged(); + table.getSelectionModel().removeListSelectionListener(listener); + + this.table = null; + this.selectionModel = null; + + } + + private static final String OBSERVE_KEY_ADAPTER = "ObServeKeyAdapter"; + + private static final String OBSERVE_FOCUS_ADAPTER = "ObServeFocusAdapter"; + + public void installTableFocusListener(final JTable table) { + + // always try to uninstall it before to avoid any memory leak + uninstallTableFocusListener(table); + + FocusAdapter focusAdapter = new FocusAdapter() { + @Override + public void focusLost(FocusEvent e) { + + UIHelper.stopEditing(table); + } + }; + + Enumeration<TableColumn> columns = table.getColumnModel().getColumns(); + while (columns.hasMoreElements()) { + TableColumn tableColumn = columns.nextElement(); + TableCellEditor cellEditor = tableColumn.getCellEditor(); + if (cellEditor instanceof NumberCellEditor) { + NumberCellEditor editor = (NumberCellEditor) cellEditor; + editor.getNumberEditor().getTextField().addFocusListener(focusAdapter); + } else if (cellEditor instanceof ComboBoxCellEditor) { +// ComboBoxCellEditor editor = (ComboBoxCellEditor) cellEditor; + //FIXME should also use the focus listener here + } + } + + if (log.isDebugEnabled()) { + log.debug("Intall " + focusAdapter); + } + + table.putClientProperty(OBSERVE_FOCUS_ADAPTER, focusAdapter); + + } + + public void uninstallTableFocusListener(final JTable table) { + + FocusAdapter focusAdapter = (FocusAdapter) table.getClientProperty(OBSERVE_FOCUS_ADAPTER); + + if (focusAdapter != null) { + + if (log.isDebugEnabled()) { + log.debug("Desintall " + focusAdapter); + } + + TableColumnModel columnModel = table.getColumnModel(); + Enumeration<TableColumn> columns = columnModel.getColumns(); + while (columns.hasMoreElements()) { + TableColumn tableColumn = columns.nextElement(); + TableCellEditor cellEditor = tableColumn.getCellEditor(); + if (cellEditor instanceof NumberCellEditor) { + NumberCellEditor editor = (NumberCellEditor) cellEditor; + editor.getNumberEditor().getTextField().removeFocusListener(focusAdapter); + } + } + + table.putClientProperty(OBSERVE_KEY_ADAPTER, null); + } + } + + public void installTableKeyListener(final JTable table) { + + // always try to uninstall it before to avoid any memory leak + uninstallTableKeyListener(table); + + EditableTableModelSupport model = (EditableTableModelSupport) table.getModel(); + final MoveToNextEditableCellAction nextCellAction = MoveToNextEditableCellAction.newAction(model, table); + final MoveToPreviousEditableCellAction previousCellAction = MoveToPreviousEditableCellAction.newAction(model, table); + + final MoveToNextEditableRowAction nextRowAction = MoveToNextEditableRowAction.newAction(model, table); + final MoveToPreviousEditableRowAction previousRowAction = MoveToPreviousEditableRowAction.newAction(model, table); + + KeyAdapter keyAdapter = new KeyAdapter() { + + @Override + public void keyPressed(KeyEvent e) { + TableCellEditor editor = table.getCellEditor(); + + int keyCode = e.getKeyCode(); + if (keyCode == KeyEvent.VK_LEFT || + (keyCode == KeyEvent.VK_TAB && e.isShiftDown())) { + e.consume(); + if (editor != null) { + editor.stopCellEditing(); + } + previousCellAction.actionPerformed(null); + + } else if (keyCode == KeyEvent.VK_RIGHT || + keyCode == KeyEvent.VK_TAB) { + e.consume(); + if (editor != null) { + editor.stopCellEditing(); + } + nextCellAction.actionPerformed(null); + + } else if (keyCode == KeyEvent.VK_UP || + (keyCode == KeyEvent.VK_ENTER && e.isShiftDown())) { + e.consume(); + if (editor != null) { + editor.stopCellEditing(); + } + previousRowAction.actionPerformed(null); + + } else if (e.getKeyCode() == KeyEvent.VK_ENTER || + keyCode == KeyEvent.VK_DOWN) { + e.consume(); + if (editor != null) { + editor.stopCellEditing(); + } + nextRowAction.actionPerformed(null); + } + } + }; + + Enumeration<TableColumn> columns = table.getColumnModel().getColumns(); + while (columns.hasMoreElements()) { + TableColumn tableColumn = columns.nextElement(); + TableCellEditor cellEditor = tableColumn.getCellEditor(); + if (cellEditor instanceof NumberCellEditor) { + NumberCellEditor editor = (NumberCellEditor) cellEditor; + editor.getNumberEditor().getTextField().addKeyListener(keyAdapter); + + } + } + + if (log.isDebugEnabled()) { + log.debug("Intall " + keyAdapter); + } + + table.addKeyListener(keyAdapter); + table.putClientProperty(OBSERVE_KEY_ADAPTER, keyAdapter); + + } + + public void uninstallTableKeyListener(final JTable table) { + + KeyAdapter keyAdapter = (KeyAdapter) table.getClientProperty(OBSERVE_KEY_ADAPTER); + + if (keyAdapter != null) { + + if (log.isDebugEnabled()) { + log.debug("Desintall " + keyAdapter); + } + + table.removeKeyListener(keyAdapter); + + TableColumnModel columnModel = table.getColumnModel(); + Enumeration<TableColumn> columns = columnModel.getColumns(); + while (columns.hasMoreElements()) { + TableColumn tableColumn = columns.nextElement(); + TableCellEditor cellEditor = tableColumn.getCellEditor(); + if (cellEditor instanceof NumberCellEditor) { + NumberCellEditor editor = (NumberCellEditor) cellEditor; + editor.getNumberEditor().getTextField().removeKeyListener(keyAdapter); + } + } + table.putClientProperty(OBSERVE_KEY_ADAPTER, null); + } + } + + protected ListSelectionListener getWhenSelectionModelChanged() { + if (whenSelectionModelChanged == null) { + whenSelectionModelChanged = e -> { + + if (!e.getValueIsAdjusting()) { + int selectedRow = table.getSelectedRow(); + if (selectedRow >= getRowCount()) { + selectedRow = getRowCount() - 1; + if (log.isInfoEnabled()) { + log.info("Decrease selectedRow!!! to " + selectedRow); + } + } + setSelectedRowIndex(selectedRow); + } + + }; + } + return whenSelectionModelChanged; + } + +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/EditableTableWithCacheTableModelSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/EditableTableWithCacheTableModelSupport.java new file mode 100644 index 0000000..63b7857 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/EditableTableWithCacheTableModelSupport.java @@ -0,0 +1,151 @@ +package fr.ird.observe.application.swing.ui.util.table; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.base.Preconditions; +import com.google.common.collect.Lists; +import fr.ird.observe.services.dto.IdDto; +import org.nuiton.util.beans.Binder; +import org.nuiton.util.beans.BinderFactory; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; + +/** + * Created on 12/11/14. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.10 + */ +public abstract class EditableTableWithCacheTableModelSupport<E extends IdDto> extends EditableTableModelSupport<E> { + + private static final long serialVersionUID = 1L; + + /** + * Cache de liste de données par numéro de ligne. Cela sert à pouvoir conserver plusieurs listes + * de données issues de ce table. Typiquement dans l'écran de capture ll ou on doit conserver pour une capture + * (donc une ligne du tableau principal) n mesures de taille et n meausre de poids. + */ + protected final Map<Integer, EditableList<E>> cacheByRow; + + protected EditableTableWithCacheTableModelSupport() { + super(true); + this.cacheByRow = new TreeMap<>(); + } + + public List<E> getCacheForRow(int rowIndex) { + EditableList<E> measures = cacheByRow.get(rowIndex); + return measures == null ? null : measures.getData(); + } + + public void initCacheForRow(int editingRow, List<E> data) { + + EditableList<E> editableList = cacheByRow.get(editingRow); + Preconditions.checkState(editableList == null, "Cant have a list for row: " + editingRow); + editableList = new EditableList<>(); + + // Get a copy of the list (to avoid to edit the content of the list) + List<E> original = copyList(data); + editableList.setOriginal(original); + editableList.setData(data); + cacheByRow.put(editingRow, editableList); + + } + + public void storeInCacheForRow(int editingRow) { + + List<E> measures = getData(); + EditableList<E> editableList = cacheByRow.get(editingRow); + Preconditions.checkState(editableList != null, "No list found for row: " + editingRow); + editableList.setData(measures); + + } + + public void removeCacheForRow(int rowToDelete) { + + cacheByRow.remove(rowToDelete); + + List<Integer> rows = Lists.newArrayList(getCacheRowsChanged()); + Collections.sort(rows); + + for (Integer row : rows) { + + if (row > rowToDelete) { + + // set now to row -1 + EditableList<E> remove = cacheByRow.remove(row); + cacheByRow.put(row - 1, remove); + + } + } + + } + + public void resetCacheForRow(int rowtoReset) { + + EditableList<E> editableList = cacheByRow.get(rowtoReset); + Preconditions.checkState(editableList != null); + + // remove data from cache + editableList.reset(); + + // restore a copy of original data + List<E> newData = copyList(editableList.getOriginal()); + editableList.setData(newData); + setData(newData); + + validate(); + + } + + public Set<Integer> getCacheRowsChanged() { + Set<Integer> rows = cacheByRow.keySet(); + return rows; + } + + @Override + public void clear() { + + cacheByRow.clear(); + super.clear(); + + } + + protected List<E> copyList(List<E> data) { + List<E> copy = new ArrayList<>(data.size()); + for (E measure : data) { + E originalMeasure = createNewRow(); + + Class<E> sourceType = (Class<E>) originalMeasure.getClass(); + Binder<E, E> binder = BinderFactory.newBinder(sourceType); + binder.copy(measure, originalMeasure); + + copy.add(originalMeasure); + } + return copy; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/InlineTableAutotSelectRowAndShowPopupAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/InlineTableAutotSelectRowAndShowPopupAction.java new file mode 100644 index 0000000..d552d67 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/InlineTableAutotSelectRowAndShowPopupAction.java @@ -0,0 +1,74 @@ +package fr.ird.observe.application.swing.ui.util.table; + +/*- + * #%L + * ObServe :: Application Swing + * %% + * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; +import javax.swing.JScrollPane; +import javax.swing.JTable; +import java.io.Serializable; + +/** + * Created on 15/03/16. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 5.0 + */ +public class InlineTableAutotSelectRowAndShowPopupAction<E extends Serializable, M extends EditableTableModelSupport<E>> extends AutotSelectRowAndShowPopupActionSupport { + + private final JMenuItem addWidget; + private final JMenuItem deleteWidget; + private final M tableModel; + + public InlineTableAutotSelectRowAndShowPopupAction(JScrollPane scrollPane, + JTable table, + M tableModel, + JPopupMenu popup, + JMenuItem addWidget, + JMenuItem deleteWidget) { + super(scrollPane, table, popup); + this.addWidget = addWidget; + this.deleteWidget = deleteWidget; + this.tableModel = tableModel; + } + + @Override + protected void beforeOpenPopup(int modelRowIndex, int modelColumnIndex) { + + boolean canAdd = tableModel.isValid(); + boolean canDelete = !tableModel.isSelectionEmpty(); + + if (canDelete) { + + // check also that the row is not empty + E selectedData = tableModel.getSelectedRow(); + canDelete = tableModel.isRowNotEmpty(selectedData); + + } + + addWidget.setEnabled(canAdd); + deleteWidget.setEnabled(canDelete); + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/MoveToNextEditableCellAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/MoveToNextEditableCellAction.java new file mode 100644 index 0000000..6287720 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/MoveToNextEditableCellAction.java @@ -0,0 +1,100 @@ +package fr.ird.observe.application.swing.ui.util.table; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JTable; +import java.awt.event.ActionEvent; + +/** + * Action to select next editable cell in a table. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.8 + */ +public class MoveToNextEditableCellAction<M extends EditableTableModelSupport> extends AbstractSelectTableAction<M> { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = + LogFactory.getLog(MoveToNextEditableCellAction.class); + + protected MoveToNextEditableCellAction(M model, JTable table) { + super(model, table); + } + + public static <M extends EditableTableModelSupport> MoveToNextEditableCellAction<M> newAction(M model, JTable table) { + return new MoveToNextEditableCellAction<>(model, table); + } + + @Override + public void actionPerformed(ActionEvent e) { + + int currentRow = getSelectedRow(); + int currentColumn = getSelectedColumn(); + + if (log.isDebugEnabled()) { + log.debug("Move to previous editable cell " + + getCellCoordinate(currentRow, currentColumn)); + } + + int columnCount = getColumnCount(); + + int rowCount = getRowCount(); + + if (currentRow <= rowCount || currentColumn <= columnCount) { + + // go to next cell + currentColumn++; + boolean canSelect = true; + + // select next cell + if (currentColumn >= columnCount) { + + // no more cell, so will move to next editable column on next row + currentColumn = 0; + currentRow++; + + if (currentRow == rowCount) { + + if (isCreateNewRow(currentRow -1)) { + + // create a new row in model + addNewRow(); + } else { + + // can not create new row, so do nothing + canSelect = false; + } + } + } + + if (canSelect) { + doSelectCell(currentRow, currentColumn); + } + } + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/MoveToNextEditableRowAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/MoveToNextEditableRowAction.java new file mode 100644 index 0000000..ae9dfb7 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/MoveToNextEditableRowAction.java @@ -0,0 +1,92 @@ +package fr.ird.observe.application.swing.ui.util.table; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JTable; +import java.awt.event.ActionEvent; + +/** + * Action to select next editable row in a table. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.8 + */ +public class MoveToNextEditableRowAction<M extends EditableTableModelSupport> extends AbstractSelectTableAction<M> { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = + LogFactory.getLog(MoveToNextEditableRowAction.class); + + protected MoveToNextEditableRowAction(M model, JTable table) { + super(model, table); + } + + public static <M extends EditableTableModelSupport> MoveToNextEditableRowAction<M> newAction(M model, JTable table) { + return new MoveToNextEditableRowAction<>(model, table); + } + + @Override + public void actionPerformed(ActionEvent e) { + int currentRow = getSelectedRow(); + int currentColumn = getSelectedColumn(); + + if (log.isDebugEnabled()) { + log.debug("Move to next row editable cell " + + getCellCoordinate(currentRow, currentColumn)); + } + + int rowCount = getRowCount(); + + if (currentRow < rowCount) { + // go to next cell + currentRow++; + boolean canSelect = true; + + // select next cell + if (currentRow >= rowCount) { + + if (log.isDebugEnabled()) { + log.debug("No next row"); + } + + if (isCreateNewRow(currentRow - 1)) { + + // create a new row in model + addNewRow(); + + } else { + canSelect = false; + } + } + + if (canSelect) { + doSelectCell(currentRow, currentColumn); + } + } + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/MoveToPreviousEditableCellAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/MoveToPreviousEditableCellAction.java new file mode 100644 index 0000000..c4a819e --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/MoveToPreviousEditableCellAction.java @@ -0,0 +1,80 @@ +package fr.ird.observe.application.swing.ui.util.table; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JTable; +import java.awt.event.ActionEvent; + +/** + * Action to select previous editable cell in a table. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.8 + */ +public class MoveToPreviousEditableCellAction<M extends EditableTableModelSupport> extends AbstractSelectTableAction<M> { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = + LogFactory.getLog(MoveToPreviousEditableCellAction.class); + + protected MoveToPreviousEditableCellAction(M model, JTable table) { + super(model, table); + } + + public static <M extends EditableTableModelSupport> MoveToPreviousEditableCellAction<M> newAction(M model, JTable table) { + return new MoveToPreviousEditableCellAction<>(model, table); + } + + @Override + public void actionPerformed(ActionEvent e) { + int currentRow = getSelectedRow(); + int currentColumn = getSelectedColumn(); + + if (log.isDebugEnabled()) { + log.debug("Move to previous editable cell, " + + getCellCoordinate(currentRow, currentColumn)); + } + + int columnCount = getColumnCount(); + + if (currentRow > 0 || currentColumn > 0) { + + // go to next cell + currentColumn--; + + // select next cell + if (currentColumn < 0) { + + currentColumn = columnCount - 1; + currentRow--; + } + + doSelectCell(currentRow, currentColumn); + } + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/MoveToPreviousEditableRowAction.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/MoveToPreviousEditableRowAction.java new file mode 100644 index 0000000..76c3896 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/MoveToPreviousEditableRowAction.java @@ -0,0 +1,71 @@ +package fr.ird.observe.application.swing.ui.util.table; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import javax.swing.JTable; +import java.awt.event.ActionEvent; + +/** + * Action to select previous editable row in a table. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.8 + */ +public class MoveToPreviousEditableRowAction<M extends EditableTableModelSupport> extends AbstractSelectTableAction<M> { + + private static final long serialVersionUID = 1L; + + /** Logger. */ + private static final Log log = + LogFactory.getLog(MoveToPreviousEditableRowAction.class); + + protected MoveToPreviousEditableRowAction(M model, JTable table) { + super(model, table); + } + + public static <M extends EditableTableModelSupport> MoveToPreviousEditableRowAction<M> newAction(M model, JTable table) { + return new MoveToPreviousEditableRowAction<>(model, table); + } + + @Override + public void actionPerformed(ActionEvent e) { + + int currentRow = getSelectedRow(); + int currentColumn = getSelectedColumn(); + + if (log.isDebugEnabled()) { + log.debug("Move to previous row editable cell " + + getCellCoordinate(currentRow, currentColumn)); + } + + if (currentRow > 0) { + + // go to next cell + currentRow--; + doSelectCell(currentRow, currentColumn); + } + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/ObserveBooleanTableCellRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/ObserveBooleanTableCellRenderer.java new file mode 100644 index 0000000..5ab6bf6 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/table/ObserveBooleanTableCellRenderer.java @@ -0,0 +1,93 @@ +package fr.ird.observe.application.swing.ui.util.table; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import javax.swing.Icon; +import javax.swing.JCheckBox; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.JTable; +import javax.swing.table.TableCellRenderer; +import java.awt.Color; +import java.awt.Component; +import java.util.function.Predicate; + +/** + * TODO A remonter dans JAXX. + * + * Created on 14/08/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 4.0.1.1 + */ +public class ObserveBooleanTableCellRenderer extends JCheckBox implements TableCellRenderer { + + private static final long serialVersionUID = 1L; + + protected final TableCellRenderer defaultDelegate; + + private final Predicate predicate; + + private static final Predicate<?> DEFAULT_PREDICATE = input -> (input != null && (Boolean) input); + + public ObserveBooleanTableCellRenderer(TableCellRenderer delegate, Predicate<?> predicate) { + this(delegate, null, predicate); + } + + public ObserveBooleanTableCellRenderer(TableCellRenderer delegate) { + //super(new BorderLayout()); + this(delegate, DEFAULT_PREDICATE); + + } + + public ObserveBooleanTableCellRenderer(TableCellRenderer delegate, Icon icon, Predicate<?> predicate) { + this.defaultDelegate = delegate; + this.predicate = predicate; + setOpaque(true); + setBorderPainted(true); + setHorizontalAlignment(JLabel.CENTER); + setIcon(icon); + } + + @Override + public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { + ((JComponent) defaultDelegate).setBackground(null); + JComponent render = (JComponent) defaultDelegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); + if (isSelected) { + setForeground(table.getSelectionForeground()); + setBackground(table.getSelectionBackground()); + } else { + setForeground(render.getForeground()); + setBackground(render.getBackground()); + if (row % 2 == 0) { + setBackground(Color.WHITE); + } + } + + boolean selectCheckBox = predicate.test(value); + setSelected(selectCheckBox); + + setBorder(render.getBorder()); + return this; + } +} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/tripMap/ObserveMapPane.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/tripMap/ObserveMapPane.java new file mode 100644 index 0000000..5283db7 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/tripMap/ObserveMapPane.java @@ -0,0 +1,366 @@ +package fr.ird.observe.application.swing.ui.util.tripMap; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.geotools.geometry.jts.ReferencedEnvelope; +import org.geotools.renderer.lite.RendererUtilities; +import org.geotools.styling.FeatureTypeStyle; +import org.geotools.styling.Rule; +import org.geotools.styling.Style; +import org.geotools.swing.JMapPane; +import org.geotools.swing.event.MapPaneAdapter; +import org.geotools.swing.event.MapPaneEvent; + +import java.awt.Color; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics; +import java.awt.Point; +import java.awt.Polygon; +import java.awt.geom.Point2D; +import java.awt.geom.Rectangle2D; +import java.awt.image.BufferedImage; +import java.util.List; + +import static org.nuiton.i18n.I18n.n; +import static org.nuiton.i18n.I18n.t; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class ObserveMapPane extends JMapPane { + + private static final long serialVersionUID = 1L; + private static final Log log = LogFactory.getLog(ObserveMapPane.class); + + protected static final int MARGIN = 10; + + protected static final int SCALE_HEIGHT = 15; + protected static final int SCALE_WIDTH_MAX = 200; + + protected static final int METERS_BY_MILES = 1852; + + protected int scaleWidth; + + protected String labelScaleUp; + + protected double rotation; + + public ObserveMapPane() { + labelScaleUp = "0 m"; + scaleWidth = 100; + rotation = 0; + addMapPaneListener(new MapPaneAdapter() { + @Override + public void onDisplayAreaChanged(MapPaneEvent ev) { + updateScale(); + } + }); + legendItems = Lists.newArrayList(); + + } + + + protected void updateScale() { + ReferencedEnvelope displayArea = getDisplayArea(); + double dpi = 2.54 / 100; // pour avoir l'echélle en metre/pixel + + try { + double meterPerPixel = RendererUtilities.calculateScale(displayArea, getWidth(), getHeight(), dpi); + + double maxWidthMeter = SCALE_WIDTH_MAX * meterPerPixel; + + double maxWidthMiles = maxWidthMeter / METERS_BY_MILES; + + int nbDigit = (int) Math.floor(Math.log10(maxWidthMiles)); + + int firstDigit = (int) Math.floor(maxWidthMiles / Math.pow(10, nbDigit)); // le premier chiffre significatif + + int useFirstDigit; + + if (firstDigit >= 5) { + useFirstDigit = 5; + } else if (firstDigit >= 2) { + useFirstDigit = 2; + } else { + useFirstDigit = 1; + } + + long scaleInMiles = useFirstDigit * (long) Math.pow(10, nbDigit); + + scaleWidth = (int) Math.round(scaleInMiles * METERS_BY_MILES / meterPerPixel); + + labelScaleUp = String.format("%,d " + t("observe.content.map.miles"), scaleInMiles); + + } catch (Exception e) { + if (log.isErrorEnabled()) { + log.error("error", e); + } + } + } + + protected void paintScale(Graphics graphics) { + graphics.setColor(Color.BLACK); + + FontMetrics fm = graphics.getFontMetrics(); + + Rectangle2D textArea = fm.getStringBounds(labelScaleUp, graphics); + + int labelLeft = getWidth() - MARGIN * 2 - scaleWidth - (int) textArea.getWidth(); + + graphics.drawString(labelScaleUp, labelLeft, getHeight() - MARGIN); + + int scalesEndX = getWidth() - MARGIN; + + int scaleStartX = scalesEndX - scaleWidth; + + int scalesEndY = getHeight() - MARGIN; + + int scaleStartY = scalesEndY - SCALE_HEIGHT; + + graphics.drawLine(scaleStartX, scaleStartY, scaleStartX, scalesEndY); + graphics.drawLine(scaleStartX, scalesEndY, scalesEndX, scalesEndY); + graphics.drawLine(scalesEndX, scalesEndY, scalesEndX, scaleStartY); + + } + + protected static int AXIS_LENGTH = 30; + + protected static int SUB_AXIS_LENGTH = 5; + + protected static int CENTER_MARGIN = 50; + + protected static int INTER_AXIS_TEXT = 3; + + protected static double FONT_SIZE = 12; + + + protected void paintCompass(Graphics graphics) { + + Point center = new Point(getWidth() - CENTER_MARGIN, CENTER_MARGIN); + + Font font = graphics.getFont(); + Font fontRatio = font.deriveFont((float) (FONT_SIZE)); + graphics.setFont(fontRatio); + + FontMetrics fm = graphics.getFontMetrics(); + + for (CardinalPoint cardinalPoint : CardinalPoint.values()) { + + Point2D direction = cardinalPoint.getDirection(rotation, AXIS_LENGTH, center); + + Point2D sommet1 = cardinalPoint.getDirection(rotation - Math.PI / 4, SUB_AXIS_LENGTH, center); + + Point2D sommet2 = cardinalPoint.getDirection(rotation + Math.PI / 4, SUB_AXIS_LENGTH, center); + + + Polygon polygon = new Polygon(); + polygon.addPoint((int) center.getX(), (int) center.getY()); + polygon.addPoint((int) direction.getX(), (int) direction.getY()); + polygon.addPoint((int) sommet2.getX(), (int) sommet2.getY()); + graphics.fillPolygon(polygon); + + graphics.drawLine((int) sommet1.getX(), (int) sommet1.getY(), (int) direction.getX(), (int) direction.getY()); + + Rectangle2D textArea = fm.getStringBounds(cardinalPoint.getLabel(), graphics); + + // on cherche la ditance entre le centre du text et sa bordure dans le direction donné + double l = cardinalPoint.distanceCenterBorder(rotation, textArea); + + Point2D textCenter = cardinalPoint.getDirection(rotation, AXIS_LENGTH + INTER_AXIS_TEXT + l, center); + + graphics.drawString( + cardinalPoint.getLabel(), + (int) (textCenter.getX() - textArea.getWidth() / 2), + (int) (textCenter.getY() + textArea.getHeight() / 2)); + } + + } + + + protected static int LEGEND_MARGIN = 3; + + protected List<ObserveMapPaneLegendItem> legendItems; + + public List<ObserveMapPaneLegendItem> getLegendItems() { + return legendItems; + } + + public void setLegendItems(List<ObserveMapPaneLegendItem> legendItems) { + this.legendItems = legendItems; + } + + protected void paintLegend(Graphics graphics) { + + if (legendItems != null) { + + int x = 0; + int y = getHeight() - ObserveMapPaneLegendItem.LEGEND_ITEM_HEIGHT * legendItems.size() - 2 * LEGEND_MARGIN; + + ObserverMapPanLegendDrawer drawer = new ObserverMapPanLegendDrawer(); + + FontMetrics fm = graphics.getFontMetrics(); + + int maxLabelWidth = 0; + + for (ObserveMapPaneLegendItem item : legendItems) { + Rectangle2D labelArea = fm.getStringBounds(item.getLabel(), graphics); + + maxLabelWidth = Math.max((int)labelArea.getWidth(), maxLabelWidth); + + } + + int legendWidth = ObserveMapPaneLegendItem.LEGEND_SYMBOL_WIDTH + maxLabelWidth + ObserveMapPaneLegendItem.LEGEND_MARGIN * 2; + + graphics.setColor(ObserveMapPaneLegendItem.LEGEND_BACKGROUND); + graphics.fillRect( + x, + y, + legendWidth, + LEGEND_MARGIN); + + y += LEGEND_MARGIN; + + for (ObserveMapPaneLegendItem item : legendItems) { + + graphics.setColor(ObserveMapPaneLegendItem.LEGEND_BACKGROUND); + graphics.fillRect( + x, + y, + legendWidth, + ObserveMapPaneLegendItem.LEGEND_ITEM_HEIGHT); + + BufferedImage symbole = new BufferedImage( + ObserveMapPaneLegendItem.LEGEND_SYMBOL_WIDTH, + ObserveMapPaneLegendItem.LEGEND_ITEM_HEIGHT, + BufferedImage.TYPE_INT_ARGB); + + Style style = item.getStyle(); + + for (FeatureTypeStyle featureTypeStyle : style.featureTypeStyles()) { + + for (Rule rule : featureTypeStyle.rules()) { + + if (rule.getFilter().evaluate(item.getSimpleFeature())) { + + drawer.drawDirect(symbole, item.getSimpleFeature(), rule); + + } + } + } + + graphics.drawImage(symbole, x + LEGEND_MARGIN, y, null); + + graphics.setColor(Color.BLACK); + + int labelMarginBottom = ((ObserveMapPaneLegendItem.LEGEND_ITEM_HEIGHT - fm.getHeight()) / 2) + fm.getDescent(); + + graphics.drawString(item.getLabel(), + x + LEGEND_MARGIN + ObserveMapPaneLegendItem.LEGEND_SYMBOL_WIDTH, + y + ObserveMapPaneLegendItem.LEGEND_ITEM_HEIGHT - labelMarginBottom); + + y += ObserveMapPaneLegendItem.LEGEND_ITEM_HEIGHT; + + } + + graphics.setColor(ObserveMapPaneLegendItem.LEGEND_BACKGROUND); + graphics.fillRect( + x, + y, + legendWidth, + LEGEND_MARGIN); + + } + + } + + + + @Override + public void paint(Graphics graphics) { + + super.paint(graphics); + + paintScale(graphics); + + paintCompass(graphics); + + paintLegend(graphics); + + } + + protected enum CardinalPoint { + NORTH(-1, 0, 0, -1, n("observe.content.map.north")), + SOUTH( 1, 0, 0, 1, n("observe.content.map.south")), + WEST ( 0, -1, 1, 0, n("observe.content.map.west")), + EST ( 0, 1, -1, 0, n("observe.content.map.east")); + + protected int matrix00; + protected int matrix01; + protected int matrix10; + protected int matrix11; + protected String label; + + CardinalPoint(int matrix00, int matrix01, int matrix10, int matrix11, String label) { + this.matrix00 = matrix00; + this.matrix01 = matrix01; + this.matrix10 = matrix10; + this.matrix11 = matrix11; + this.label = label; + } + + public Point2D.Double getDirection(double angle, double length, Point center) { + + double x = Math.sin(angle) * length; + double y = Math.cos(angle) * length; + + double deltaX = matrix00 * x + matrix01 * y; + double deltaY = matrix10 * x + matrix11 * y; + Point2D.Double result = new Point2D.Double(center.getX() + deltaX, center.getY() + deltaY); + + return result; + } + + // on cherche la ditance entre le centre du text et sa bordure dans le direction donné + public double distanceCenterBorder(double angle, Rectangle2D textArea) { + + double x = Math.sin(angle); + double y = Math.cos(angle); + + double deltaW = Math.abs(textArea.getWidth() / 2 / (matrix00 * x + matrix01 * y)); + double deltaH = Math.abs(textArea.getHeight() / 2 / (matrix10 * x + matrix11 * y)); + + double delta = Math.min(deltaH, deltaW); + + return delta; + } + + public String getLabel() { + return t(label); + } + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/tripMap/ObserveMapPaneLegendItem.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/tripMap/ObserveMapPaneLegendItem.java new file mode 100644 index 0000000..ba15c44 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/tripMap/ObserveMapPaneLegendItem.java @@ -0,0 +1,90 @@ +package fr.ird.observe.application.swing.ui.util.tripMap; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.vividsolutions.jts.geom.Coordinate; +import org.geotools.styling.Style; +import org.opengis.feature.simple.SimpleFeature; + +import java.awt.Color; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class ObserveMapPaneLegendItem { + + protected static final int LEGEND_ITEM_HEIGHT = 20; + protected static final int LEGEND_SYMBOL_WIDTH = 50; + protected static final int LEGEND_MARGIN = 5; + protected static final Color LEGEND_BACKGROUND = new Color(1f, 1f, 1f, 0.8f); + + + public static Coordinate[] lineCoordinates() { + Coordinate[] coordinates = new Coordinate[2]; + coordinates[0] = new Coordinate(LEGEND_MARGIN, LEGEND_ITEM_HEIGHT / 2); + coordinates[1] = new Coordinate(LEGEND_SYMBOL_WIDTH - LEGEND_MARGIN, LEGEND_ITEM_HEIGHT / 2); + return coordinates; + } + + public static Coordinate pointCoordinates() { + Coordinate coordinate = new Coordinate(LEGEND_SYMBOL_WIDTH / 2, LEGEND_ITEM_HEIGHT / 2); + return coordinate; + } + + + protected SimpleFeature simpleFeature; + + protected Style style; + + protected String label; + + public ObserveMapPaneLegendItem(SimpleFeature simpleFeature, Style style, String label) { + this.simpleFeature = simpleFeature; + this.style = style; + this.label = label; + } + + public SimpleFeature getSimpleFeature() { + return simpleFeature; + } + + public void setSimpleFeature(SimpleFeature simpleFeature) { + this.simpleFeature = simpleFeature; + } + + public Style getStyle() { + return style; + } + + public void setStyle(Style style) { + this.style = style; + } + + public String getLabel() { + return label; + } + + public void setLabel(String label) { + this.label = label; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/tripMap/ObserverMapPanLegendDrawer.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/tripMap/ObserverMapPanLegendDrawer.java new file mode 100644 index 0000000..643fa6a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/tripMap/ObserverMapPanLegendDrawer.java @@ -0,0 +1,111 @@ +package fr.ird.observe.application.swing.ui.util.tripMap; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.vividsolutions.jts.geom.Geometry; +import org.geotools.geometry.jts.LiteShape; +import org.geotools.legend.Drawer; +import org.geotools.styling.LineSymbolizer; +import org.geotools.styling.Rule; +import org.geotools.styling.SLD; +import org.geotools.styling.Symbolizer; +import org.opengis.feature.simple.SimpleFeature; + +import java.awt.BasicStroke; +import java.awt.Color; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.Stroke; +import java.awt.geom.AffineTransform; +import java.awt.image.BufferedImage; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class ObserverMapPanLegendDrawer { + + protected final Drawer drawer; + + + public ObserverMapPanLegendDrawer() { + drawer = Drawer.create(); + + } + + public void drawDirect(BufferedImage bi, SimpleFeature feature, Rule rule) { + AffineTransform affineTransform = new AffineTransform(); + + LiteShape shape = new LiteShape(null, affineTransform, false); + for (Symbolizer symbolizer : rule.getSymbolizers()) { + if (symbolizer instanceof LineSymbolizer) { + LineSymbolizer lineSymbolizer = (LineSymbolizer) symbolizer; + + Geometry geometry = findGeometry(feature, lineSymbolizer); + if (geometry != null) { + + Graphics graphics = bi.getGraphics(); + Graphics2D g = (Graphics2D) graphics; + + shape.setGeometry(geometry); + + + Color c = SLD.color(lineSymbolizer); + int w = SLD.width(lineSymbolizer); + float[] lineDash = SLD.lineDash(lineSymbolizer); + if (c != null && w > 0) { + g.setColor(c); + + Stroke str = new BasicStroke( + w, + BasicStroke.CAP_SQUARE, + BasicStroke.JOIN_MITER, + 10.0f, lineDash, 0.0f + ); + g.setStroke(str); + + g.draw(shape); + } + } + } else { + drawer.drawFeature(bi, feature, affineTransform, false, symbolizer, null, shape); + } + + } + + + } + + protected Geometry findGeometry(SimpleFeature feature, LineSymbolizer lineSymbolizer) { + String geomName = lineSymbolizer.getGeometryPropertyName(); + + Geometry geom; + if (geomName == null) { + geom = (Geometry) feature.getDefaultGeometry(); + } else { + geom = (Geometry) feature.getAttribute(geomName); + } + return geom; + } + + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/tripMap/TripMapContentBuilder.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/tripMap/TripMapContentBuilder.java new file mode 100644 index 0000000..52582be --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/tripMap/TripMapContentBuilder.java @@ -0,0 +1,477 @@ +package fr.ird.observe.application.swing.ui.util.tripMap; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.ImmutableSet; +import com.google.common.collect.Lists; +import com.google.common.collect.Sets; +import com.vividsolutions.jts.geom.Coordinate; +import com.vividsolutions.jts.geom.GeometryFactory; +import com.vividsolutions.jts.geom.LineString; +import com.vividsolutions.jts.geom.Point; +import com.vividsolutions.jts.geom.Polygon; +import fr.ird.observe.application.swing.ObserveSwingTechnicalException; +import fr.ird.observe.services.dto.TripMapPointDto; +import fr.ird.observe.services.dto.constants.TripMapPointType; +import fr.ird.observe.services.util.I18nEnumUtil; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.time.DateUtils; +import org.geotools.data.FileDataStore; +import org.geotools.data.FileDataStoreFinder; +import org.geotools.data.simple.SimpleFeatureSource; +import org.geotools.factory.CommonFactoryFinder; +import org.geotools.feature.DefaultFeatureCollection; +import org.geotools.feature.simple.SimpleFeatureBuilder; +import org.geotools.feature.simple.SimpleFeatureTypeBuilder; +import org.geotools.geometry.jts.JTSFactoryFinder; +import org.geotools.map.FeatureLayer; +import org.geotools.map.Layer; +import org.geotools.map.MapContent; +import org.geotools.referencing.CRS; +import org.geotools.styling.NamedLayer; +import org.geotools.styling.SLD; +import org.geotools.styling.SLDParser; +import org.geotools.styling.Style; +import org.geotools.styling.StyleFactory; +import org.geotools.styling.StyledLayer; +import org.geotools.styling.StyledLayerDescriptor; +import org.geotools.styling.UserLayer; +import org.opengis.feature.simple.SimpleFeature; +import org.opengis.feature.simple.SimpleFeatureType; +import org.opengis.referencing.FactoryException; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import static org.nuiton.i18n.I18n.t; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class TripMapContentBuilder { + + public static final String TRIP_LINES_LAYER_NAME = "Trip lines"; + public static final String TRIP_LONGLINE_FISHING_ZONE_LAYER_NAME = "Trip longline zone"; + public static final String TRIP_LONGLINE_LINE_LAYER_NAME = "Trip longline line"; + public static final String TRIP_POINTS_LAYER_NAME = "Trip points"; + + protected static final Set<TripMapPointType> TRIP_MAP_POINT_TYPES_IN_LEGEND = ImmutableSet.of( + TripMapPointType.seineActivityInHarbour, + TripMapPointType.seineActivityWithFreeSchoolType, + TripMapPointType.seineActivityWithObjectSchoolType, + TripMapPointType.longlineActivityInHarbour, + TripMapPointType.longlineActivityWithSettingStart, + TripMapPointType.longlineActivityWithSettingEnd, + TripMapPointType.longlineActivityWithHaulingStart, + TripMapPointType.longlineActivityWithHaulingEnd, + TripMapPointType.longlineActivityWithStation, + TripMapPointType.longlineActivityWithInteraction); + + public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM"); + + protected StyledLayerDescriptor styledLayerDescriptor; + protected final MapContent mapContent; + protected final List<ObserveMapPaneLegendItem> legendItems; + + public TripMapContentBuilder() { + mapContent = new MapContent(); + legendItems = Lists.newArrayList(); + } + + public MapContent getMapContent() { + return mapContent; + } + + public List<ObserveMapPaneLegendItem> getLegendItems() { + return legendItems; + } + + public void setStyledLayerDescriptor(File styleFile) throws FileNotFoundException { + + StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory(null); + + SLDParser stylereader = new SLDParser(styleFactory, styleFile); + + styledLayerDescriptor = stylereader.parseSLD(); + } + + public void addLayer(File layerFile) throws IOException { + FileDataStore store = FileDataStoreFinder.getDataStore(layerFile); + SimpleFeatureSource featureSource = store.getFeatureSource(); + Style style = SLD.createSimpleStyle(featureSource.getSchema()); + style = findStyle(styledLayerDescriptor, store.getNames().get(0).getLocalPart(), null, style); + Layer layer = new FeatureLayer(featureSource, style, layerFile.getName()); + mapContent.addLayer(layer); + } + + public void addTripLine(List<TripMapPointDto> tripMapPoints) throws FactoryException { + + GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); + + SimpleFeatureTypeBuilder lineFeatureTypeBuilder = new SimpleFeatureTypeBuilder(); + lineFeatureTypeBuilder.setName("lineBuilder"); + lineFeatureTypeBuilder.setCRS(CRS.decode("EPSG:4326", true)); + lineFeatureTypeBuilder.add("line", LineString.class); + lineFeatureTypeBuilder.add("label", String.class); + lineFeatureTypeBuilder.add("type", String.class); + + SimpleFeatureType lineFeatureType = lineFeatureTypeBuilder.buildFeatureType(); + SimpleFeatureBuilder lineBuilder = new SimpleFeatureBuilder(lineFeatureType); + + DefaultFeatureCollection linesFeatures = new DefaultFeatureCollection(); + + List<Coordinate> coordinatesByDay = null; + + TripMapPointDto previousPoint = null; + + for (TripMapPointDto point : tripMapPoints) { + if (previousPoint == null) { + coordinatesByDay = Lists.newLinkedList(); + } else if (!DateUtils.isSameDay(previousPoint.getTime(), point.getTime())) { + + if (coordinatesByDay.size() > 1) { + LineString line = geometryFactory.createLineString(coordinatesByDay.toArray(new Coordinate[0])); + lineBuilder.add(line); + lineBuilder.add(DATE_FORMAT.format(previousPoint.getTime())); + lineBuilder.add("tripDay"); + SimpleFeature feature = lineBuilder.buildFeature(null); + + linesFeatures.add(feature); + } + + + Coordinate[] coordinates = { + new Coordinate(previousPoint.getLongitude(), previousPoint.getLatitude()), + new Coordinate(point.getLongitude(), point.getLatitude()), + }; + LineString lineBetweenTwoDays = geometryFactory.createLineString(coordinates); + lineBuilder.add(lineBetweenTwoDays); + lineBuilder.add(DateFormat.getDateInstance().format(previousPoint.getTime())); + lineBuilder.add("tripBetweenTwoDays"); + linesFeatures.add(lineBuilder.buildFeature(null)); + + coordinatesByDay = Lists.newLinkedList(); + } + + Coordinate coordinate = new Coordinate(point.getLongitude(), point.getLatitude()); + coordinatesByDay.add(coordinate); + + previousPoint = point; + } + + if (coordinatesByDay != null && coordinatesByDay.size() > 1) { + LineString line = geometryFactory.createLineString(coordinatesByDay.toArray(new Coordinate[0])); + lineBuilder.add(line); + lineBuilder.add(DATE_FORMAT.format(previousPoint.getTime())); + lineBuilder.add("tripDay"); + linesFeatures.add(lineBuilder.buildFeature(null)); + } + + Style styleLines = findStyle(styledLayerDescriptor, TRIP_LINES_LAYER_NAME, null); + + if (! linesFeatures.isEmpty()) { + Layer layerLines = new FeatureLayer(linesFeatures, styleLines, TRIP_LINES_LAYER_NAME); + mapContent.addLayer(layerLines); + } + + + // add line in legend + LineString line = geometryFactory.createLineString(ObserveMapPaneLegendItem.lineCoordinates()); + lineBuilder.add(line); + lineBuilder.add(""); + lineBuilder.add("tripDay"); + + ObserveMapPaneLegendItem legendTripDay = new ObserveMapPaneLegendItem( + lineBuilder.buildFeature(null), + styleLines, + t("observe.content.map.legend.tripDay")); + legendItems.add(legendTripDay); + + lineBuilder.add(line); + lineBuilder.add(""); + lineBuilder.add("tripBetweenTwoDays"); + ObserveMapPaneLegendItem legendTripBetweenTwoDays = new ObserveMapPaneLegendItem( + lineBuilder.buildFeature(null), + styleLines, + t("observe.content.map.legend.tripBetweenTwoDays")); + legendItems.add(legendTripBetweenTwoDays); + + } + + public void addLonglineFishingZone(List<TripMapPointDto> tripMapPoints) throws FactoryException { + GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); + + SimpleFeatureTypeBuilder polygonFeatureTypeBuilder = new SimpleFeatureTypeBuilder(); + polygonFeatureTypeBuilder.setName("longlineFishingZoneBuilder"); + polygonFeatureTypeBuilder.setCRS(CRS.decode("EPSG:4326", true)); + polygonFeatureTypeBuilder.add("zone", Polygon.class); + polygonFeatureTypeBuilder.add("label", String.class); + polygonFeatureTypeBuilder.add("type", String.class); + + SimpleFeatureType polygonFeatureType = polygonFeatureTypeBuilder.buildFeatureType(); + SimpleFeatureBuilder polygonBuilder = new SimpleFeatureBuilder(polygonFeatureType); + + DefaultFeatureCollection polygonsFeatures = new DefaultFeatureCollection(); + + for (int indexPoint = 3; indexPoint < tripMapPoints.size(); indexPoint++) { + if (tripMapPoints.get(indexPoint).getType().equals(TripMapPointType.longlineActivityWithHaulingEnd) + && tripMapPoints.get(indexPoint - 1).getType().equals(TripMapPointType.longlineActivityWithHaulingStart) + && tripMapPoints.get(indexPoint - 2).getType().equals(TripMapPointType.longlineActivityWithSettingEnd) + && tripMapPoints.get(indexPoint - 3).getType().equals(TripMapPointType.longlineActivityWithSettingStart)) { + + Coordinate[] coordinates = { + new Coordinate(tripMapPoints.get(indexPoint - 3).getLongitude(), tripMapPoints.get(indexPoint - 3).getLatitude()), + new Coordinate(tripMapPoints.get(indexPoint - 2).getLongitude(), tripMapPoints.get(indexPoint - 2).getLatitude()), + new Coordinate(tripMapPoints.get(indexPoint - 1).getLongitude(), tripMapPoints.get(indexPoint - 1).getLatitude()), + new Coordinate(tripMapPoints.get(indexPoint).getLongitude(), tripMapPoints.get(indexPoint).getLatitude()), + new Coordinate(tripMapPoints.get(indexPoint - 3).getLongitude(), tripMapPoints.get(indexPoint - 3).getLatitude()) + }; + + + Polygon polygon = geometryFactory.createPolygon(coordinates); + //polygon = (Polygon) polygon.convexHull(); // permet de transformer un poliqgone croisé en polygon convex + polygonBuilder.add(polygon); + polygonBuilder.add(DATE_FORMAT.format(tripMapPoints.get(indexPoint - 3).getTime())); + polygonBuilder.add("longlineFishingZone"); + SimpleFeature feature = polygonBuilder.buildFeature(null); + polygonsFeatures.add(feature); + + } + } + + if (!polygonsFeatures.isEmpty()) { + Style styleLines = findStyle(styledLayerDescriptor, TRIP_LONGLINE_FISHING_ZONE_LAYER_NAME, null); + Layer layerLines = new FeatureLayer(polygonsFeatures, styleLines, TRIP_LONGLINE_FISHING_ZONE_LAYER_NAME); + mapContent.addLayer(layerLines); + } + } + + public void addLonglineLine(List<TripMapPointDto> tripMapPoints) throws FactoryException { + GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); + + SimpleFeatureTypeBuilder lineFeatureTypeBuilder = new SimpleFeatureTypeBuilder(); + lineFeatureTypeBuilder.setName("longlineSettingBuilder"); + lineFeatureTypeBuilder.setCRS(CRS.decode("EPSG:4326", true)); + lineFeatureTypeBuilder.add("line", LineString.class); + lineFeatureTypeBuilder.add("type", String.class); + + SimpleFeatureType lineFeatureType = lineFeatureTypeBuilder.buildFeatureType(); + SimpleFeatureBuilder lineBuilder = new SimpleFeatureBuilder(lineFeatureType); + + DefaultFeatureCollection linesFeatures = new DefaultFeatureCollection(); + + List<Coordinate> defaultLineCoordinates = Lists.newLinkedList(); + + for (int indexPoint = 0; indexPoint < tripMapPoints.size(); indexPoint++) { + if (indexPoint > 1 && tripMapPoints.get(indexPoint).getType().equals(TripMapPointType.longlineActivityWithSettingEnd) + && tripMapPoints.get(indexPoint - 1).getType().equals(TripMapPointType.longlineActivityWithSettingStart) + || tripMapPoints.get(indexPoint).getType().equals(TripMapPointType.longlineActivityWithHaulingEnd) + && tripMapPoints.get(indexPoint - 1).getType().equals(TripMapPointType.longlineActivityWithHaulingStart)) { + + Coordinate[] coordinates = { + new Coordinate(tripMapPoints.get(indexPoint - 1).getLongitude(), tripMapPoints.get(indexPoint - 1).getLatitude()), + new Coordinate(tripMapPoints.get(indexPoint).getLongitude(), tripMapPoints.get(indexPoint).getLatitude()), + }; + + boolean setting = tripMapPoints.get(indexPoint).getType().equals(TripMapPointType.longlineActivityWithSettingEnd); + LineString lineString = geometryFactory.createLineString(coordinates); + lineBuilder.add(lineString); + lineBuilder.add(setting ? "setting" : "hauling"); + SimpleFeature feature = lineBuilder.buildFeature(null); + linesFeatures.add(feature); + + defaultLineCoordinates.clear(); + } + + if (! (tripMapPoints.get(indexPoint).getType().equals(TripMapPointType.longlineActivityWithSettingEnd) + || tripMapPoints.get(indexPoint).getType().equals(TripMapPointType.longlineActivityWithHaulingStart))) { + + defaultLineCoordinates.add(new Coordinate(tripMapPoints.get(indexPoint).getLongitude(), tripMapPoints.get(indexPoint).getLatitude())); + + } + + if ((tripMapPoints.get(indexPoint).getType().equals(TripMapPointType.longlineActivityWithSettingStart) + || indexPoint == tripMapPoints.size() - 1) && defaultLineCoordinates.size() > 1) { + + LineString lineString = geometryFactory.createLineString(defaultLineCoordinates.toArray( new Coordinate[0])); + lineBuilder.add(lineString); + lineBuilder.add("trip"); + SimpleFeature feature = lineBuilder.buildFeature(null); + linesFeatures.add(feature); + + defaultLineCoordinates.clear(); + + } + + + + } + + Style styleLines = findStyle(styledLayerDescriptor, TRIP_LONGLINE_LINE_LAYER_NAME, null); + if (!linesFeatures.isEmpty()) { + Layer layerLines = new FeatureLayer(linesFeatures, styleLines, TRIP_LONGLINE_LINE_LAYER_NAME); + mapContent.addLayer(layerLines); + } + + // add line in legend + LineString line = geometryFactory.createLineString(ObserveMapPaneLegendItem.lineCoordinates()); + lineBuilder.add(line); + lineBuilder.add("setting"); + + ObserveMapPaneLegendItem legendTripDay = new ObserveMapPaneLegendItem( + lineBuilder.buildFeature(null), + styleLines, + t("observe.content.map.legend.setting")); + legendItems.add(legendTripDay); + + line = geometryFactory.createLineString(ObserveMapPaneLegendItem.lineCoordinates()); + lineBuilder.add(line); + lineBuilder.add("hauling"); + + legendTripDay = new ObserveMapPaneLegendItem( + lineBuilder.buildFeature(null), + styleLines, + t("observe.content.map.legend.hauling")); + legendItems.add(legendTripDay); + + + } + + + public void addPoints(List<TripMapPointDto> tripMapPoints) throws FactoryException { + + GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); + + SimpleFeatureTypeBuilder pointFeatureTypeBuilder = new SimpleFeatureTypeBuilder(); + pointFeatureTypeBuilder.setName("point Builder"); + pointFeatureTypeBuilder.setCRS(CRS.decode("EPSG:4326", true)); + pointFeatureTypeBuilder.add("point", Point.class); + pointFeatureTypeBuilder.add("label", String.class); + pointFeatureTypeBuilder.add("pointType", String.class); + + SimpleFeatureType pointFeatureType = pointFeatureTypeBuilder.buildFeatureType(); + SimpleFeatureBuilder pointBuilder = new SimpleFeatureBuilder(pointFeatureType); + + DefaultFeatureCollection pointsFeatures = new DefaultFeatureCollection(); + + Style stylePoints = findStyle(styledLayerDescriptor, TRIP_POINTS_LAYER_NAME, null); + + Set<TripMapPointType> pointTypeInLegend = Sets.newHashSet(); + + for (TripMapPointDto tripMapPoint : tripMapPoints) { + Coordinate coordinate = new Coordinate(tripMapPoint.getLongitude(), tripMapPoint.getLatitude()); + + TripMapPointType type = tripMapPoint.getType(); + + Point point = geometryFactory.createPoint(coordinate); + pointBuilder.add(point); + pointBuilder.add(DATE_FORMAT.format(tripMapPoint.getTime())); + pointBuilder.add(type.name()); + pointsFeatures.add(pointBuilder.buildFeature(null)); + + // add point in legend + if (TRIP_MAP_POINT_TYPES_IN_LEGEND.contains(type) && ! pointTypeInLegend.contains(type)) { + point = geometryFactory.createPoint(ObserveMapPaneLegendItem.pointCoordinates()); + pointBuilder.add(point); + pointBuilder.add(""); + pointBuilder.add(type.name()); + + ObserveMapPaneLegendItem legendPoint = new ObserveMapPaneLegendItem( + pointBuilder.buildFeature(null), + stylePoints, + I18nEnumUtil.getLabel(type)); + legendItems.add(legendPoint); + pointTypeInLegend.add(type); + } + + } + + if (! pointsFeatures.isEmpty()) { + Layer pointsLayer = new FeatureLayer(pointsFeatures, stylePoints, TRIP_POINTS_LAYER_NAME); + mapContent.addLayer(pointsLayer); + } + + } + + + protected Style findStyle(StyledLayerDescriptor styledLayerDescriptor, final String layerName, String styleName, Style defaultStyle) { + + Optional<StyledLayer> styledLayerOptional = styledLayerDescriptor.layers().stream().filter( input -> input.getName().equals(layerName)).findFirst(); + + Style style = defaultStyle; + + if (styledLayerOptional.isPresent()) { + + StyledLayer styledLayer = styledLayerOptional.get(); + + Style[] styles = new Style[0]; + + if (styledLayer instanceof UserLayer) { + + styles = ((UserLayer) styledLayer).getUserStyles(); + + } else if (styledLayer instanceof NamedLayer) { + + styles = ((NamedLayer) styledLayer).getStyles(); + + } + + if (styles.length == 1) { + + style = styles[0]; + + } else { + + for (Style styleTmp : styles) { + + if (StringUtils.isBlank(styleName) && styleTmp.isDefault() + || styleTmp.getName().equals(styleName)) { + + style = styleTmp; + } + } + } + } + + return style; + + } + + protected Style findStyle(StyledLayerDescriptor styledLayerDescriptor, final String layerName, String styleName) { + + Style style = findStyle(styledLayerDescriptor, layerName, styleName, null); + + if (style == null) { + throw new ObserveSwingTechnicalException(String.format("No style found for layer name '%s' and style name '%s'", layerName, styleName)); + } + return style; + + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/tripMap/TripMapUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/tripMap/TripMapUI.jaxx new file mode 100644 index 0000000..27c50f2 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/tripMap/TripMapUI.jaxx @@ -0,0 +1,53 @@ +<!-- + #%L + ObServe :: Swing + %% + Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + %% + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as + published by the Free Software Foundation, either version 3 of the + License, or (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public + License along with this program. If not, see + <http://www.gnu.org/licenses/gpl-3.0.html>. + #L% + --> +<JPanel id="tripMap" + layout="{new CardLayout()}"> + + <import> + java.awt.CardLayout + fr.ird.observe.application.swing.ui.util.tripMap.ObserveMapPane + static org.nuiton.i18n.I18n.n + </import> + + <TripMapUIHandler id='handler' initializer='TripMapUIHandler.newHandler(this)'/> + + <script><![CDATA[ + +void $afterCompleteSetup() { + getHandler().initUI(); +} + +]]> + </script> + + <JPopupMenu id='mapPopupMenu'> + <JMenuItem id='zoomIt' onActionPerformed='getHandler().zoomIt()'/> + <JMenuItem id='exportPng' onActionPerformed='getHandler().exportPng()'/> + </JPopupMenu> + + <JLabel id="waitLoadingLabel"/> + + <ObserveMapPane id='observeMapPane' + constraints="BorderLayout.CENTER"/> + + +</JPanel> \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/tripMap/TripMapUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/tripMap/TripMapUI.jcss similarity index 100% rename from observe-application-swing/src/main/java/fr/ird/observe/ui/util/tripMap/TripMapUI.jcss rename to observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/tripMap/TripMapUI.jcss diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/tripMap/TripMapUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/tripMap/TripMapUIHandler.java new file mode 100644 index 0000000..441547f --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/ui/util/tripMap/TripMapUIHandler.java @@ -0,0 +1,363 @@ +package fr.ird.observe.application.swing.ui.util.tripMap; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Lists; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.ObserveSwingTechnicalException; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.services.dto.IdDtos; +import fr.ird.observe.services.dto.TripMapDto; +import fr.ird.observe.services.dto.TripMapPointDto; +import fr.ird.observe.application.swing.ui.UIHelper; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.geotools.geometry.DirectPosition2D; +import org.geotools.geometry.jts.ReferencedEnvelope; +import org.geotools.swing.JMapPane; +import org.geotools.swing.event.MapPaneEvent; +import org.geotools.swing.event.MapPaneListener; + +import javax.imageio.ImageIO; +import java.awt.CardLayout; +import java.awt.Point; +import java.awt.event.MouseEvent; +import java.awt.event.MouseListener; +import java.awt.event.MouseMotionListener; +import java.awt.event.MouseWheelEvent; +import java.awt.event.MouseWheelListener; +import java.awt.geom.AffineTransform; +import java.awt.geom.Point2D; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.util.List; + +import static org.nuiton.i18n.I18n.t; + +/** + * @author Sylvain Bavencoff - bavencoff@codelutin.com + */ +public class TripMapUIHandler { + + public static final double ZOOM_STEP_RATIO = 0.1; + + public static TripMapUIHandler newHandler(TripMapUI view) { + return new TripMapUIHandler(view); + } + + private static final Log log = LogFactory.getLog(TripMapUIHandler.class); + + protected final TripMapUI view; + + private ObserveSwingApplicationConfig config; + protected ReferencedEnvelope tripArea; + + protected boolean rendererRunning; + + public TripMapUIHandler(TripMapUI view) { + this.view = view; + } + + public void initUI() { + + ObserveMapPane mapPane = getObserveMapPane(); + + MouseMapListener mouseMapListener = new MouseMapListener(); + mapPane.addMouseWheelListener(mouseMapListener); + mapPane.addMouseMotionListener(mouseMapListener); + mapPane.addMouseListener(mouseMapListener); + mapPane.addMapPaneListener(new TripMapListener()); + + mapPane.setComponentPopupMenu(view.getMapPopupMenu()); + + rendererRunning = false; + + } + + public void setConfig(ObserveSwingApplicationConfig config) { + this.config = config; + + JMapPane mapPane = getObserveMapPane(); + mapPane.setBackground(config.getMapBackgroundColor()); + } + + protected ObserveMapPane getObserveMapPane() { + return view.getObserveMapPane(); + } + + public void doOpenMap(TripMapDto tripMapDto) { + + try { + ((CardLayout) view.getLayout()).first(view); + ObserveSwingApplicationContext.get().getMainUI().setBusy(true); + + ObserveMapPane mapPane = getObserveMapPane(); + + if (mapPane.getMapContent() != null) { + // appeler pour libéré les listeners + mapPane.getMapContent().dispose(); + } + + List<TripMapPointDto> tripMapPoints = Lists.newArrayList(tripMapDto.getPoints()); + + + TripMapContentBuilder mapContentBuilder = new TripMapContentBuilder(); + mapContentBuilder.setStyledLayerDescriptor(config.getMapStyleFile()); + + for (File layerFile : config.getMapLayerFiles()) { + mapContentBuilder.addLayer(layerFile); + } + + if (IdDtos.isSeineId(tripMapDto.getId())) { + + mapContentBuilder.addTripLine(tripMapPoints); + + } else if (IdDtos.isLonglineId(tripMapDto.getId())) { + + mapContentBuilder.addLonglineFishingZone(tripMapPoints); + mapContentBuilder.addLonglineLine(tripMapPoints); + + } + + mapContentBuilder.addPoints(tripMapPoints); + + // set zoom + tripArea = new ReferencedEnvelope(); + for (TripMapPointDto point : tripMapPoints) { + tripArea.expandToInclude(new DirectPosition2D(point.getLongitude(), point.getLatitude())); + } + tripArea.expandBy(1.1); + + mapPane.setMapContent(mapContentBuilder.getMapContent()); + mapPane.setLegendItems(mapContentBuilder.getLegendItems()); + + } catch (Exception e) { + throw new ObserveSwingTechnicalException("Unable to load trip map activity points", e); + } finally { + ObserveSwingApplicationContext.get().getMainUI().setBusy(false); + } + + } + + public void doCloseMap() { + ((CardLayout) view.getLayout()).first(view); + } + + public void zoomIt() { + if (! tripArea.isEmpty()) { + JMapPane mapPane = getObserveMapPane(); + mapPane.setDisplayArea(tripArea); + } + } + + public void exportPng() { + + File file = UIHelper.chooseFile( + view, + t("observe.content.map.export.chooseFile.title"), + t("observe.content.map.export.chooseFile.ok"), + null, + "^.+\\.png|.+\\.PNG$", + t("observe.content.map.export.chooseFile.png")); + + if (file != null && UIHelper.confirmOverwriteFileIfExist(view, file)) { + + BufferedImage im = new BufferedImage(view.getWidth(), view.getHeight(), BufferedImage.TYPE_INT_ARGB); + view.paint(im.getGraphics()); + try { + ImageIO.write(im, "PNG", file); + } catch (IOException e) { + throw new ObserveSwingTechnicalException("unable to export map ", e); + } + + UIHelper.displayInfo(t("observe.content.map.export.success", file)); + } + } + + protected double zoomRatio = 1; + protected Point zoomCenter; + + protected void zoomApply() { + if (zoomRatio != 1 && ! rendererRunning) { + + JMapPane mapPane = getObserveMapPane(); + + ReferencedEnvelope displayArea = mapPane.getDisplayArea(); + + double deltaWidth = displayArea.getWidth() * (zoomRatio -1); + double deltaHeight = displayArea.getHeight() * (zoomRatio - 1); + + double ratioLeft = zoomCenter.getX() * 1d / mapPane.getWidth(); + + // l'axe de Y est inversé entre le référentiel du composant swing et le référentiel géographique + double ratioTop = 1 - (zoomCenter.getY() * 1d / mapPane.getHeight()); + + double deltaLeft = deltaWidth * ratioLeft; + double deltaRight = deltaLeft - deltaWidth; + + double deltaTop = deltaHeight * ratioTop; + double deltaBottom = deltaTop - deltaHeight; + + if (log.isDebugEnabled()) { + log.debug(String.format("Map mouse zoom (zoom ratio : %s, deltaLeft : %s, deltaRight : %s, deltaTop : %s, deltaBottom : %s)", + zoomRatio, deltaLeft, deltaRight, deltaRight, deltaBottom)); + } + + ReferencedEnvelope newDisplayArea = new ReferencedEnvelope( + displayArea.getMinX() + deltaLeft, + displayArea.getMaxX() + deltaRight, + displayArea.getMinY() + deltaTop, + displayArea.getMaxY() + deltaBottom, + displayArea.getCoordinateReferenceSystem() + ); + + mapPane.setDisplayArea(newDisplayArea); + + zoomRatio = 1; + + } + + } + + private class MouseMapListener implements MouseWheelListener, MouseListener, MouseMotionListener { + + @Override + public void mouseWheelMoved(MouseWheelEvent e) { + int notches = e.getWheelRotation(); + zoomRatio = zoomRatio * (1 + (ZOOM_STEP_RATIO * notches * -1)); + zoomCenter = e.getPoint(); + zoomApply(); + } + + @Override + public void mouseClicked(MouseEvent e) { + + } + + protected Point2D startPointInWorld; + protected AffineTransform startScreenToWorldTransform; + protected ReferencedEnvelope startDisplayArea; + + @Override + public void mousePressed(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON1) { + startMove(e.getPoint()); + } + } + + @Override + public void mouseReleased(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON1) { + endMove(e.getPoint()); + } + } + + @Override + public void mouseEntered(MouseEvent e) { + + } + + @Override + public void mouseExited(MouseEvent e) { + + } + + @Override + public void mouseDragged(MouseEvent e) { +// endMove(e.getPoint()); + } + + @Override + public void mouseMoved(MouseEvent e) { + + } + + protected void startMove(Point2D startPointInScreen) { + JMapPane mapPane = getObserveMapPane(); + + startDisplayArea = mapPane.getDisplayArea(); + + startScreenToWorldTransform = mapPane.getScreenToWorldTransform(); + + startPointInWorld = new Point2D.Double(); + + startScreenToWorldTransform.transform(startPointInScreen, startPointInWorld); + + } + + protected void endMove(Point2D endPointInScreen) { + + Point2D endPointInWorld = new Point2D.Double(); + + startScreenToWorldTransform.transform(endPointInScreen, endPointInWorld); + + double transX = startPointInWorld.getX() - endPointInWorld.getX(); + double transY = startPointInWorld.getY() - endPointInWorld.getY(); + + ReferencedEnvelope endDisplayArea = new ReferencedEnvelope(startDisplayArea); + + endDisplayArea.translate(transX, transY); + + JMapPane mapPane = getObserveMapPane(); + + mapPane.setDisplayArea(endDisplayArea); + + if (log.isDebugEnabled()) { + log.debug(String.format("Translate (x : %s, y : %s)", transX, transY)); + } + } + } + + protected class TripMapListener implements MapPaneListener { + + protected boolean firstRendering; + + @Override + public void onNewMapContent(MapPaneEvent ev) { + firstRendering = true; + } + + @Override + public void onDisplayAreaChanged(MapPaneEvent ev) { + } + + @Override + public void onRenderingStarted(MapPaneEvent ev) { + rendererRunning = true; + } + + @Override + public void onRenderingStopped(MapPaneEvent ev) { + rendererRunning = false; + if (firstRendering) { + zoomIt(); + ((CardLayout) view.getLayout()).last(view); + firstRendering = false; + } else { + zoomApply(); + } + } + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/validation/ObserveSwingValidator.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/validation/ObserveSwingValidator.java new file mode 100644 index 0000000..41e879a --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/validation/ObserveSwingValidator.java @@ -0,0 +1,179 @@ +/* + * #%L + * ObServe :: Business + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.validation; + +import com.opensymphony.xwork2.ActionContext; +import com.opensymphony.xwork2.util.ValueStack; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import jaxx.runtime.validator.swing.SwingValidator; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.nuiton.validator.NuitonValidatorFactory; +import org.nuiton.validator.NuitonValidatorProvider; +import org.nuiton.validator.NuitonValidatorScope; +import org.nuiton.validator.xwork2.XWork2ValidatorUtil; + +/** + * Une surcharge du validateur swing offert par jaxx pour pouvoir ajouter dans + * la stack le DataContext (pour faire de la validation sur le context de + * données d'un niveau supérieur (valider une marée à partir d'une route par + * exemple). + * + * @param <B> le type d'objet a valider + * @author Tony Chemit - chemit@codelutin.com + * @since 1.0 + */ +public class ObserveSwingValidator<B> extends SwingValidator<B> { + + /** Logger */ + private static final Log log = LogFactory.getLog(ObserveSwingValidator.class); + + /** un etat pour initialiser la stack une unique fois la stack */ + private static boolean init; + + private static ValidationContext validationContext; + + public static <B> ObserveSwingValidator<B> newValidator(Class<B> type, + String context, + NuitonValidatorScope... scopes) { + return new ObserveSwingValidator<>( + type, + context, + scopes + ); + } + + public static <B> ObserveSwingValidator<B> newValidator(NuitonValidatorProvider provider, + Class<B> type, + String context, + NuitonValidatorScope... scopes) { + return new ObserveSwingValidator<>( + provider, + type, + context, + scopes + ); + } + + public ObserveSwingValidator( + Class<B> type, + String context, + NuitonValidatorScope... scopes) { + super(NuitonValidatorFactory.getDefaultProvider(), type, context, scopes); + } + + public ObserveSwingValidator(NuitonValidatorProvider provider, + Class<B> type, + String context, + NuitonValidatorScope... scopes) { + super(provider, type, context, scopes); + } + + @Override + protected void rebuildDelegateValidator(Class<B> beanType, + String context, + NuitonValidatorScope... scopes) { + super.rebuildDelegateValidator(beanType, context, scopes); + + if (isInit()) { + // deja initialise + return; + } + + // on positionne dans la stack de dataContext pour pouvoir faire de la + // validation sur des objets dans le scope. + + ValidationContext dataContext = getValidationContext(); + if (dataContext == null) { + + // aucun context de validation enregistré + if (log.isDebugEnabled()) { + log.debug("No validation context registred, try in application context..."); + } + ObserveSwingApplicationContext rootContext = ObserveSwingApplicationContext.get(); + if (rootContext == null) { + throw new IllegalStateException( + "pas de context d'application enregistré... utiliser la " + + "methode " + + //FIXME +// DataSourceFactory.class.getName() + + "#setApplicationContext(context)"); + } + dataContext = rootContext.getValidationContext(); + } + + reloadDataContext(dataContext, true); + + // on marque pour ne jamais revenir ici + setInit(true); + } + + public static void reloadDataContext(ValidationContext validationContext, boolean strict) { + if (validationContext != ObserveSwingValidator.validationContext) { + + // keep this validation context + ObserveSwingValidator.validationContext = validationContext; + setInit(false); + } + ValueStack valueStack; + ActionContext context = ActionContext.getContext(); + if (context == null) { + + if (strict) { + throw new IllegalStateException( + "pas de context xworks enregistré... utiliser la methode " + + ActionContext.class.getName() + "#setContext(context)"); + } + + valueStack = XWork2ValidatorUtil.getSharedValueStack(); + if (valueStack == null) { + return; + } + } else { + valueStack = context.getValueStack(); + } + + if (log.isDebugEnabled()) { + log.debug("Enregistrement du context de validation [" + validationContext + "] dans la valueStack de " + + "validation (" + valueStack + ')'); + } + + valueStack.push(validationContext); + } + + public static ValidationContext getValidationContext() { + if (validationContext == null) { + validationContext = ObserveSwingApplicationContext.get().getValidationContext(); + } + return validationContext; + } + + private static boolean isInit() { + return init; + } + + private static void setInit(boolean init) { + ObserveSwingValidator.init = init; + } + + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/validation/ValidationContext.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/validation/ValidationContext.java new file mode 100644 index 0000000..75bdb53 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/validation/ValidationContext.java @@ -0,0 +1,317 @@ +/* + * #%L + * ObServe :: Business + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.validation; + +import fr.ird.observe.application.swing.ObserveOpenDataManager; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.decoration.DecoratorService; +import fr.ird.observe.application.swing.db.DataContext; +import fr.ird.observe.application.swing.db.ObserveSwingDataSource; +import fr.ird.observe.services.dto.IdDto; +import fr.ird.observe.services.dto.longline.ActivityLonglineDto; +import fr.ird.observe.services.dto.longline.SetLonglineDto; +import fr.ird.observe.services.dto.longline.TripLonglineDto; +import fr.ird.observe.services.dto.referential.SpeciesDto; +import fr.ird.observe.services.dto.seine.ActivitySeineDto; +import fr.ird.observe.services.dto.seine.FloatingObjectDto; +import fr.ird.observe.services.dto.seine.RouteDto; +import fr.ird.observe.services.dto.seine.SetSeineDto; +import fr.ird.observe.services.dto.seine.TripSeineDto; +import fr.ird.observe.services.service.ReferentialService; +import fr.ird.observe.services.service.longline.ActivityLonglineService; +import fr.ird.observe.services.service.longline.SetLonglineService; +import fr.ird.observe.services.service.longline.TripLonglineService; +import fr.ird.observe.services.service.seine.ActivitySeineService; +import fr.ird.observe.services.service.seine.FloatingObjectService; +import fr.ird.observe.services.service.seine.RouteService; +import fr.ird.observe.services.service.seine.SetSeineService; +import fr.ird.observe.services.service.seine.TripSeineService; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import java.util.List; +import java.util.Map; +import java.util.TreeMap; + +/** + * Contient les objets en cours de validation. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.4 + */ +public class ValidationContext { + + /** Logger */ + static private final Log log = LogFactory.getLog(ValidationContext.class); + + public static final String VALIDATION_TRANSACTION_NAME = "validation"; + + private static final DtoSupplier<TripSeineDto> TRIP_SEINE_DTO_SUPPLIER = new DtoSupplier<TripSeineDto>() { + + @Override + public TripSeineDto get(ObserveSwingDataSource dataSource, String id) { + TripSeineService service = dataSource.newTripSeineService(); + TripSeineDto dto = service.loadDto(id); + return dto; + } + }; + + private static final DtoSupplier<RouteDto> ROUTE_DTO_SUPPLIER = new DtoSupplier<RouteDto>() { + + @Override + public RouteDto get(ObserveSwingDataSource dataSource, String id) { + RouteService service = dataSource.newRouteService(); + RouteDto dto = service.loadDto(id); + return dto; + } + }; + + private static final DtoSupplier<ActivitySeineDto> ACTIVITY_SEINE_DTO_SUPPLIER = new DtoSupplier<ActivitySeineDto>() { + + @Override + public ActivitySeineDto get(ObserveSwingDataSource dataSource, String id) { + ActivitySeineService service = dataSource.newActivitySeineService(); + ActivitySeineDto dto = service.loadDto(id); + return dto; + } + }; + + private static final DtoSupplier<TripLonglineDto> TRIP_LONGLINE_DTO_SUPPLIER = new DtoSupplier<TripLonglineDto>() { + + @Override + public TripLonglineDto get(ObserveSwingDataSource dataSource, String id) { + TripLonglineService service = dataSource.newTripLonglineService(); + TripLonglineDto dto = service.loadDto(id); + return dto; + } + }; + + private static final DtoSupplier<ActivityLonglineDto> ACTIVITY_LONGLINE_DTO_SUPPLIER = new DtoSupplier<ActivityLonglineDto>() { + + @Override + public ActivityLonglineDto get(ObserveSwingDataSource dataSource, String id) { + ActivityLonglineService service = dataSource.newActivityLonglineService(); + ActivityLonglineDto dto = service.loadDto(id); + return dto; + } + }; + + private static final DtoSupplier<SetSeineDto> SET_SEINE_DTO_SUPPLIER = new DtoSupplier<SetSeineDto>() { + + @Override + public SetSeineDto get(ObserveSwingDataSource dataSource, String id) { + SetSeineService service = dataSource.newSetSeineService(); + SetSeineDto dto = service.loadDto(id); + return dto; + } + }; + + private static final DtoSupplier<SetLonglineDto> SET_LONGLINE_DTO_SUPPLIER = new DtoSupplier<SetLonglineDto>() { + + @Override + public SetLonglineDto get(ObserveSwingDataSource dataSource, String id) { + SetLonglineService service = dataSource.newSetLonglineService(); + SetLonglineDto dto = service.loadDto(id); + return dto; + } + }; + + private static final DtoSupplier<FloatingObjectDto> FLOATING_OBJECT_DTO_SUPPLIER = new DtoSupplier<FloatingObjectDto>() { + + @Override + public FloatingObjectDto get(ObserveSwingDataSource dataSource, String id) { + FloatingObjectService service = dataSource.newFloatingObjectService(); + FloatingObjectDto dto = service.loadDto(id); + return dto; + } + }; + + private static final DtoSupplier<SpeciesDto> SPECIES_DTO_SUPPLIER = new DtoSupplier<SpeciesDto>() { + + @Override + public SpeciesDto get(ObserveSwingDataSource dataSource, String id) { + ReferentialService service = dataSource.newReferentialService(); + SpeciesDto dto = service.loadSpecies(id); + return dto; + } + }; + + protected final DataContext dataContext; + + protected Map<String, Object> cache; + + private List<?> referentielList; + + public Map<String, Object> getCache() { + if (cache == null) { + cache = new TreeMap<>(); + } + return cache; + } + + public void cleanCache() { + getCache().clear(); + referentielList = null; + } + + public ValidationContext(DataContext dataContext) { + this.dataContext = dataContext; + } + + public DecoratorService getDecoratorService() { + return ObserveSwingApplicationContext.get().getDecoratorService(); + } + + public ObserveOpenDataManager getOpenDataManager() { + return ObserveSwingApplicationContext.get().getOpenDataManager(); + } + + public DataContext getDataContext() { + return dataContext; + } + + public TripSeineDto getCurrentTripSeine() { + String tripSeineId = dataContext.getSelectedTripSeineId(); + TripSeineDto result = null; + if (tripSeineId != null) { + result = getDto(TRIP_SEINE_DTO_SUPPLIER, tripSeineId); + } + return result; + } + + public TripLonglineDto getCurrentTripLongline() { + String tripLonglineId = dataContext.getSelectedTripLonglineId(); + TripLonglineDto result = null; + if (tripLonglineId != null) { + result = getDto(TRIP_LONGLINE_DTO_SUPPLIER, tripLonglineId); + } + return result; + } + + public RouteDto getCurrentRoute() { + String routeId = dataContext.getSelectedRouteId(); + RouteDto result = null; + if (routeId != null) { + result = getDto(ROUTE_DTO_SUPPLIER, routeId); + } + return result; + } + + public ActivitySeineDto getCurrentActivitySeine() { + String activitySeineId = dataContext.getSelectedActivitySeineId(); + ActivitySeineDto result = null; + if (activitySeineId != null) { + result = getDto(ACTIVITY_SEINE_DTO_SUPPLIER, activitySeineId); + } + return result; + } + + public ActivityLonglineDto getCurrentActivityLongline() { + String activityLonglineId = dataContext.getSelectedActivityLonglineId(); + ActivityLonglineDto result = null; + if (activityLonglineId != null) { + result = getDto(ACTIVITY_LONGLINE_DTO_SUPPLIER, activityLonglineId); + } + return result; + } + + public SetSeineDto getCurrentSetSeine() { + String setSeineId = dataContext.getSelectedSetSeineId(); + SetSeineDto result = null; + if (setSeineId != null) { + result = getDto(SET_SEINE_DTO_SUPPLIER, setSeineId); + } + return result; + } + + public SetLonglineDto getCurrentSetLongline() { + String setLonglineId = dataContext.getSelectedSetLonglineId(); + SetLonglineDto result = null; + if (setLonglineId != null) { + result = getDto(SET_LONGLINE_DTO_SUPPLIER, setLonglineId); + } + return result; + } + + public FloatingObjectDto getCurrentFloatingObject() { + String floatingObjectId = dataContext.getSelectedFloatingObjectId(); + FloatingObjectDto result = null; + if (floatingObjectId != null) { + result = getDto(FLOATING_OBJECT_DTO_SUPPLIER, floatingObjectId); + } + return result; + } + + public SpeciesDto getSpecies(String speciesId) { + SpeciesDto result = null; + if (speciesId != null) { + result = getDto(SPECIES_DTO_SUPPLIER, speciesId); + } + return result; + } + + public List<?> getEditingReferentielList() { + return referentielList; + } + + public void setEditingReferentielList(List<?> referentielList) { + if (log.isDebugEnabled()) { + log.debug("Add referentielList (size : " + (referentielList == null ? 0 : referentielList.size()) + ")"); + } + this.referentielList = referentielList; + } + + protected <D extends IdDto> D getDto(DtoSupplier<D> dtoSupplier, String id) { + Object o = getCache().get(id); + if (o != null) { + if (log.isDebugEnabled()) { + log.debug("Use cached entity : " + id); + } + // found in cache + return (D) o; + } + + D result = dtoSupplier.get(id); + + if (result != null) { + if (log.isInfoEnabled()) { + log.info("Put entity into cache : " + id); + } + getCache().put(id, result); + + } + + return result; + } + + protected static abstract class DtoSupplier<D extends IdDto> { + + public final D get(String id) { + ObserveSwingDataSource dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); + D dto = get(dataSource, id); + return dto; + } + + public abstract D get(ObserveSwingDataSource dataSource, String id); + + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/validation/ValidationModelMode.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/validation/ValidationModelMode.java new file mode 100644 index 0000000..00b20fa --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/validation/ValidationModelMode.java @@ -0,0 +1,85 @@ +/* + * #%L + * ObServe :: Business + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.validation; + +import static org.nuiton.i18n.I18n.n; + +/** + * Pour caractériser le type de modele de validation a utiliser. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.3 + */ +public enum ValidationModelMode { + + /** validation du referentiel */ + REFERENTIEL( + n("observe.actions.validate.model.type.referentiel"), + n("observe.actions.validate.model.type.referentiel.description"), + true, false), + + /** validation de donnees observer */ + DATA( + n("observe.actions.validate.model.type.data"), + n("observe.actions.validate.model.type.data.description"), + false, true), + + /** validation du referentiel et de donnees observer */ + ALL( + n("observe.actions.validate.model.type.all"), + n("observe.actions.validate.model.type.all.description"), + true, false); + + private final String label; + + private final String description; + + private final boolean referential; + + private final boolean data; + + ValidationModelMode(String label, + String description, + boolean referential, + boolean data) { + this.label = label; + this.description = description; + this.referential = referential; + this.data = data; + } + + public String getLabel() { + return label; + } + + public String getDescription() { + return description; + } + + public boolean isReferential() { + return referential; + } + + public boolean isData() { + return data; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/validation/ValidationService.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/validation/ValidationService.java new file mode 100644 index 0000000..07cee1e --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/validation/ValidationService.java @@ -0,0 +1,155 @@ +/* + * #%L + * ObServe :: Business + * %% + * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.validation; + +import fr.ird.observe.services.dto.AbstractObserveDto; +import fr.ird.observe.services.dto.IdDto; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; + +import org.nuiton.validator.NuitonValidatorScope; +import org.nuiton.validator.bean.simple.SimpleBeanValidator; + +import java.util.Set; + +/** + * Contrat du service de validation des données. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 1.3 + */ +public class ValidationService { + + /** Logger */ + private static final Log log = + LogFactory.getLog(ValidationService.class); + + /** + * Obtenir le validateur d'un type objet + * + * @param context le lastName du context de validation + * @param scopes les scopes autorisés + * @param klass type de l'objet à valider + * @param <B> type de l'objet à valider + * @return le validateur trouvé ou {@code null} + */ + public <B> SimpleBeanValidator<B> getValidator(String context, + NuitonValidatorScope[] scopes, + Class<B> klass) { + + SimpleBeanValidator<B> valitator = SimpleBeanValidator.newValidator( + klass, + context, + scopes + ); + + Set<NuitonValidatorScope> resultScopes = valitator.getEffectiveScopes(); + if (resultScopes.isEmpty()) { + valitator = null; + if (log.isDebugEnabled()) { + log.debug(klass + " : validator skip (no scopes detected)"); + } + } else { + if (log.isDebugEnabled()) { + log.debug(klass + " : keep validator " + valitator); + } + } + return valitator; + } + + /** + * Obtenir le dictionnaire des validateurs pour les types d'entités donnés. + * + * @param contextName le lastName du context de validation + * @param scopes les scopes autorisés + * @param beanclass types des entités + * @return le dictionnaire des validateurs par type d'entité. + */ + public ValidatorsMap getValidators( + String contextName, + NuitonValidatorScope[] scopes, + Class<?>... beanclass) { + ValidatorsMap map = detectValidators( + contextName, + scopes, + beanclass + ); + return map; + } + + /** + * Obtenir le dictionnaire des validateurs pour les entités donnés. + * + * <b>Note:</b> On effectue un parcours des entités pour connaitre les types + * d'objets à valider, il faut donc des les collections des entités soient + * toutes chargées (ou l'objet attaché à une transaction...). + * + * @param contextName le lastName du context de validation + * @param scopes les scopes autorisés + * @param dtos les entités + * @return le dictionnaire des validateurs par type d'entité. + */ + public ValidatorsMap getValidators( + String contextName, + NuitonValidatorScope[] scopes, + IdDto... dtos) { + + //FIXME + Set<Class<? extends AbstractObserveDto>> types = null; +// try { +// types = TopiaEntityHelper.detectTypes( +// ObserveEntityEnum.values(), +// entities +// ); +// } catch (TopiaException e) { +// throw new IllegalArgumentException( +// "could not obtains types for reason " + e.getMessage(), e); +// } + + ValidatorsMap result = detectValidators( + contextName, + scopes, + types.toArray(new Class<?>[types.size()]) + ); + return result; + } + + @SuppressWarnings("unchecked") + public <T> ValidatorsMap detectValidators( + String context, + NuitonValidatorScope[] scopes, + Class<?>... types) { + + ValidatorsMap result = new ValidatorsMap(); + + for (Class<?> c : types) { + // on cherche le validateur + SimpleBeanValidator<T> validator = (SimpleBeanValidator<T>) + getValidator(context, scopes, c); + if (validator != null) { + // on enregistre le validateur + result.put(c, validator); + } + } + return result; + } +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/application/swing/validation/ValidatorsMap.java b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/validation/ValidatorsMap.java new file mode 100644 index 0000000..1b582c3 --- /dev/null +++ b/observe-application-swing/src/main/java/fr/ird/observe/application/swing/validation/ValidatorsMap.java @@ -0,0 +1,121 @@ +/* + * #%L + * ObServe :: Business + * %% + * Copyright (C) 2008 - 2010 CodeLutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ +package fr.ird.observe.application.swing.validation; + +import org.nuiton.validator.NuitonValidatorScope; +import org.nuiton.validator.bean.simple.SimpleBeanValidator; + +import java.util.Collection; +import java.util.EnumSet; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * Un dictionnaire de validateurs ordonnees par le type de leur bean. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 2.1 + */ +public class ValidatorsMap implements Map<Class<?>, SimpleBeanValidator<?>> { + + protected final Map<Class<?>, SimpleBeanValidator<?>> delegate; + + public ValidatorsMap() { + delegate = new HashMap<>(); + } + + public NuitonValidatorScope[] getScopes() { + EnumSet<NuitonValidatorScope> result = + EnumSet.noneOf(NuitonValidatorScope.class); + for (SimpleBeanValidator<?> b : values()) { + result.addAll(b.getScopes()); + } + return result.toArray(new NuitonValidatorScope[result.size()]); + } + + public <X> SimpleBeanValidator<X> getValidator(Class<X> klass) { + SimpleBeanValidator<X> beanValidator = (SimpleBeanValidator<X>) get(klass); + return beanValidator; + } + + @Override + public int size() { + return delegate.size(); + } + + @Override + public boolean isEmpty() { + return delegate.isEmpty(); + } + + @Override + public boolean containsKey(Object key) { + return delegate.containsKey(key); + } + + @Override + public boolean containsValue(Object value) { + return delegate.containsValue(value); + } + + @Override + public SimpleBeanValidator<?> get(Object key) { + return delegate.get(key); + } + + @Override + public SimpleBeanValidator<?> put(Class<?> key, SimpleBeanValidator<?> value) { + return delegate.put(key, value); + } + + @Override + public SimpleBeanValidator<?> remove(Object key) { + return delegate.remove(key); + } + + @Override + public void putAll(Map<? extends Class<?>, ? extends SimpleBeanValidator<?>> m) { + delegate.putAll(m); + } + + @Override + public void clear() { + delegate.clear(); + } + + @Override + public Set<Class<?>> keySet() { + return delegate.keySet(); + } + + @Override + public Collection<SimpleBeanValidator<?>> values() { + return delegate.values(); + } + + @Override + public Set<Entry<Class<?>, SimpleBeanValidator<?>>> entrySet() { + return delegate.entrySet(); + } + +} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/configuration/ObserveSwingApplicationConfig.java b/observe-application-swing/src/main/java/fr/ird/observe/configuration/ObserveSwingApplicationConfig.java deleted file mode 100644 index e482d6e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/configuration/ObserveSwingApplicationConfig.java +++ /dev/null @@ -1,1168 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.configuration; - -import com.google.common.base.Charsets; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import fr.ird.observe.ObserveCLAction; -import fr.ird.observe.ObserveResourceManager; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.constants.CreationMode; -import fr.ird.observe.db.constants.DbMode; -import fr.ird.observe.services.ObserveDataSourceConfigurationMainFactory; -import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationRest; -import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaH2; -import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaPG; -import fr.ird.observe.ui.UIHelper; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.config.ApplicationConfig; -import org.nuiton.config.ApplicationConfigHelper; -import org.nuiton.config.ApplicationConfigProvider; -import org.nuiton.version.Version; -import org.nuiton.version.Versions; - -import javax.swing.JOptionPane; -import java.awt.Color; -import java.beans.PropertyChangeListener; -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.util.ArrayList; -import java.util.Calendar; -import java.util.Date; -import java.util.List; -import java.util.Locale; -import java.util.Properties; -import java.util.Set; - -import static fr.ird.observe.ObserveResourceManager.Resource; -import static org.nuiton.i18n.I18n.t; - -/** - * La configuration de l'application. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class ObserveSwingApplicationConfig extends ApplicationConfig { - - - /** - * le fichier de configuration de l'application avec les informations sur le - * projet (version, license,...) et la configuration des ui (icons, ...) - */ - public static final String APPLICATION_PROPERTIES = "/observe.properties"; - - /** le lastName du repertoire ou sont les donnees de l'application */ - public static final String USER_DIRECTORY_FILENAME = ".observe"; - - /** le pattern du fichier de sauvegarde d'une base locale */ - public static final String BACKUP_DB_PATTERN = "obstuna-local-%1$tF--%1$tk-%1$tM-%1$tS.sql.gz"; - - /** le pattern du fichier de sauvegarde d'une base access importée */ - public static final String ACCESS_DB_PATTERN = "import-access-%1$tF--%1$tk-%1$tM-%1$tS.sql.gz"; - - /** le pattern du fichier de rapport après validation */ - public static final String REPORT_PATTERN = "report-%1$tF--%1$tk-%1$tM-%1$tS.sql.gz"; - - public static final String DB_NAME = "obstuna"; - - /** - * La version de l'application. - */ - public static final String APPLICATION_VERSION = "application.version"; - - public static final String VERSION = "version"; - - public static final String PROPERTY_DEFAULT_DB_MODE = "defaultDbMode"; - - public static final String PROPERTY_DEFAULT_CREATION_MODE = "defaultCreationMode"; - - public static final String PROPERTY_SPECIES_LIST_SEINE_TARGET_CATCH_ID = "speciesListSeineTargetCatchId"; - - public static final String PROPERTY_SPECIES_LIST_SEINE_SCHOOL_ESTIMATE_ID = "speciesListSeineSchoolEstimateId"; - - public static final String PROPERTY_SPECIES_LIST_SEINE_OBJECT_SCHOOL_ESTIMATE_ID = "speciesListSeineObjectSchoolEstimateId"; - - public static final String PROPERTY_SPECIES_LIST_SEINE_NON_TARGET_CATCH_ID = "speciesListSeineNonTargetCatchId"; - - public static final String PROPERTY_SPECIES_LIST_SEINE_OBJECT_OBSERVED_SPECIES_ID = "speciesListSeineObjectObservedSpeciesId"; - - public static final String PROPERTY_SPECIES_LIST_LONGLINE_CATCH_ID = "speciesListLonglineCatchId"; - - public static final String PROPERTY_SPECIES_LIST_LONGLINE_ENCOUNTER_ID = "speciesListLonglineEncounterId"; - - public static final String PROPERTY_SPECIES_LIST_LONGLINE_DEPREDATOR_ID = "speciesListLonglineDepredatorId"; - - public static final String PROPERTY_VERSION = "version"; - - public static final String PROPERTY_DB_VERSION = "dbVersion"; - - public static final String PROPERTY_AUTO_POPUP_NUMBER_EDITOR = "autoPopupNumberEditor"; - - public static final String PROPERTY_SHOW_NUMBER_EDITOR_BUTTON = "showNumberEditorButton"; - - public static final String PROPERTY_SHOW_DATE_TIME_EDITOR_SLIDER= "showTimeEditorSlider"; - - public static final String PROPERTY_LOCAL_STORAGE_EXIST = "localStorageExist"; - - public static final String PROPERTY_INITIAL_DUMP_EXIST = "initialDumpExist"; - - public static final String PROPERTY_MAIN_STORAGE_OPENED = "mainStorageOpened"; - - public static final String PROPERTY_STORE_REMOTE_STORAGE = "storeRemoteStorage"; - - public static final String PROPERTY_DEFAULT_GPS_MAX_DELAY = "defaultGpsMaxDelay"; - - public static final String PROPERTY_DEFAULT_GPS_MAX_SPEED = "defaultGpsMaxSpeed"; - - public static final String PROPERTY_CHANGE_SYNCHRO_SRC = "changeSynchroSrc"; - - public static final String PROPERTY_NON_TARGET_OBSERVATION = "nonTargetObservation"; - - public static final String PROPERTY_TARGET_DISCARDS_OBSERVATION = "targetDiscardsObservation"; - - public static final String PROPERTY_SAMPLES_OBSERVATION = "samplesObservation"; - - public static final String PROPERTY_OBJECTS_OBSERVATION = "objectsObservation"; - - public static final String PROPERTY_DETAILLED_ACTIVITIES_OBSERVATION = "detailledActivitiesObservation"; - - public static final String PROPERTY_MAMMALS_OBSERVATION = "mammalsObservation"; - - public static final String PROPERTY_BIRDS_OBSERVATION = "birdsObservation"; - - public static final String PROPERTY_BAIT_OBSERVATION = "baitObservation"; - - public static final String PROPERTY_RESOURCES_DIRECTORY = "resourcesDirectory"; - - public static final String PROPERTY_LOCALE = "locale"; - - public static final String PROPERTY_DB_LOCALE = "dbLocale"; - - public static final String PROPERTY_CAN_MIGRATE_OBSTUNA = "canMigrateObstuna"; - - public static final String PROPERTY_CAN_MIGRATE_H2 = "canMigrateH2"; - - public static final String PROPERTY_MAIN_STORAGE_OPENED_LOCAL = "mainStorageOpenedLocal"; - - public static final String PROPERTY_COPYRIGHT_TEXT = "copyrightText"; - - public static final String PROPERTY_FULL_SCREEN = "fullScreen"; - - public static final String PROPERTY_LOCAL_DBDIRECTORY = "localDBDirectory"; - - public static final String PROPERTY_I18N_DIRECTORY = "i18nDirectory"; - - public static final String PROPERTY_INITIAL_DB_DUMP = "initialDbDump"; - - public static final String PROPERTY_BACKUP_DIRECTORY = "backupDirectory"; - - public static final String PROPERTY_REPORT_DIRECTORY = "reportDirectory"; - - public static final String PROPERTY_MAP_DIRECTORY = "mapDirectory"; - - public static final String PROPERTY_TMP_DIRECTORY = "tmpDirectory"; - - public static final String PROPERTY_DISPLAY_MAIN_UI = "displayMainUI"; - - public static final String PROPERTY_CAN_USE_UI = "canUseUI"; - - public static final String PROPERTY_ADJUSTING = "adjusting"; - - public static final String PROPERTY_H2_LOGIN = "h2Login"; - - public static final String PROPERTY_H2_PASSWORD = "h2Password"; - - public static final String PROPERTY_OBSTUNA_URL = "obstunaUrl"; - - public static final String PROPERTY_OBSTUNA_LOGIN = "obstunaLogin"; - - public static final String PROPERTY_OBSTUNA_PASSWORD = "obstunaPassword"; - - public static final String PROPERTY_OBSTUNA_USE_SSL = "obstunaUseSsl"; - - public static final String PROPERTY_LOAD_LOCAL_STORAGE = "loadLocalStorage"; - - public static final String PROPERTY_SHOW_MIGRATION_PROGRESSION = "showMigrationProgression"; - - public static final String PROPERTY_SHOW_MIGRATION_SQL = "showMigrationSql"; - - public static final String PROPERTY_VALIDATION_REPORT_DIRECTORY = "validationReportDirectory"; - - public static final String PROPERTY_SHOW_SQL = "showSql"; - - public static final String PROPERTY_H2_SERVER_PORT = "h2ServerPort"; - - public static final String PROPERTY_DEV_MODE = "devMode"; - - public static final String PROPERTY_TREE_OPEN_NODES = "treeOpenNodes"; - - /** Logger */ - private static final Log log = LogFactory.getLog(ObserveSwingApplicationConfig.class); - - protected static final String DEFAULT_OBSERVE_SWING_CONFIGURATION_FILENAME = "observeSwing.conf"; - - /** - * un drepeau pour savoir s'il faut lancer l'interface graphique. Cette - * valeur peut être programmées lors des actions. - */ - protected boolean displayMainUI = true; - - /** drapeau pour savoir si une base locale existe */ - protected boolean localStorageExist; - - /** - * drapeau pour savoir si le dump initial a ete chargee depuis la base - * centrale - */ - protected boolean initialDumpExist; - - /** drapeau pour savoir si une source de données est ouverte */ - protected boolean mainStorageOpened; - - /** - * drapeau pour savoir si la source ouverte est locale (attention, lorsqu'il - * n'y a pas de storage d'ouvert, la valeur est null). - */ - protected Boolean mainStorageOpenedLocal; - - /** - * drapeau pour savoir si on peut utiliser des ui dans l'environnement. - * - * Par defaut, on suppose qu'on peut utiliser l'environnement graphique et - * si on désactive explicitement ou si pas d'environnement graphique - * trouvé. - */ - protected boolean canUseUI = true; - - /** La version de l'application */ - private Version version; - - /** Texte du copyright (calculé dynamiquement). */ - protected String copyrightText; - - /** - * Liste des options qu'on ne peut pas sauvegarder (les mots de passes, - * les options d'admin pour les simples utilisateurs,...). - * - * @since 1.5 - */ - protected String[] unsavables; - - //FIXME - private final ImmutableSet<String> longlinVesselTypeIds = ImmutableSet.copyOf( - Sets.newHashSet("fr.ird.observe.entities.referentiel.VesselType#1239832675735#0.044156847891821505", - "fr.ird.observe.entities.referentiel.VesselType#1239832675736#0.8708229847859869", - "fr.ird.observe.entities.referentiel.VesselType#1239832686137#0.1")); - - private final ImmutableSet<String> seineVesselTypeIds = ImmutableSet.copyOf( - Sets.newHashSet("fr.ird.observe.entities.referentiel.VesselType#1239832675735#0.044156847891821505", - "fr.ird.observe.entities.referentiel.VesselType#1239832675735#0.307197212385357", - "fr.ird.observe.entities.referentiel.VesselType#1239832675735#0.7380146830307519", - "fr.ird.observe.entities.referentiel.VesselType#1239832675735#0.9086075071905084", - "fr.ird.observe.entities.referentiel.VesselType#1239832675737#0.43324169605639407")); - - public ObserveSwingApplicationConfig() { - this(DEFAULT_OBSERVE_SWING_CONFIGURATION_FILENAME); - } - - public ObserveSwingApplicationConfig(String confFileName) { - setEncoding(Charsets.UTF_8.name()); - setConfigFileName(confFileName); - ApplicationConfigProvider applicationConfigProvider = ApplicationConfigHelper.getProvider(getClass().getClassLoader(), ObserveSwingApplicationConfigProvider.OBSERVE_SWING_CONFIGURATION_PROVIDER_NAME); - loadDefaultOptions(applicationConfigProvider.getOptions()); - } - - public boolean containActions(Step action) { - List<Action> list = actions.get(action.ordinal()); - return !(list == null || list.isEmpty()); - } - - public void initConfig(ObserveResourceManager manager) throws IOException { - - Version version = null; - - Properties p = manager.getResource(Resource.application); - - for (Object k : p.keySet()) { - String key = String.valueOf(k); - Object value = p.get(k); - if (log.isDebugEnabled()) { - log.debug("install property [" + k + "] : " + value); - } - String strValue = String.valueOf(value); - if (APPLICATION_VERSION.equals(key)) { - version = Versions.valueOf(strValue); - if (version.isSnapshot()) { - version = Versions.removeSnapshot(version); - } - - } else { - setDefaultOption(key, strValue); - } - } - - if (version == null) { - throw new IllegalStateException("No application.version found in application configuration."); - } - - setVersion(version); - setDefaultOption(VERSION, version.getVersion()); - setDefaultOption(APPLICATION_VERSION, version.getVersion()); - - // creation des actions disponibles - for (ObserveCLAction.ActionDefinition a : ObserveCLAction.ActionDefinition.values()) { - - for (String alias : a.aliases) { - addActionAlias(alias, a.action); - } - } - - } - - @Override - protected void migrateUserConfigurationFile(File oldHomeConfig, - File homeConfig) throws IOException { - super.migrateUserConfigurationFile(oldHomeConfig, homeConfig); - // on previent l'utilisateur que son fichier de configuration a été - // deplacé - JOptionPane.showInternalMessageDialog(null, - t("observe.title.config.migrate"), - t("observe.runner.config.migrate.file", - oldHomeConfig.getName(), - oldHomeConfig, - homeConfig - ), - JOptionPane.WARNING_MESSAGE); - } - - public void installSaveAction() { - // ajout de l'action de sauvegarde automatique sur certaines propriétés - - List<String> result = new ArrayList<>(); - - for (ObserveSwingApplicationConfigOption option : ObserveSwingApplicationConfigOption.values()) { - String key = option.getPropertyKey(); - if (key != null) { - // add a listener - if (log.isDebugEnabled()) { - log.debug("register action listener for property " + key); - } - result.add(key); - } - } - - installSaveUserAction(result.toArray(new String[result.size()])); - } - - public String getCopyrightText() { - if (copyrightText == null) { - Date date = new Date(); - Calendar calendar = Calendar.getInstance(); - calendar.setTime(date); - int year = calendar.get(Calendar.YEAR); - copyrightText = "Version " + getVersion() + " IRD @ 2008-" + year; - } - return copyrightText; - } - - public boolean isDevMode() { - boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.DEV_MODE.key); - return result; - } - - public Version getVersion() { - return version; - } - - public Version getModelVersion() { - Version result = getOption(Version.class, ObserveSwingApplicationConfigOption.MODEL_VERSION.key); - return result; - } - - public boolean isAutoPopupNumberEditor() { - boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.AUTO_POPUP_NUMBER_EDITOR.key); - return result; - } - - public boolean isShowNumberEditorButton() { - boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.SHOW_NUMBER_EDITOR_BUTTON.key); - return result; - } - - public boolean isShowTimeEditorSlider() { - boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.SHOW_DATE_TIME_EDITOR_SLIDER.key); - return result; - } - - public boolean isFullScreen() { - boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.FULL_SCREEN.key); - return result; - } - - public File getDataDirectory() { - File file = getOptionAsFile(ObserveSwingApplicationConfigOption.DATA_DIRECTORY.key); - return file; - } - - public File getValidationReportDirectory() { - File file = getOptionAsFile(ObserveSwingApplicationConfigOption.VALIDATION_REPORT_DIRECTORY.key); - return file; - } - - public File getLocalDBDirectory() { - File result = getOptionAsFile(ObserveSwingApplicationConfigOption.DB_DIRECTORY.key); - return result; - } - - public File getResourcesDirectory() { - File result = getOptionAsFile(ObserveSwingApplicationConfigOption.RESOURCES_DIRECTORY.key); - return result; - } - - public File getI18nDirectory() { - File result = getOptionAsFile(ObserveSwingApplicationConfigOption.I18N_DIRECTORY.key); - return result; - } - - public void setResourcesDirectory(File newValue) { - setOption(ObserveSwingApplicationConfigOption.RESOURCES_DIRECTORY, newValue); - } - - public File getInitialDbDump() { - File result = getOptionAsFile(ObserveSwingApplicationConfigOption.INITIAL_DB_DUMP.key); - return result; - } - - public File getBackupDirectory() { - File result = getOptionAsFile(ObserveSwingApplicationConfigOption.BACKUP_DIRECTORY.key); - return result; - } - - public File getReportDirectory() { - File result = getOptionAsFile(ObserveSwingApplicationConfigOption.REPORT_DIRECTORY.key); - return result; - } - - public File getTmpDirectory() { - File result = getOptionAsFile(ObserveSwingApplicationConfigOption.TMP_DIRECTORY.key); - return result; - } - - public File getLogConfigurationFile() { - File result = getOptionAsFile(ObserveSwingApplicationConfigOption.LOG_CONFIGURATION_FILE.key); - return result; - } - - public String getH2Login() { - String result = getOption(ObserveSwingApplicationConfigOption.H2_LOGIN.key); - return result; - } - - public char[] getH2Password() { - String result = getOption(ObserveSwingApplicationConfigOption.H2_PASSWORD.key); - char[] r = result.toCharArray(); - return r; - } - - public int getH2ServerPort() { - Integer port = getOptionAsInt(ObserveSwingApplicationConfigOption.H2_SERVER_PORT.key); - return port; - } - - public String getObstunaUrl() { - String result = getOption(ObserveSwingApplicationConfigOption.OBSTUNA_URL.key); - return result; - } - - public void setObstunaUrl(String jdbcUrl) { - setOption(ObserveSwingApplicationConfigOption.OBSTUNA_URL.key, jdbcUrl); - } - - public String getObstunaLogin() { - String result = getOption(ObserveSwingApplicationConfigOption.OBSTUNA_LOGIN.key); - return result; - } - - public void setObstunaLogin(String login) { - setOption(ObserveSwingApplicationConfigOption.OBSTUNA_LOGIN.key, login); - } - - public char[] getObstunaPassword() { - String result = getOption(ObserveSwingApplicationConfigOption.OBSTUNA_PASSWORD.key); - char[] r = result.toCharArray(); - return r; - } - - public void setObstunaPassword(char[] password) { - setOption(ObserveSwingApplicationConfigOption.OBSTUNA_PASSWORD.key, new String(password)); - } - - public boolean isObstunaUseSsl() { - boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.OBSTUNA_USE_SSL_CERT.key); - return result; - } - - public void setObstunaUseSsl(boolean useSsl) { - setOption(ObserveSwingApplicationConfigOption.OBSTUNA_USE_SSL_CERT, useSsl); - } - - public URL getServerUrl() { - URL result = (URL) getOption(ObserveSwingApplicationConfigOption.SERVER_URL); - return result; - } - - public void setServerUrl(URL serverUrl) { - setOption(ObserveSwingApplicationConfigOption.SERVER_URL, serverUrl); - } - - public String getServerLogin() { - String result = getOption(ObserveSwingApplicationConfigOption.SERVER_LOGIN.key); - return result; - } - - public void setServerLogin(String serverLoginl) { - setOption(ObserveSwingApplicationConfigOption.SERVER_LOGIN.key, serverLoginl); - } - - public char[] getServerPassword() { - String result = getOption(ObserveSwingApplicationConfigOption.SERVER_PASSWORD.key); - char[] r = result.toCharArray(); - return r; - } - - public void setServerPassword(char[] password) { - setOption(ObserveSwingApplicationConfigOption.SERVER_PASSWORD.key, new String(password)); - } - - public String getServerDataBaseName() { - String result = getOption(ObserveSwingApplicationConfigOption.SERVER_DATABASE_NAME.key); - return result; - } - - public void setServerDataBaseName(String dataBaseName) { - setOption(ObserveSwingApplicationConfigOption.SERVER_DATABASE_NAME.key, dataBaseName); - } - - public DbMode getDefaultDbMode() { - DbMode result = getOption(DbMode.class, ObserveSwingApplicationConfigOption.DEFAULT_DB_MODE.key); - return result; - } - - public CreationMode getDefaultCreationMode() { - CreationMode result = - getOption(CreationMode.class, ObserveSwingApplicationConfigOption.DEFAULT_CREATION_MODE.key); - return result; - } - - public boolean isShowMigrationSql() { - boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.SHOW_MIGRATION_SQL.key); - return result; - } - - public boolean isShowMigrationProgression() { - boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.SHOW_MIGRATION_PROGRESSION.key); - return result; - } - - public boolean isShowSql() { - boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.SHOW_SQL.key); - return result; - } - - public int getDefaultGpsMaxDelay() { - Integer i = getOptionAsInt(ObserveSwingApplicationConfigOption.DEFAULT_GPS_MAX_DELAY.key); - return i; - } - - public float getDefaultGpsMaxSpeed() { - double i = getOptionAsDouble(ObserveSwingApplicationConfigOption.DEFAULT_GPS_MAX_SPEED.key); - return (float) i; - } - - public boolean isChangeSynchroSrc() { - boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.CHANGE_SYNCHRO_SRC.key); - return result; - } - - public boolean isStoreRemoteStorage() { - boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.STORE_REMOTE_STORAGE.key); - return result; - } - - public boolean isCanMigrateObstuna() { - boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.OBSTUNA_CAN_MIGRATE.key); - return result; - } - - public boolean isCanMigrateH2() { - boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.H2_CAN_MIGRATE.key); - return result; - } - - public boolean isLoadLocalStorage() { - boolean result = getOptionAsBoolean(ObserveSwingApplicationConfigOption.LOAD_LOCAL_STORAGE.key); - return result; - } - - public Locale getLocale() { - Locale result = getOption(Locale.class, ObserveSwingApplicationConfigOption.LOCALE.key); - return result; - } - - public Locale getDbLocale() { - Locale result = getOption(Locale.class, ObserveSwingApplicationConfigOption.DB_LOCALE.key); - return result; - } - - public int getNonTargetObservation() { - int value = getOptionAsInt(ObserveSwingApplicationConfigOption.NON_TARGET_OBSERVATION.key); - return value; - } - - public int getTargetDiscardsObservation() { - int value = getOptionAsInt(ObserveSwingApplicationConfigOption.TARGET_DISCARDS_OBSERVATION.key); - return value; - } - - public int getSamplesObservation() { - int value = getOptionAsInt(ObserveSwingApplicationConfigOption.SAMPLES_OBSERVATION.key); - return value; - } - - public int getObjectsObservation() { - int value = getOptionAsInt(ObserveSwingApplicationConfigOption.OBJECTS_OBSERVATION.key); - return value; - } - - public int getDetailledActivitiesObservation() { - int value = getOptionAsInt(ObserveSwingApplicationConfigOption.DETAILLED_ACTIVITIES_OBSERVATION.key); - return value; - } - - public int getMammalsObservation() { - int value = getOptionAsInt(ObserveSwingApplicationConfigOption.MAMMALS_OBSERVATION.key); - return value; - } - - public int getBirdsObservation() { - int value = getOptionAsInt(ObserveSwingApplicationConfigOption.BIRDS_OBSERVATION.key); - return value; - } - - public int getBaitObservation() { - int value = getOptionAsInt(ObserveSwingApplicationConfigOption.BAIT_OBSERVATION.key); - return value; - } - - public boolean isDisplayMainUI() { - return displayMainUI; - } - - public boolean isCanUseUI() { - return canUseUI; - } - - public boolean isLocalStorageExist() { - return localStorageExist; - } - - public boolean isInitialDumpExist() { - return initialDumpExist; - } - - public boolean isMainStorageOpened() { - return mainStorageOpened; - } - - public Boolean getMainStorageOpenedLocal() { - return mainStorageOpenedLocal; - } - - public void setLocalStorageExist(boolean newValue) { - localStorageExist = newValue; - // always force propagation - firePropertyChange(PROPERTY_LOCAL_STORAGE_EXIST, newValue); - } - - public void setInitialDumpExist(boolean newValue) { - initialDumpExist = newValue; - // always force propagation - firePropertyChange(PROPERTY_INITIAL_DUMP_EXIST, newValue); - } - - public void setMainStorageOpened(boolean newValue) { - mainStorageOpened = newValue; - if (!newValue) { - // on force la reinitialisation - setMainStorageOpenedLocal(null); - } - // always force propagation - firePropertyChange(PROPERTY_MAIN_STORAGE_OPENED, newValue); - } - - public void setMainStorageOpenedLocal(Boolean newValue) { - mainStorageOpenedLocal = newValue; - // always force propagation - firePropertyChange(PROPERTY_MAIN_STORAGE_OPENED + "Local", newValue); - } - - public void setDisplayMainUI(boolean b) { - displayMainUI = b; - } - - public void setCanUseUI(boolean canUseUI) { - this.canUseUI = canUseUI; - if (!canUseUI) { - // on ne pourra pas lancer l'ui principale - setDisplayMainUI(false); - } - } - - public void setAutoPopupNumberEditor(boolean newValue) { - setOption(ObserveSwingApplicationConfigOption.AUTO_POPUP_NUMBER_EDITOR, newValue); - } - - public void setShowNumberEditorButton(boolean newValue) { - setOption(ObserveSwingApplicationConfigOption.SHOW_NUMBER_EDITOR_BUTTON, newValue); - } - - public void setShowTimeEditorSlider(boolean newValue) { - setOption(ObserveSwingApplicationConfigOption.SHOW_DATE_TIME_EDITOR_SLIDER, newValue); - } - - public void setFullScreen(boolean newValue) { - setOption(ObserveSwingApplicationConfigOption.FULL_SCREEN, newValue); - } - - public void setChangeSynchroSrc(boolean newValue) { - setOption(ObserveSwingApplicationConfigOption.CHANGE_SYNCHRO_SRC, newValue); - } - - public void setStoreRemoteStorage(boolean newValue) { - setOption(ObserveSwingApplicationConfigOption.STORE_REMOTE_STORAGE, newValue); - } - - public void setLoadLocalStorage(boolean newValue) { - setOption(ObserveSwingApplicationConfigOption.LOAD_LOCAL_STORAGE, newValue); - } - - public void setDefaultDbMode(DbMode newValue) { - setOption(ObserveSwingApplicationConfigOption.DEFAULT_DB_MODE, newValue); - } - - public void setDefaultCreationMode(CreationMode newValue) { - setOption(ObserveSwingApplicationConfigOption.DEFAULT_CREATION_MODE, newValue); - } - - public void setDefaultGpsMaxDelay(int newValue) { - setOption(ObserveSwingApplicationConfigOption.DEFAULT_GPS_MAX_DELAY, newValue); - } - - public void setDefaultGpsMaxSpeed(float newValue) { - setOption(ObserveSwingApplicationConfigOption.DEFAULT_GPS_MAX_SPEED, newValue); - } - - public void setLocale(Locale newValue) { - setOption(ObserveSwingApplicationConfigOption.LOCALE, newValue); - } - - public void setDbLocale(Locale newValue) { - setOption(ObserveSwingApplicationConfigOption.DB_LOCALE, newValue); - } - - public void setCanMigrateObstuna(Boolean newValue) { - setOption(ObserveSwingApplicationConfigOption.OBSTUNA_CAN_MIGRATE, newValue); - } - - public void setCanMigrateH2(Boolean newValue) { - setOption(ObserveSwingApplicationConfigOption.H2_CAN_MIGRATE, newValue); - } - - public void setNonTargetObservation(int newValue) { - setOption(ObserveSwingApplicationConfigOption.NON_TARGET_OBSERVATION, newValue); - } - - public void setTargetDiscardsObservation(int newValue) { - setOption(ObserveSwingApplicationConfigOption.TARGET_DISCARDS_OBSERVATION, newValue); - } - - public void setSamplesObservation(int newValue) { - setOption(ObserveSwingApplicationConfigOption.SAMPLES_OBSERVATION, newValue); - } - - public void setObjectsObservation(int newValue) { - setOption(ObserveSwingApplicationConfigOption.OBJECTS_OBSERVATION, newValue); - } - - public void setDetailledActivitiesObservation(int newValue) { - setOption(ObserveSwingApplicationConfigOption.DETAILLED_ACTIVITIES_OBSERVATION, newValue); - } - - public void setMammalsObservation(int newValue) { - setOption(ObserveSwingApplicationConfigOption.MAMMALS_OBSERVATION, newValue); - } - - public void setBirdsObservation(int newValue) { - setOption(ObserveSwingApplicationConfigOption.BIRDS_OBSERVATION, newValue); - } - - public void setBaitObservation(int newValue) { - setOption(ObserveSwingApplicationConfigOption.BAIT_OBSERVATION, newValue); - } - - public void setShowMigrationSql(boolean showMigrationSql) { - setOption(ObserveSwingApplicationConfigOption.SHOW_MIGRATION_SQL, showMigrationSql); - } - - public void setShowMigrationProgression(boolean showMigrationProgression) { - setOption(ObserveSwingApplicationConfigOption.SHOW_MIGRATION_PROGRESSION, showMigrationProgression); - } - - public void setShowSql(boolean showSql) { - setOption(ObserveSwingApplicationConfigOption.SHOW_SQL, showSql); - } - - public String getSpeciesListSeineNonTargetCatchId() { - String value = getOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_NON_TARGET_CATCH_ID.key); - return value; - } - - public String getSpeciesListSeineTargetCatchId() { - String value = getOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_TARGET_CATCH_ID.key); - return value; - } - - public String getSpeciesListSeineSchoolEstimateId() { - String value = getOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_SCHOOL_ESTIMATE_ID.key); - return value; - } - - public String getSpeciesListSeineObjectObservedSpeciesId() { - String value = getOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_OBJECT_OBSERVED_SPECIES_ID.key); - return value; - } - - public String getSpeciesListSeineObjectSchoolEstimateId() { - String value = getOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_OBJECT_SCHOOL_ESTIMATE_ID.key); - return value; - } - - public String getSpeciesListLonglineCatchId() { - String value = getOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_LONGLINE_CATCH_ID.key); - return value; - } - - public String getSpeciesListLonglineEncounterId() { - String value = getOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_LONGLINE_ENCOUNTER_ID.key); - return value; - } - - public String getSpeciesListLonglineDepredatorId() { - String value = getOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_LONGLINE_DEPREDATOR_ID.key); - return value; - } - - public void setSpeciesListSeineNonTargetCatchId(String speciesListSeineNonTargetCatchId) { - setOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_NON_TARGET_CATCH_ID, speciesListSeineNonTargetCatchId); - } - - public void setSpeciesListSeineTargetCatchId(String speciesListSeineTargetCatchId) { - setOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_TARGET_CATCH_ID, speciesListSeineTargetCatchId); - } - - public void setSpeciesListSeineSchoolEstimateId(String speciesListSeineSchoolEstimateId) { - setOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_SCHOOL_ESTIMATE_ID, speciesListSeineSchoolEstimateId); - } - - public void setSpeciesListSeineObjectObservedSpeciesId(String speciesListSeineObjectObservedSpeciesId) { - setOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_OBJECT_OBSERVED_SPECIES_ID, speciesListSeineObjectObservedSpeciesId); - } - - public void setSpeciesListSeineObjectSchoolEstimateId(String speciesListseineObjectSchoolEstimateId) { - setOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_OBJECT_SCHOOL_ESTIMATE_ID, speciesListseineObjectSchoolEstimateId); - } - - public void setSpeciesListLonglineCatchId(String speciesListLonglineCatchId) { - setOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_LONGLINE_CATCH_ID, speciesListLonglineCatchId); - } - - public void setSpeciesListLonglineEncounterId(String speciesListLonglineEncounterId) { - setOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_LONGLINE_ENCOUNTER_ID, speciesListLonglineEncounterId); - } - - public void setSpeciesListLonglineDepredatorId(String speciesListLonglineDepredatorId) { - setOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_LONGLINE_DEPREDATOR_ID, speciesListLonglineDepredatorId); - } - - public Color getMapBackgroundColor() { - Color result = getOptionAsColor(ObserveSwingApplicationConfigOption.MAP_BACKGROUND_COLOR.key); - return result; - } - - public List<File> getMapLayerFiles() { - List<File> layers = Lists.newLinkedList(); - - for (ObserveSwingApplicationConfigOption layerOption : ObserveSwingApplicationConfigOption.MAP_LAYERS) { - File layerFile = getOptionAsFile(layerOption.key); - if (layerFile != null && layerFile.exists()) { - layers.add(layerFile); - } - } - return layers; - } - - public File getMapStyleFile() { - File result = getOptionAsFile(ObserveSwingApplicationConfigOption.MAP_STYLE_FILE.key); - return result; - } - - public String[] getTreeOpenNodeIds() { - String ids = getOption(ObserveSwingApplicationConfigOption.TREE_OPEN_NODES.key); - String[] result = null; - if (ids != null) { - result = ids.split(","); - } - return result; - } - - public void setTreeOpenNodeIds(String[] ids) { - String joinIds = StringUtils.join(ids, ","); - setOption(ObserveSwingApplicationConfigOption.TREE_OPEN_NODES, joinIds); - } - - public String[] getUnsavables() { - if (unsavables == null) { - List<String> tmp = new ArrayList<>(); - tmp.add(ObserveSwingApplicationConfigOption.OBSTUNA_PASSWORD.getKey()); -// tmp.add(OBSTUNA_SSL_CERTIFICAT_PASSWORD.getKey()); - tmp.add(ObserveSwingApplicationConfigOption.H2_PASSWORD.getKey()); - tmp.add(ObserveSwingApplicationConfigOption.OBSTUNA_CAN_MIGRATE.getKey()); - -// if (!ObserveRunner.isAdmin()) { -// // toutes les options dite admin ne sont pas sauvables -// -// for (ObserveSwingApplicationConfigOption option : values()) { -// if (option.isAdmin()) { -// -// // ne pas ajouter les options d'admin pour le simple utilisateur -// tmp.add(option.key); -// } -// } -// } - unsavables = tmp.toArray(new String[tmp.size()]); - } - return unsavables; - } - - public void saveForUser(String... excludeKeys) { - if (log.isInfoEnabled()) { - log.info(t("observe.message.save.configuration", getUserConfigFile())); - } - super.saveForUser(getUnsavables()); - } - - - public void fromStorageConfig(ObserveDataSourceConfigurationTopiaH2 config) { - setShowMigrationProgression(config.isShowMigrationProgression()); - setShowMigrationSql(config.isShowMigrationSql()); - saveForUser(); - } - - public void fromStorageConfig(ObserveDataSourceConfigurationTopiaPG config) { - setObstunaUrl(config.getJdbcUrl()); - setObstunaLogin(config.getUsername()); - setObstunaPassword(config.getPassword()); - setObstunaUseSsl(config.isUseSsl()); -// if (useSsl) { -// setOption(OBSTUNA_SSL_CERTIFICAT_FILE, -// config.getSslCertificatFile().getAbsolutePath()); -// setOption(OBSTUNA_SSL_CERTIFICAT_PASSWORD, -// new String(config.getSslCertificatPassword())); -// } else { -// setOption(OBSTUNA_SSL_CERTIFICAT_FILE.key, ""); -// setOption(OBSTUNA_SSL_CERTIFICAT_PASSWORD, EMPTY_CHAR_ARRAY); -// } - setShowMigrationProgression(config.isShowMigrationProgression()); - setShowMigrationSql(config.isShowMigrationSql()); - //TODO-TC20100311 : on devrait pas regarder si l'utilisateur veut sauver - //TODO-TC20100311 : la configuration ? - saveForUser(); - } - - public void fromStorageConfig(ObserveDataSourceConfigurationRest config) { - setServerUrl(config.getServerUrl()); - setServerLogin(config.getLogin()); - setServerPassword(config.getPassword()); - setServerDataBaseName(config.getOptionalDatabaseName().orElse(null)); - saveForUser(); - } - - - public ObserveDataSourceConfigurationTopiaH2 getDataSourceConfigurationH2(String label) { - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ObserveDataSourceConfigurationMainFactory configurationMainFactory = applicationContext.getObserveDataSourceConfigurationMainFactory(); - - File dbDirectory = new File(getLocalDBDirectory(), DB_NAME); - - ObserveDataSourceConfigurationTopiaH2 result = configurationMainFactory.createObserveDataSourceConfigurationTopiaH2( - label, - dbDirectory, - DB_NAME, - getH2Login(), - getH2Password(), - isShowMigrationProgression(), - isShowMigrationSql(), - getModelVersion() - ); - return result; - } - - public ObserveDataSourceConfigurationTopiaPG getDataSourceConfigurationPG(String label) { - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ObserveDataSourceConfigurationMainFactory configurationMainFactory = applicationContext.getObserveDataSourceConfigurationMainFactory(); - - ObserveDataSourceConfigurationTopiaPG result = configurationMainFactory.createObserveDataSourceConfigurationTopiaPG( - label, - getObstunaUrl(), - getObstunaLogin(), - getObstunaPassword(), - isObstunaUseSsl(), - isShowMigrationProgression(), - isShowMigrationSql(), - getModelVersion() - ); - return result; - } - - public ObserveDataSourceConfigurationRest getDataSourceConfigurationRest(String label) { - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ObserveDataSourceConfigurationMainFactory configurationMainFactory = applicationContext.getObserveDataSourceConfigurationMainFactory(); - - ObserveDataSourceConfigurationRest result = configurationMainFactory.createObserveDataSourceConfigurationRest( - label, - getServerUrl(), - getServerLogin(), - getServerPassword(), - getServerDataBaseName(), - getModelVersion() - ); - return result; - } - - public void removeJaxxPropertyChangeListener() { - List<String> tmp = new ArrayList<>(); - for (ObserveSwingApplicationConfigOption option : ObserveSwingApplicationConfigOption.values()) { - String propertyName = option.getPropertyKey(); - if (propertyName != null) { - tmp.add(propertyName); - } - } - if (log.isDebugEnabled()) { - log.debug("property names to seek for options : " + tmp); - } - String[] propertyNames = tmp.toArray( - new String[tmp.size()]); - - PropertyChangeListener[] toRemove = - UIHelper.findJaxxPropertyChangeListener( - propertyNames, - getPropertyChangeListeners()); - if (toRemove == null || toRemove.length == 0) { - return; - } - if (log.isDebugEnabled()) { - log.debug("before remove : " + getPropertyChangeListeners().length); - log.debug("toRemove : " + toRemove.length); - } - for (PropertyChangeListener listener : toRemove) { - removePropertyChangeListener(listener); - } - if (log.isDebugEnabled()) { - log.debug("after remove : " + getPropertyChangeListeners().length); - } - } - - public void setOption(ObserveSwingApplicationConfigOption option, Object newValue) { - String key = option.getKey(); - Object oldValue = getOption(key); - String value = String.valueOf(newValue); - setOption(key, value); - if (log.isDebugEnabled()) { - log.debug("set option " + key + " value : " + value); - } - String propertyName = option.getPropertyKey(); - if (propertyName != null) { - // l'option est javabeans, declanchement d'un changement - if (log.isTraceEnabled()) { - log.trace("fires config change from option " + key); - } - firePropertyChange(propertyName, oldValue, newValue); - } - } - - void setVersion(Version version) { - this.version = version; - } - - public Set<String> getSeineVesselTypeIds() { - return seineVesselTypeIds; - } - - public Set<String> getLonglineVesselTypeIds() { - return longlinVesselTypeIds; - } - - public String replaceRecursiveOptions(String option) { - return super.replaceRecursiveOptions(option); - } - - public String getConfigurationDescription() { - StringBuilder builder = new StringBuilder(); - builder.append("\n====================================================================================================================="); - builder.append("\n=== Observe Swing configuration ====================================================================================="); - builder.append(String.format("\n=== %1$-40s = %2$s", "Filename", getConfigFileName())); - for (ObserveSwingApplicationConfigOption option : ObserveSwingApplicationConfigOption.orderedByNameValues()) { - builder.append(String.format("\n=== %1$-40s = %2$s", option.getKey(), getOption(option))); - } - builder.append("\n====================================================================================================================="); - return builder.toString(); - } - - ////////////////////////////////////////////////// - // Toutes les étapes d'actions - ////////////////////////////////////////////////// - - public enum Step { - - AfterInit, BeforeExit - } - - protected void firePropertyChange(String propertyName, Object newValue) { - pcs.firePropertyChange(propertyName, null, newValue); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/configuration/ObserveSwingApplicationConfigOption.java b/observe-application-swing/src/main/java/fr/ird/observe/configuration/ObserveSwingApplicationConfigOption.java deleted file mode 100644 index c062d94..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/configuration/ObserveSwingApplicationConfigOption.java +++ /dev/null @@ -1,943 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.configuration; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import fr.ird.observe.db.constants.CreationMode; -import fr.ird.observe.db.constants.DbMode; -import fr.ird.observe.services.ObserveSpeciesListConfiguration; -import org.nuiton.config.ApplicationConfig; -import org.nuiton.config.ConfigOptionDef; -import org.nuiton.version.Version; - -import java.awt.Color; -import java.io.File; -import java.net.URL; -import java.util.Collections; -import java.util.List; -import java.util.Locale; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Les options disponibles dans l'application, modifiables via la ligne de - * commande, ou le fichier utilisateur. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.2 - */ -public enum ObserveSwingApplicationConfigOption implements ConfigOptionDef { - - /** le lastName du fichier de configuration (sans le prefix .) */ - CONFIG_FILE( - ApplicationConfig.CONFIG_FILE_NAME, - n("observe.config.configFileName.description"), - ObserveSwingApplicationConfig.DEFAULT_OBSERVE_SWING_CONFIGURATION_FILENAME, - String.class, - true, - true - ), - - /** flag pour afficher automatiquement la popup du clavier numerique */ - DEV_MODE( - "observe." + ObserveSwingApplicationConfig.PROPERTY_DEV_MODE, - n("observe.config.devMode"), - "true", - Boolean.class, - true, - true - ), - - /** version du modèle de données */ - MODEL_VERSION( - "observe.model.version", - n("observe.model.version"), - null, - Version.class, - true, - true - ), - - // directories - - /** le repertoire ou est stoquee la base locale */ - DATA_DIRECTORY( - "data.directory", - n("observe.config.defaultDataDirectory.description"), - "${user.home}/.observe", - File.class, - false, - false - ), - - /** le repertoire ou est stoquee la base locale */ - DB_DIRECTORY( - "db.directory", - n("observe.config.defaultLocalDbDirectory.description"), - "${data.directory}/db", - File.class, - false, - false - ), - - /** - * le lastName de la base initiale recuperee lors de la premiere connexion - * a Obstuna. - */ - INITIAL_DB_DUMP( - "initial.db.dump", - n("observe.config.defaultInitialDbDump.description"), - "${data.directory}/initial-database.sql.gz", - File.class, - false, - false - ), - - /** le repertoire ou effectuer les sauvegarde */ - BACKUP_DIRECTORY( - "backup.directory", - n("observe.config.defaultBackupDirectory.description"), - "${data.directory}/backup", - File.class, - false, - false - ), - - /** le repertoire ou sont stockees toutes les ressources de l'utilisateur */ - RESOURCES_DIRECTORY( - "resources.directory", - ObserveSwingApplicationConfig.PROPERTY_RESOURCES_DIRECTORY, - n("observe.config.defaultResourcesDirectory.description"), - "${data.directory}/resources-${version}", - File.class, - false, - false - ), - - /** le repertoire ou sont stockees les traduction i18n de l'utilisateur */ - I18N_DIRECTORY( - "i18n.directory", - ObserveSwingApplicationConfig.PROPERTY_I18N_DIRECTORY, - n("observe.config.defaultI18nDirectory.description"), - "${resources.directory}/i18n", - File.class, - false, - false - ), - - /** le repertoire ou sont stockees les reports de l'utilisateur */ - REPORT_DIRECTORY( - "report.directory", - ObserveSwingApplicationConfig.PROPERTY_REPORT_DIRECTORY, - n("observe.config.defaultReportDirectory.description"), - "${resources.directory}/report", - File.class, - false, - false - ), - - /** le repertoire ou sont stockees les cartes de l'utilisateur */ - MAP_DIRECTORY( - "map.directory", - ObserveSwingApplicationConfig.PROPERTY_MAP_DIRECTORY, - n("observe.config.defaultMapDirectory.description"), - "${resources.directory}/map", - File.class, - false, - false - ), - - /** le repertoire ou sont stockees les reports de validation de l'utilisateur */ - VALIDATION_REPORT_DIRECTORY( - "validation.report.directory", - ObserveSwingApplicationConfig.PROPERTY_VALIDATION_REPORT_DIRECTORY, - n("observe.config.defaultValidationReportDirectory.description"), - "${data.directory}/validation-report", - File.class, - false, - false - ), - - /** le repertoire temporaire (utilise pour les base de synchro) */ - TMP_DIRECTORY( - "tmp.directory", - n("observe.config.defaultTmpDirectory.description"), - "${data.directory}/tmp", - File.class, - false, - false - ), - - /** Le chemin du fichier de configuration des logs. */ - LOG_CONFIGURATION_FILE( - "logConfigurationFile", - n("observe.config.logConfigurationFile.description"), - "${resources.directory}/observe-log4j.properties", - String.class, - true, - false), - - // local db config - - /** login sur toutes les bases h2 (non sauvegarde) */ - H2_LOGIN( - "h2.username", - n("observe.config.h2.login.description"), - "sa", - String.class, - true, - true - ), - - /** mot de passe sur toutes les bases h2 (non sauvegarde) */ - H2_PASSWORD( - "h2.password", - n("observe.config.h2.password.description"), - "sa", - String.class, - true, - true - ), - - /** flag pour effectuer la mise a jour des bases locales */ - H2_CAN_MIGRATE( - "h2.canMigrate", - n("observe.config.h2.can.migrate.description"), - "true", - Boolean.class, - false, - false - ), - - - /** port à utiliser pour lancer ObServe en mode serveur */ - H2_SERVER_PORT( - "h2.serverPort", - n("observe.config.h2.serverPort.description"), - "9093", - Integer.class, - false, - false - ), - - // obstuna db config - - /** url de la base obstuna */ - OBSTUNA_URL( - "obstuna.url", - n("observe.config.obstuna.url.description"), - "jdbc:postgresql:///obstuna", - String.class, - false, - false - ), - - /** login de la base obstuna */ - OBSTUNA_LOGIN( - "obstuna.username", - n("observe.config.obstuna.login.description"), - "utilisateur", - String.class, - false, - false - ), - - /** mot de passe de la base obstuna (non sauvegarde) */ - OBSTUNA_PASSWORD( - "obstuna.password", - n("observe.config.obstuna.password.description"), - "", - String.class, - true, - false - ), - - /** flag pour activer l'utilisation ssl pour la connexion a obstuna */ - OBSTUNA_USE_SSL_CERT( - "obstuna.useSsl", - n("observe.config.obstuna.useSsl.description"), - "false", - Boolean.class, - false, - false - ), - - /** flag pour mettre a jour obstuna */ - OBSTUNA_CAN_MIGRATE( - "pg.canMigrate", - n("observe.config.pg.can.migrate.description"), - "false", - Boolean.class, - false, - false - ), - - // Rest server config - - /** url du serveur restflag pour mettre a jour obstuna */ - SERVER_URL( - "server.url", - n("observe.config.server.url.description"), - null, - URL.class, - false, - false - ), - - /** url du serveur restflag pour mettre a jour obstuna */ - SERVER_LOGIN( - "server.login", - n("observe.config.server.login.description"), - "", - String.class, - false, - false - ), - - /** url du serveur restflag pour mettre a jour obstuna */ - SERVER_PASSWORD( - "server.password", - n("observe.config.server.password.description"), - "", - String.class, - false, - false - ), - - /** url du serveur restflag pour mettre a jour obstuna */ - SERVER_DATABASE_NAME( - "server.dataBaseName", - n("observe.config.server.dataBaseName.description"), - null, - String.class, - false, - false - ), - - // change storage options - - /** le mode de connexion par defaut */ - DEFAULT_DB_MODE( - ObserveSwingApplicationConfig.PROPERTY_DEFAULT_DB_MODE, - ObserveSwingApplicationConfig.PROPERTY_DEFAULT_DB_MODE, - n("observe.config.defaultDbMode"), - DbMode.USE_LOCAL.name(), - DbMode.class, - false, - false - ), - - /** le mode de creation par defaut de base locale */ - DEFAULT_CREATION_MODE( - ObserveSwingApplicationConfig.PROPERTY_DEFAULT_CREATION_MODE, - ObserveSwingApplicationConfig.PROPERTY_DEFAULT_CREATION_MODE, - n("observe.config.defaultCreationMode"), - CreationMode.IMPORT_EXTERNAL_DUMP.name(), - CreationMode.class, - false, - false - ), - - /** flag pour sauvegarder le paramétrage de la connexion a obstuna */ - STORE_REMOTE_STORAGE( - "ui." + ObserveSwingApplicationConfig.PROPERTY_STORE_REMOTE_STORAGE, - ObserveSwingApplicationConfig.PROPERTY_STORE_REMOTE_STORAGE, - n("observe.config.ui.storeRemoteStorage"), - "true", - Boolean.class, - false, - false - ), - - /** flag pour charge ou non la base locale au démarrage */ - LOAD_LOCAL_STORAGE( - "ui." + ObserveSwingApplicationConfig.PROPERTY_LOAD_LOCAL_STORAGE, - ObserveSwingApplicationConfig.PROPERTY_LOAD_LOCAL_STORAGE, - n("observe.config.ui.loadLocalStorage"), - "true", - Boolean.class, - false, - false - ), - - /** pour afficher la progression de la migration dans les logs */ - SHOW_MIGRATION_PROGRESSION( - ObserveSwingApplicationConfig.PROPERTY_SHOW_MIGRATION_PROGRESSION, - ObserveSwingApplicationConfig.PROPERTY_SHOW_MIGRATION_PROGRESSION, - n("observe.config.showMigrationProgression"), - "true", - Boolean.class, - false, - false - ), - - /** pour affichier les requetes sql lors de la migration dans les logs */ - SHOW_MIGRATION_SQL( - ObserveSwingApplicationConfig.PROPERTY_SHOW_MIGRATION_SQL, - ObserveSwingApplicationConfig.PROPERTY_SHOW_MIGRATION_SQL, - n("observe.config.showMigrationSql"), - "true", - Boolean.class, - false, - false - ), - /** pour affichier toutes les requetes sql dans les logs */ - SHOW_SQL( - ObserveSwingApplicationConfig.PROPERTY_SHOW_SQL, - ObserveSwingApplicationConfig.PROPERTY_SHOW_SQL, - n("observe.config.showSql"), - "false", - Boolean.class, - false, - false - ), - // gps default values - - /** temps maximum autorise en deux points gps */ - DEFAULT_GPS_MAX_DELAY( - ObserveSwingApplicationConfig.PROPERTY_DEFAULT_GPS_MAX_DELAY, - ObserveSwingApplicationConfig.PROPERTY_DEFAULT_GPS_MAX_DELAY, - n("observe.config.defaultGpsMaxDelay"), - "60", - Integer.class, - false, - false - ), - - /** vitesse maximum (en noeud) entre deux points gps */ - DEFAULT_GPS_MAX_SPEED( - ObserveSwingApplicationConfig.PROPERTY_DEFAULT_GPS_MAX_SPEED, - ObserveSwingApplicationConfig.PROPERTY_DEFAULT_GPS_MAX_SPEED, - n("observe.config.defaultGpsMaxSpeed"), - "25.0f", - Float.class, - false, - false - ), - - // synchro actions options - - /** flag pour autoriser le choix de la base source */ - CHANGE_SYNCHRO_SRC( - "ui." + ObserveSwingApplicationConfig.PROPERTY_CHANGE_SYNCHRO_SRC, - ObserveSwingApplicationConfig.PROPERTY_CHANGE_SYNCHRO_SRC, - n("observe.config.ui.changeSynchroSrc"), - "false", - Boolean.class, - false, - false - ), - - // ui config - - /** flag pour voir le boutton d'affichage de la popup de clavier numerique) */ - SHOW_NUMBER_EDITOR_BUTTON( - "ui." + ObserveSwingApplicationConfig.PROPERTY_SHOW_NUMBER_EDITOR_BUTTON, - ObserveSwingApplicationConfig.PROPERTY_SHOW_NUMBER_EDITOR_BUTTON, - n("observe.config.ui.showNumberEditorButton"), - "true", - Boolean.class, - false, - false - ), - - /** flag pour afficher automatiquement la popup du clavier numerique */ - AUTO_POPUP_NUMBER_EDITOR( - "ui." + ObserveSwingApplicationConfig.PROPERTY_AUTO_POPUP_NUMBER_EDITOR, - ObserveSwingApplicationConfig.PROPERTY_AUTO_POPUP_NUMBER_EDITOR, - n("observe.config.ui.autoPopupNumberEditor"), - "false", - Boolean.class, - false, - false - ), - - /** flag pour voir la réglette d'affichage des heures dans l'éditeur des temps */ - SHOW_DATE_TIME_EDITOR_SLIDER( - "ui." + ObserveSwingApplicationConfig.PROPERTY_SHOW_DATE_TIME_EDITOR_SLIDER, - ObserveSwingApplicationConfig.PROPERTY_SHOW_DATE_TIME_EDITOR_SLIDER, - n("observe.config.ui.showTimeEditorSlider"), - "true", - Boolean.class, - false, - false - ), - - /** flag pour lancer l'application en mode plein ecran */ - FULL_SCREEN( - "ui." + ObserveSwingApplicationConfig.PROPERTY_FULL_SCREEN, - ObserveSwingApplicationConfig.PROPERTY_FULL_SCREEN, - n("observe.config.ui.fullscreen"), - "false", - Boolean.class, - false, - false - ), - - /** locale a utiliser dans l'application */ - LOCALE( - "ui." + ObserveSwingApplicationConfig.PROPERTY_LOCALE, - ObserveSwingApplicationConfig.PROPERTY_LOCALE, - n("observe.config.ui.locale"), - Locale.FRANCE.toString(), - Locale.class, - false, - false - ), - - /** locale du referentiel */ - DB_LOCALE( - "db." + ObserveSwingApplicationConfig.PROPERTY_LOCALE, - ObserveSwingApplicationConfig.PROPERTY_DB_LOCALE, - n("observe.config.db.locale"), - Locale.FRANCE.toString(), - Locale.class, - false, - false - ), - - // program observation max - - /** la valeur maximale de qualification des observations faune associe */ - NON_TARGET_OBSERVATION( - "observation.fauneAssociee", - ObserveSwingApplicationConfig.PROPERTY_NON_TARGET_OBSERVATION, - n("observe.config.observation.fauneAssociee"), - "1", - Integer.class, - false, - false - ), - - /** la valeur maximale de qualification des observations rejet thons */ - TARGET_DISCARDS_OBSERVATION( - "observation.rejetsThons", - ObserveSwingApplicationConfig.PROPERTY_TARGET_DISCARDS_OBSERVATION, - n("observe.config.observation.rejetsThons"), - "1", - Integer.class, - false, - false - ), - - /** la valeur maximale de qualification des observations mensuration */ - SAMPLES_OBSERVATION( - "observation.mensurations", - ObserveSwingApplicationConfig.PROPERTY_SAMPLES_OBSERVATION, - n("observe.config.observation.mensurations"), - "1", - Integer.class, - false, - false - ), - - /** la valeur maximale de qualification des observations objet flottant */ - OBJECTS_OBSERVATION( - "observation.floatingObject", - ObserveSwingApplicationConfig.PROPERTY_OBJECTS_OBSERVATION, - n("observe.config.observation.floatingObject"), - "1", - Integer.class, - false, - false - ), - - /** la valeur maximale de qualification des observations activitys detaillees */ - DETAILLED_ACTIVITIES_OBSERVATION( - "observation.activitysDetaillees", - ObserveSwingApplicationConfig.PROPERTY_DETAILLED_ACTIVITIES_OBSERVATION, - n("observe.config.observation.activitysDetaillees"), - "1", - Integer.class, - false, - false - ), - - /** la valeur maximale de qualification des observations mammiferes */ - MAMMALS_OBSERVATION( - "observation.mammiferes", - ObserveSwingApplicationConfig.PROPERTY_MAMMALS_OBSERVATION, - n("observe.config.observation.mammiferes"), - "1", - Integer.class, - false, - false - ), - - /** la valeur maximale de qualification des observations oiseaux */ - BIRDS_OBSERVATION( - "observation.oiseaux", - ObserveSwingApplicationConfig.PROPERTY_BIRDS_OBSERVATION, - n("observe.config.observation.oiseaux"), - "1", - Integer.class, - false, - false - ), - - /** la valeur maximale de qualification des observations gleure */ - BAIT_OBSERVATION( - "observation.gleure", - ObserveSwingApplicationConfig.PROPERTY_BAIT_OBSERVATION, - n("observe.config.observation.gleure"), - "1", - Integer.class, - false, - false - ), - - /** le type de liste d'espèces pour les captures cibles (seine) */ - SPECIES_LIST_SEINE_TARGET_CATCH_ID( - "speciesList.seine.targetCatch", - ObserveSwingApplicationConfig.PROPERTY_SPECIES_LIST_SEINE_TARGET_CATCH_ID, - n("observe.config.speciesList.seine.targetCatch"), - ObserveSpeciesListConfiguration.DEFAULT_SPECIES_LIST_SEINE_TARGET_CATCH_ID, - String.class, - false, - false - ), - - /** le type de liste d'espèce pour les Estimation banc (seine) */ - SPECIES_LIST_SEINE_SCHOOL_ESTIMATE_ID( - "speciesList.seine.schoolEstimate", - ObserveSwingApplicationConfig.PROPERTY_SPECIES_LIST_SEINE_SCHOOL_ESTIMATE_ID, - n("observe.config.speciesList.seine.schoolEstimate"), - ObserveSpeciesListConfiguration.DEFAULT_SPECIES_LIST_SEINE_SCHOOL_ESTIMATE_ID, - String.class, - false, - false - ), - - /** le type de liste d'espèces pour les Estimation banc objet (seine) */ - SPECIES_LIST_SEINE_OBJECT_SCHOOL_ESTIMATE_ID( - "speciesList.seine.objectSchoolEstimate", - ObserveSwingApplicationConfig.PROPERTY_SPECIES_LIST_SEINE_OBJECT_SCHOOL_ESTIMATE_ID, - n("observe.config.speciesList.seine.objectSchoolEstimate"), - ObserveSpeciesListConfiguration.DEFAULT_SPECIES_LIST_SEINE_OBJECT_SCHOOL_ESTIMATE_ID, - String.class, - false, - false - ), - - /** le type de liste d'espèces pour les captures non cibles (seine) */ - SPECIES_LIST_SEINE_NON_TARGET_CATCH_ID( - "speciesList.seine.nonTargetCatch", - ObserveSwingApplicationConfig.PROPERTY_SPECIES_LIST_SEINE_NON_TARGET_CATCH_ID, - n("observe.config.speciesList.seine.nonTargetCatch"), - ObserveSpeciesListConfiguration.DEFAULT_SPECIES_LIST_SEINE_NON_TARGET_CATCH_ID, - String.class, - false, - false - ), - - /** le type de liste d'espèces pour les Faune observée (seine) */ - SPECIES_LIST_SEINE_OBJECT_OBSERVED_SPECIES_ID( - "speciesList.seine.objectObservedSpecies", - ObserveSwingApplicationConfig.PROPERTY_SPECIES_LIST_SEINE_OBJECT_OBSERVED_SPECIES_ID, - n("observe.config.speciesList.seine.objectObservedSpecies"), - ObserveSpeciesListConfiguration.DEFAULT_SPECIES_LIST_SEINE_OBJECT_OBSERVED_SPECIES_ID, - String.class, - false, - false - ), - - /** le type de liste d'espèces pour les captures (longline) */ - SPECIES_LIST_LONGLINE_CATCH_ID( - "speciesList.longline.catch", - ObserveSwingApplicationConfig.PROPERTY_SPECIES_LIST_LONGLINE_CATCH_ID, - n("observe.config.speciesList.longline.catch"), - ObserveSpeciesListConfiguration.DEFAULT_SPECIES_LIST_LONGLINE_CATCH_ID, - String.class, - false, - false - ), - - /** le type de liste d'espèces pour les rencontres (longline) */ - SPECIES_LIST_LONGLINE_ENCOUNTER_ID( - "speciesList.longline.encounter", - ObserveSwingApplicationConfig.PROPERTY_SPECIES_LIST_LONGLINE_ENCOUNTER_ID, - n("observe.config.speciesList.longline.encounter"), - ObserveSpeciesListConfiguration.DEFAULT_SPECIES_LIST_LONGLINE_ENCOUNTER_ID, - String.class, - false, - false - ), - /** le type de liste d'espèces pour les deprédations (longline) */ - SPECIES_LIST_LONGLINE_DEPREDATOR_ID( - "speciesList.longline.depredator", - ObserveSwingApplicationConfig.PROPERTY_SPECIES_LIST_LONGLINE_DEPREDATOR_ID, - n("observe.config.speciesList.longline.encounter"), - ObserveSpeciesListConfiguration.DEFAULT_SPECIES_LIST_LONGLINE_DEPREDATOR_ID, - String.class, - false, - false - ), - - /** le chemin vers le fond de carte */ - MAP_BACKGROUND_COLOR( - "map.background.color", - n("observe.config.map.background.description"), - new Color(87, 200, 255).toString(), - Color.class, - false, - false - ), - /** shape file 1 */ - MAP_LAYER_1( - "map.layer1.path", - n("observe.config.map.layer1.description"), - "${resources.directory}/map/shapeFiles/continents/GSHHS_l_L1.shp", - File.class, - false, - false - ), - /** shape file 2 */ - MAP_LAYER_2( - "map.layer2.path", - n("observe.config.map.layer2.description"), - "${resources.directory}/map/shapeFiles/continents/GSHHS_l_L6.shp", - File.class, - false, - false - ), - /** shape file 3 */ - MAP_LAYER_3( - "map.layer3.path", - n("observe.config.map.layer3.description"), - "${resources.directory}/map/shapeFiles/lakesAndSeas/GSHHS_l_L2.shp", - File.class, - false, - false - ), - /** shape file 4 */ - MAP_LAYER_4( - "map.layer4.path", - n("observe.config.map.layer4.description"), - "${resources.directory}/map/shapeFiles/borders/WDBII_border_l_L1.shp", - File.class, - false, - false - ), - /** shape file 5 */ - MAP_LAYER_5( - "map.layer5.path", - n("observe.config.map.layer5.description"), - "${resources.directory}/map/shapeFiles/zee/World_EEZ_v8_2014.shp", - File.class, - false, - false - ), - /** shape file 6 */ - MAP_LAYER_6( - "map.layer6.path", - n("observe.config.map.layer6.description"), - null, - File.class, - false, - false - ), - /** shape file 7 */ - MAP_LAYER_7( - "map.layer7.path", - n("observe.config.map.layer7.description"), - null, - File.class, - false, - false - ), - /** shape file 8 */ - MAP_LAYER_8( - "map.layer8.path", - n("observe.config.map.layer8.description"), - null, - File.class, - false, - false - ), - /** shape file 9 */ - MAP_LAYER_9( - "map.layer9.path", - n("observe.config.map.layer9.description"), - null, - File.class, - false, - false - ), - /** shape file 10 */ - MAP_LAYER_10( - "map.layer10.path", - n("observe.config.map.layer10.description"), - null, - File.class, - false, - false - ), - /** style Maps */ - MAP_STYLE_FILE( - "map.style.path", - n("observe.config.map.style.description"), - "${resources.directory}/map/style.xml", - File.class, - false, - false), - - - /** Ids des noeuds ouverts dans l'arbre */ - TREE_OPEN_NODES( - "ui." + ObserveSwingApplicationConfig.PROPERTY_TREE_OPEN_NODES, - ObserveSwingApplicationConfig.PROPERTY_TREE_OPEN_NODES, - n("observe.config.ui.treeOpenNodes"), - null, - String.class, - false, - false - ); - - public static final List<ObserveSwingApplicationConfigOption> MAP_LAYERS = ImmutableList.of(MAP_LAYER_1, MAP_LAYER_2, MAP_LAYER_3, - MAP_LAYER_4, MAP_LAYER_5, MAP_LAYER_6, MAP_LAYER_7, MAP_LAYER_8, MAP_LAYER_9, MAP_LAYER_10); - - /** - * Clef qui represente l'option (c'est celle enregistrée dans le fichier de - * configuration). - */ - protected final String key; - - /** - * Clef de la propriété (javaBeans) de la configuration associé à cette - * option ({@code null} si pas associé à une propriété javaBeans). - */ - protected final String propertyKey; - - /** Clef i18n de description de l'option */ - protected final String description; - - /** Type de l'option */ - protected final Class<?> type; - - /** Valeur par défaut de l'option */ - protected String defaultValue; - - /** Drapeau pour savoir si on ne doit pas sauvegarder cette option */ - protected boolean _transient; - - /** Drapeau pour savoir si l'option est modifiable */ - protected boolean _final; - -// /** -// * Drapeau pour savoir si l'option requiere le mode admin -// * -// * @see ObserveRunner#isAdmin() -// */ -// protected boolean admin; - - ObserveSwingApplicationConfigOption(String key, - String description, - String defaultValue, - Class<?> type, - boolean _transient, - boolean _final) { - this(key, null, description, defaultValue, type, _transient, _final); - } - - ObserveSwingApplicationConfigOption(String key, - String propertyKey, - String description, - String defaultValue, - Class<?> type, - boolean _transient, - boolean _final) { - this.key = key; - this.description = description; - this.defaultValue = defaultValue; - this.type = type; - this._final = _final; - this._transient = _transient; - this.propertyKey = propertyKey; - } - - @Override - public boolean isFinal() { - return _final; - } - - @Override - public boolean isTransient() { - return _transient; - } - -// public boolean isAdmin() { -// return admin; -// } - - @Override - public String getDefaultValue() { - return defaultValue; - } - - @Override - public String getDescription() { - return t(description); - } - - @Override - public String getKey() { - return key; - } - - @Override - public Class<?> getType() { - return type; - } - - @Override - public void setDefaultValue(String defaultValue) { - this.defaultValue = defaultValue; - } - - @Override - public void setTransient(boolean _transient) { - this._transient = _transient; - } - - @Override - public void setFinal(boolean _final) { - this._final = _final; - } - -// public void setAdmin(boolean admin) { -// this.admin = admin; -// } - - public String getPropertyKey() { - return propertyKey; - } - - public static ImmutableList<ObserveSwingApplicationConfigOption> orderedByNameValues() { - - List<ObserveSwingApplicationConfigOption> values = Lists.newArrayList(values()); - Collections.sort(values, (o1, o2) -> o1.getKey().compareTo(o2.getKey())); - return ImmutableList.copyOf(values); - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/configuration/ObserveSwingApplicationConfigProvider.java b/observe-application-swing/src/main/java/fr/ird/observe/configuration/ObserveSwingApplicationConfigProvider.java deleted file mode 100644 index e222258..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/configuration/ObserveSwingApplicationConfigProvider.java +++ /dev/null @@ -1,60 +0,0 @@ -package fr.ird.observe.configuration; - -/*- - * #%L - * ObServe :: Application Swing - * %% - * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveCLAction; -import org.nuiton.config.ApplicationConfigProvider; -import org.nuiton.config.ConfigActionDef; -import org.nuiton.config.ConfigOptionDef; - -import java.util.Locale; - -import static org.nuiton.i18n.I18n.l; - -/** - * @author Sylvain Bavencoff - bavencoff@codelutin.com - */ -public class ObserveSwingApplicationConfigProvider implements ApplicationConfigProvider { - - public static final String OBSERVE_SWING_CONFIGURATION_PROVIDER_NAME = "observeSwing"; - - @Override - public String getName() { - return OBSERVE_SWING_CONFIGURATION_PROVIDER_NAME; - } - - @Override - public String getDescription(Locale locale) { - return l(locale, "observe.config.name"); - } - - @Override - public ConfigOptionDef[] getOptions() { - return ObserveSwingApplicationConfigOption.values(); - } - - @Override - public ConfigActionDef[] getActions() { - return ObserveCLAction.ActionDefinition.values(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/db/DataContext.java b/observe-application-swing/src/main/java/fr/ird/observe/db/DataContext.java deleted file mode 100644 index 4e643a6..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/db/DataContext.java +++ /dev/null @@ -1,778 +0,0 @@ -package fr.ird.observe.db; - -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.IdDtos; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.services.dto.seine.FloatingObjectDto; -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.services.dto.seine.SetSeineDto; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.jdesktop.beans.AbstractSerializableBean; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -public class DataContext extends AbstractSerializableBean { - - public static final String PROPERTY_OPEN_PROGRAM = "openProgram"; - - public static final String PROPERTY_OPEN_TRIP = "openTrip"; - public static final String PROPERTY_OPEN_TRIP_SEINE = "openTripSeine"; - public static final String PROPERTY_OPEN_TRIP_LONGLINE = "openTripLongline"; - - public static final String PROPERTY_OPEN_ROUTE = "openRoute"; - - public static final String PROPERTY_OPEN_ACTIVITY = "openActivity"; - public static final String PROPERTY_OPEN_ACTIVITY_SEINE = "openActivitySeine"; - public static final String PROPERTY_OPEN_ACTIVITY_LONGLINE = "openActivityLongline"; - - public static final String PROPERTY_OPEN_SET = "openSet"; - public static final String PROPERTY_OPEN_SET_SEINE = "openSetSeine"; - public static final String PROPERTY_OPEN_SET_LONGLINE = "openSetLongline"; - - public static final String PROPERTY_OPEN_PROGRAM_ID = "openProgramId"; - - public static final String PROPERTY_OPEN_TRIP_ID = "openTripId"; - public static final String PROPERTY_OPEN_TRIP_SEINE_ID = "openTripSeineId"; - public static final String PROPERTY_OPEN_TRIP_LONGLINE_ID = "openTripLonglineId"; - - public static final String PROPERTY_OPEN_ROUTE_ID = "openRouteId"; - - public static final String PROPERTY_OPEN_ACTIVITY_ID = "openActivityId"; - public static final String PROPERTY_OPEN_ACTIVITY_SEINE_ID = "openActivitySeineId"; - public static final String PROPERTY_OPEN_ACTIVITY_LONGLINE_ID = "openActivityLonglineId"; - - public static final String PROPERTY_OPEN_SET_ID = "openSetId"; - public static final String PROPERTY_OPEN_SET_SEINE_ID = "openSetSeineId"; - public static final String PROPERTY_OPEN_SET_LONGLINE_ID = "openSetLonglineId"; - - public static final String PROPERTY_SELECTED_PROGRAM_ID = "selectedProgramId"; - - public static final String PROPERTY_SELECTED_TRIP_ID = "selectedTripId"; - - public static final String PROPERTY_SELECTED_ROUTE_ID = "selectedRouteId"; - - public static final String PROPERTY_SELECTED_ACTIVITY_ID = "selectedActivityId"; - - public static final String PROPERTY_SELECTED_SET_ID = "selectedSetId"; - - public static final String PROPERTY_SELECTED_FLOATING_OBJECT_ID = "selectedFloatingObjectId"; - - public static final String PROPERTY_ENABLED = "enabled"; - - public static final String PROPERTY_SELECTION_CHANGED = "selectionChanged"; - - protected String openProgramId; - - protected String openTripSeineId; - - protected String openTripLonglineId; - - protected String openRouteId; - - protected String openActivitySeineId; - - protected String openActivityLonglineId; - - protected String openSetSeineId; - - protected String openSetLonglineId; - - protected String selectedProgramId; - - protected String selectedTripId; - - protected String selectedRouteId; - - protected String selectedActivityId; - - protected String selectedSetId; - - protected String selectedFloatingObjectId; - - protected boolean enabled; - - protected boolean selectionChanged; - - protected TripSeineDto validationTripSeine; - - protected RouteDto validationRoute; - - protected ActivitySeineDto validationActivitySeine; - - protected SetSeineDto validationSetSeine; - - protected FloatingObjectDto validationFloatingObject; - - /** Logger */ - private static final Log log = LogFactory.getLog(DataContext.class); - - private static final long serialVersionUID = 1L; - - public String getOpenProgramId() { - return openProgramId; - } - - public void setOpenProgramId(String openProgramId) { - String oldValue = getOpenProgramId(); - boolean oldValue2 = isOpenProgram(); - this.openProgramId = openProgramId; - firePropertyChange(PROPERTY_OPEN_PROGRAM_ID, oldValue, this.openProgramId); - firePropertyChange(PROPERTY_OPEN_PROGRAM, oldValue2, isOpenProgram()); - } - - public String getOpenTripId() { - return openTripSeineId != null ? openTripSeineId : openTripLonglineId; - } - - public String getOpenTripSeineId() { - return openTripSeineId; - } - - public String getOpenTripLonglineId() { - return openTripLonglineId; - } - - public void setOpenTripSeineId(String openTripId) { - String oldValue = getOpenTripId(); - String oldValue2 = getOpenTripSeineId(); - boolean oldValue3 = isOpenTrip(); - boolean oldValue4 = isOpenTripSeine(); - this.openTripSeineId = openTripId; - firePropertyChange(PROPERTY_OPEN_TRIP_ID, oldValue, this.openTripSeineId); - firePropertyChange(PROPERTY_OPEN_TRIP_SEINE_ID, oldValue2, this.openTripSeineId); - firePropertyChange(PROPERTY_OPEN_TRIP, oldValue3, isOpenTrip()); - firePropertyChange(PROPERTY_OPEN_TRIP_SEINE, oldValue4, isOpenTripSeine()); - } - - public void setOpenTripLonglineId(String openTripId) { - String oldValue = getOpenTripId(); - String oldValue2 = getOpenTripLonglineId(); - boolean oldValue3 = isOpenTrip(); - boolean oldValue4 = isOpenTripLongline(); - this.openTripLonglineId = openTripId; - firePropertyChange(PROPERTY_OPEN_TRIP_ID, oldValue, this.openTripLonglineId); - firePropertyChange(PROPERTY_OPEN_TRIP_LONGLINE_ID, oldValue2, this.openTripLonglineId); - firePropertyChange(PROPERTY_OPEN_TRIP, oldValue3, isOpenTrip()); - firePropertyChange(PROPERTY_OPEN_TRIP_LONGLINE, oldValue4, isOpenTripLongline()); - } - - public String getOpenRouteId() { - return openRouteId; - } - - public void setOpenRouteId(String openRouteId) { - String oldValue = getOpenRouteId(); - boolean oldValue2 = isOpenRoute(); - this.openRouteId = openRouteId; - firePropertyChange(PROPERTY_OPEN_ROUTE_ID, oldValue, openRouteId); - firePropertyChange(PROPERTY_OPEN_ROUTE, oldValue2, isOpenRoute()); - } - - public String getOpenActivityId() { - return openActivitySeineId != null ? openActivitySeineId : openActivityLonglineId; - } - - public String getOpenActivityLonglineId() { - return openActivityLonglineId; - } - - public String getOpenActivitySeineId() { - return openActivitySeineId; - } - - public void setOpenActivitySeineId(String openActivityId) { - String oldValue = getOpenActivityId(); - String oldValue2 = getOpenActivitySeineId(); - boolean oldValue3 = isOpenActivity(); - boolean oldValue4 = isOpenActivitySeine(); - this.openActivitySeineId = openActivityId; - firePropertyChange(PROPERTY_OPEN_ACTIVITY_ID, oldValue, this.openActivitySeineId); - firePropertyChange(PROPERTY_OPEN_ACTIVITY_SEINE_ID, oldValue2, this.openActivitySeineId); - firePropertyChange(PROPERTY_OPEN_ACTIVITY, oldValue3, isOpenActivity()); - firePropertyChange(PROPERTY_OPEN_ACTIVITY_SEINE, oldValue4, isOpenActivitySeine()); - } - - public void setOpenActivityLonglineId(String openActivityId) { - String oldValue = getOpenActivityId(); - String oldValue2 = getOpenActivityLonglineId(); - boolean oldValue3 = isOpenActivity(); - boolean oldValue4 = isOpenActivityLongline(); - this.openActivityLonglineId = openActivityId; - firePropertyChange(PROPERTY_OPEN_ACTIVITY_ID, oldValue, this.openActivityLonglineId); - firePropertyChange(PROPERTY_OPEN_ACTIVITY_LONGLINE_ID, oldValue2, this.openActivityLonglineId); - firePropertyChange(PROPERTY_OPEN_ACTIVITY, oldValue3, isOpenActivity()); - firePropertyChange(PROPERTY_OPEN_ACTIVITY_LONGLINE, oldValue4, isOpenActivityLongline()); - } - - public String getOpenSetId() { - return openSetSeineId != null ? openSetSeineId : openSetLonglineId; - } - - public String getOpenSetLonglineId() { - return openSetSeineId; - } - - public String getOpenSetSeineId() { - return openSetLonglineId; - } - - public void setOpenSetSeineId(String openSetId) { - String oldValue = getOpenSetId(); - String oldValue2 = getOpenSetSeineId(); - boolean oldValue3 = isOpenSet(); - boolean oldValue4 = isOpenSetSeine(); - this.openSetSeineId = openSetId; - firePropertyChange(PROPERTY_OPEN_SET_ID, oldValue, this.openSetSeineId); - firePropertyChange(PROPERTY_OPEN_SET_SEINE_ID, oldValue2, this.openSetSeineId); - firePropertyChange(PROPERTY_OPEN_SET, oldValue3, isOpenSet()); - firePropertyChange(PROPERTY_OPEN_SET_SEINE, oldValue4, isOpenSetSeine()); - } - - public void setOpenSetLonglineId(String openSetId) { - String oldValue = getOpenSetId(); - String oldValue2 = getOpenSetLonglineId(); - boolean oldValue3 = isOpenSet(); - boolean oldValue4 = isOpenSetLongline(); - this.openSetLonglineId = openSetId; - firePropertyChange(PROPERTY_OPEN_SET_ID, oldValue, this.openSetLonglineId); - firePropertyChange(PROPERTY_OPEN_SET_LONGLINE_ID, oldValue2, this.openSetLonglineId); - firePropertyChange(PROPERTY_OPEN_SET, oldValue3, isOpenSet()); - firePropertyChange(PROPERTY_OPEN_SET_LONGLINE, oldValue4, isOpenSetLongline()); - } - - public String getSelectedProgramId() { - return selectedProgramId; - } - - public void setSelectedProgramId(String selectedProgramId) { - String oldValue = getSelectedProgramId(); - this.selectedProgramId = selectedProgramId; - firePropertyChange(PROPERTY_SELECTED_PROGRAM_ID, oldValue, this.selectedProgramId); - } - - public String getSelectedTripId() { - return selectedTripId; - } - - public String getSelectedTripLonglineId() { - return isSelectedTripLongline() ? getSelectedTripId() : null; - } - - public String getSelectedTripSeineId() { - return isSelectedTripSeine() ? getSelectedTripId() : null; - } - - public void setSelectedTripId(String selectedTripId) { - String oldValue = getSelectedTripId(); - this.selectedTripId = selectedTripId; - firePropertyChange(PROPERTY_SELECTED_TRIP_ID, oldValue, this.selectedTripId); - } - - public boolean isSelectedTripLongline() { - return selectedTripId != null && IdDtos.isLonglineId(selectedTripId); - } - - public boolean isSelectedTripSeine() { - return selectedTripId != null && IdDtos.isSeineId(selectedTripId); - } - - public String getSelectedRouteId() { - return selectedRouteId; - } - - public void setSelectedRouteId(String selectedRouteId) { - String oldValue = getSelectedRouteId(); - this.selectedRouteId = selectedRouteId; - firePropertyChange(PROPERTY_SELECTED_ROUTE_ID, oldValue, selectedRouteId); - } - - public String getSelectedActivityId() { - return selectedActivityId; - } - - public String getSelectedActivityLonglineId() { - return isSelectedActivityLongline() ? getSelectedActivityId() : null; - } - - public String getSelectedActivitySeineId() { - return isSelectedActivitySeine() ? getSelectedActivityId() : null; - } - - public boolean isSelectedActivityLongline() { - return selectedActivityId != null && IdDtos.isLonglineId(selectedActivityId); - } - - public boolean isSelectedActivitySeine() { - return selectedActivityId != null && IdDtos.isSeineId(selectedActivityId); - } - - public void setSelectedActivityId(String selectedActivityId) { - String oldValue = getSelectedActivityId(); - this.selectedActivityId = selectedActivityId; - firePropertyChange(PROPERTY_SELECTED_ACTIVITY_ID, oldValue, this.selectedActivityId); - } - - public String getSelectedSetId() { - return selectedSetId; - } - - public String getSelectedSetLonglineId() { - return isSelectedActivityLongline() ? getSelectedSetId() : null; - } - - public String getSelectedSetSeineId() { - return isSelectedActivitySeine() ? getSelectedSetId() : null; - } - - public void setSelectedSetId(String selectedSetId) { - String oldValue = getSelectedSetId(); - this.selectedSetId = selectedSetId; - firePropertyChange(PROPERTY_SELECTED_SET_ID, oldValue, this.selectedSetId); - } - - public String getSelectedFloatingObjectId() { - return selectedFloatingObjectId; - } - - public void setSelectedFloatingObjectId(String selectedFloatingObjectId) { - String oldValue = getSelectedFloatingObjectId(); - this.selectedFloatingObjectId = selectedFloatingObjectId; - firePropertyChange(PROPERTY_SELECTED_FLOATING_OBJECT_ID, oldValue, this.selectedFloatingObjectId); - } - - public boolean isEnabled() { - return enabled; - } - - public boolean getEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - boolean oldValue = getEnabled(); - this.enabled = enabled; - firePropertyChange(PROPERTY_ENABLED, oldValue, enabled); - } - - public boolean isSelectionChanged() { - return selectionChanged; - } - - public boolean getSelectionChanged() { - return selectionChanged; - } - - public void setSelectionChanged(boolean selectionChanged) { - boolean oldValue = getSelectionChanged(); - this.selectionChanged = selectionChanged; - firePropertyChange(PROPERTY_SELECTION_CHANGED, oldValue, selectionChanged); - } - - public DataContext() { - } - - static DataContextType[] types; - - static DataContextType[] reverseTypes; - - public DataContextType[] getTypes() { - if (types == null) { - types = DataContextType.values(); - } - return types; - } - - public DataContextType[] getReverseTypes() { - if (reverseTypes == null) { - List<DataContextType> list = Arrays.asList(DataContextType.values()); - Collections.reverse(list); - reverseTypes = list.toArray(new DataContextType[list.size()]); - } - - return reverseTypes; - } - - public String getHigherOpenId() { - for (DataContextType type : getReverseTypes()) { - String result = type.getOpenId(this); - if (result != null) { - return result; - } - } - return null; - } - - public String getHigherSelectedId() { - - for (DataContextType type : getReverseTypes()) { - String result = type.getSelectedId(this); - if (result != null) { - return result; - } - } - return null; - } - - public String[] getSelectedIds() { - - List<String> ids = new ArrayList<>(); - - for (DataContextType type : getTypes()) { - String result = type.getSelectedId(this); - if (result != null) { - ids.add(result); - } - } - return ids.toArray(new String[ids.size()]); - } - - public String[] getOpenIds() { - - List<String> ids = new ArrayList<>(); - - for (DataContextType type : getTypes()) { - String result = type.getOpenId(this); - if (result != null) { - ids.add(result); - } - } - return ids.toArray(new String[ids.size()]); - } - - public String[] getOpenIds(Class<?> type) { - - String[] result = null; - - if (isOpenProgram()) { - - List<String> ids = new ArrayList<>(); - ids.add(getOpenProgramId()); - - if (!ProgramDto.class.equals(type) && isOpenTrip()) { - - String tripId = getOpenTripId(); - ids.add(tripId); - - if (IdDtos.isTripSeineId(tripId)) { - - // on a seine trip - if (!IdDtos.isTripClass(type) && isOpenRoute()) { - - ids.add(getOpenRouteId()); - - if (!RouteDto.class.equals(type) && isOpenActivitySeine()) { - - ids.add(getOpenActivitySeineId()); - - if (!IdDtos.isActivityClass(type) && isOpenSetSeine()) { - ids.add(getOpenSetSeineId()); - } - } - } - - } else { - - // on a longline trip - if (!IdDtos.isTripClass(type) && isOpenActivityLongline()) { - - ids.add(getOpenActivityLonglineId()); - - if (!IdDtos.isActivityClass(type) && isOpenSetLongline()) { - ids.add(getOpenSetLonglineId()); - } - - } - - } - - } - - result = ids.toArray(new String[ids.size()]); - - } - - return result; - } - - public boolean isOpenProgram() { - return openProgramId != null; - } - - public boolean isOpenTrip() { - return isOpenTripLongline() || isOpenTripSeine(); - } - - public boolean isOpenTripLongline() { - return openTripLonglineId != null; - } - - public boolean isOpenTripSeine() { - return openTripSeineId != null; - } - - public boolean isOpenRoute() { - return openRouteId != null; - } - - public boolean isOpenActivity() { - return isOpenActivityLongline() || isOpenActivitySeine(); - } - - public boolean isOpenActivityLongline() { - return openActivityLonglineId != null; - } - - public boolean isOpenActivitySeine() { - return openActivitySeineId != null; - } - - - public boolean isOpenSet() { - return isOpenSetLongline() || isOpenSetSeine(); - } - - public boolean isOpenSetLongline() { - return openSetLonglineId != null; - } - - public boolean isOpenSetSeine() { - return openSetSeineId != null; - } - - public boolean isSelectedOpen(Class<?> type) { - - for (DataContextType entityType : DataContextType.values()) { - if (entityType.acceptType(type)) { - - // bon type trouve - - String openId = entityType.getOpenId(this); - String selectedId = entityType.getSelectedId(this); - if (selectedId == null || openId == null) { - - // pas selectionne ou rien d'ouvert - return false; - } - - return selectedId.equals(openId); - } - } - - // type non trouve - return false; - } - - public void populateSelectedIds(String... selectedId) { - - List<String> oldSelection = Arrays.asList(getSelectedIds()); - - if (log.isDebugEnabled()) { - log.debug("old selection = " + oldSelection); - } - - // on nettoye toujours toutes les anciennes sélections - // avant de positionner les nouvelles - resetSelect(); - - List<String> realSelection = null; - if (selectedId != null && selectedId.length > 0) { - - realSelection = new ArrayList<>(); - for (String s : selectedId) { - if (s == null) { - - // ce cas peut arriver lors de la creation d'un nouvel objet - continue; - } - DataContextType type = DataContextType.acceptId(s); - if (type == null) { - - if (log.isWarnEnabled()) { - log.warn("Could not find type for id : " + s); - } - continue; - } - - type.setSelectedId(this, s); - realSelection.add(s); - if (log.isDebugEnabled()) { - log.debug("add selectedId : " + s); - } - } - } - - if (oldSelection.equals(realSelection)) { - - // rien a change - if (log.isDebugEnabled()) { - log.debug("selection does not changed"); - } - return; - } - - if (log.isInfoEnabled()) { - log.info("new selection = " + realSelection); - } - - // on change toujours l'état de selection - - setSelectionChanged(true); - } - - public void populateOpens(String... openIds) { - if (!getEnabled()) { - - if (log.isWarnEnabled()) { - log.warn(this + " is not enabled"); - } - // service non initialisé - resetOpen(); - return; - } - - List<String> oldSelection = Arrays.asList(getOpenIds()); - List<String> realSelection = new ArrayList<>(); - - if (openIds != null && openIds.length > 0) { - - for (String s : openIds) { - if (s == null) { - - // ce cas peut arriver lors de la creation d'un nouvel objet - continue; - } - DataContextType type = DataContextType.acceptId(s); - if (type == null) { - - if (log.isWarnEnabled()) { - log.warn("Could not find type for id : " + s); - } - continue; - } - - if (!type.canOpen()) { - - // pas de traitement open - continue; - } - - type.setOpenId(this, s); - realSelection.add(s); - if (log.isDebugEnabled()) { - log.debug("add openId : " + s); - } - } - } - - // if only the program is open, remove it - if (realSelection.size() == 1) { - setOpenProgramId(null); - realSelection.clear(); - } - - if (oldSelection.equals(realSelection)) { - - // rien a change - if (log.isDebugEnabled()) { - log.debug("openIds selection does not changed"); - } - return; - } - - if (log.isInfoEnabled()) { - log.info("new openIds selection = " + realSelection); - log.info("old openIds selection = " + oldSelection); - } - - for (String s : oldSelection) { - - if (realSelection.contains(s)) { - // pas bouge rien a faire - continue; - } - - DataContextType type = DataContextType.acceptId(s); - if (type == null) { - - if (log.isWarnEnabled()) { - log.warn("Could not find type for id : " + s); - } - continue; - } - - if (!type.canOpen()) { - - // pas de traitement open - continue; - } - - String newId = type.getOpenId(this); - if (newId != null) { - - if (log.isInfoEnabled()) { - log.info("will remove old obsolete open id : " + s); - } - - // plus d'id pour ce type, on le supprime - type.setOpenId(this, null); - } - } - } - - protected void reset() { - resetOpen(); - resetSelect(); - } - - protected void resetSelect() { - setSelectedProgramId(null); - setSelectedTripId(null); - setSelectedRouteId(null); - setSelectedActivityId(null); - setSelectedFloatingObjectId(null); - setSelectedSetId(null); - selectionChanged = false; - } - - public void resetOpen() { - setOpenProgramId(null); - setOpenTripSeineId(null); - setOpenTripLonglineId(null); - setOpenRouteId(null); - setOpenActivitySeineId(null); - setOpenActivityLonglineId(null); - } - - protected void firePropertyChange(String propertyName, Object newValue) { - firePropertyChange(propertyName, null, newValue); - } - -} //DataContext diff --git a/observe-application-swing/src/main/java/fr/ird/observe/db/ObserveSwingDataSource.java b/observe-application-swing/src/main/java/fr/ird/observe/db/ObserveSwingDataSource.java deleted file mode 100644 index c6ab886..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/db/ObserveSwingDataSource.java +++ /dev/null @@ -1,723 +0,0 @@ -package fr.ird.observe.db; - -/*- - * #%L - * ObServe :: Application Swing - * %% - * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableList; -import com.google.common.collect.ImmutableMap; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.db.event.ObserveSwingDataSourceEvent; -import fr.ird.observe.db.event.ObserveSwingDataSourceListener; -import fr.ird.observe.services.ObserveService; -import fr.ird.observe.services.ObserveServiceInitializer; -import fr.ird.observe.services.ObserveServiceMainFactory; -import fr.ird.observe.services.ObserveServicesProvider; -import fr.ird.observe.services.ObserveSpeciesListConfiguration; -import fr.ird.observe.services.configuration.ObserveDataSourceConfiguration; -import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationAndConnection; -import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationRest; -import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaH2; -import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaPG; -import fr.ird.observe.services.configuration.ObserveDataSourceConnection; -import fr.ird.observe.services.configuration.ObserveDataSourceInformation; -import fr.ird.observe.services.configuration.ObserveDataSourceType; -import fr.ird.observe.services.dto.DataSourceCreateConfigurationDto; -import fr.ird.observe.services.dto.DataSourceCreateWithNoReferentialImportException; -import fr.ird.observe.services.dto.IncompatibleDataSourceCreateConfigurationException; -import fr.ird.observe.services.dto.ObserveDbUserDto; -import fr.ird.observe.services.dto.constants.ReferentialLocale; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.ReferentialReferenceSet; -import fr.ird.observe.services.service.BabModelVersionException; -import fr.ird.observe.services.service.DataSourceService; -import fr.ird.observe.services.service.DatabaseConnexionNotAuthorizedException; -import fr.ird.observe.services.service.DatabaseDestroyNotAuthorizedException; -import fr.ird.observe.services.service.DatabaseNotFoundException; -import fr.ird.observe.services.service.ObserveReferentialCache; -import fr.ird.observe.services.service.PingService; -import fr.ird.observe.services.service.ReferentialService; -import fr.ird.observe.services.service.SqlScriptProducerService; -import fr.ird.observe.services.service.actions.consolidate.ConsolidateDataService; -import fr.ird.observe.services.service.actions.export.ReplicateTripService; -import fr.ird.observe.services.service.actions.report.ReportService; -import fr.ird.observe.services.service.actions.synchro.data.DataSynchronizeService; -import fr.ird.observe.services.service.actions.synchro.referential.diff.ReferentialSynchronizeDiffService; -import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeLocalService; -import fr.ird.observe.services.service.actions.synchro.referential.ng.ReferentialSynchronizeService; -import fr.ird.observe.services.service.actions.validate.ValidateService; -import fr.ird.observe.services.service.longline.ActivityLongLineEncounterService; -import fr.ird.observe.services.service.longline.ActivityLongLineSensorUsedService; -import fr.ird.observe.services.service.longline.ActivityLonglineService; -import fr.ird.observe.services.service.longline.BranchlineService; -import fr.ird.observe.services.service.longline.SetLonglineCatchService; -import fr.ird.observe.services.service.longline.SetLonglineDetailCompositionService; -import fr.ird.observe.services.service.longline.SetLonglineGlobalCompositionService; -import fr.ird.observe.services.service.longline.SetLonglineService; -import fr.ird.observe.services.service.longline.TdrService; -import fr.ird.observe.services.service.longline.TripLonglineGearUseService; -import fr.ird.observe.services.service.longline.TripLonglineService; -import fr.ird.observe.services.service.seine.ActivitySeineObservedSystemService; -import fr.ird.observe.services.service.seine.ActivitySeineService; -import fr.ird.observe.services.service.seine.FloatingObjectService; -import fr.ird.observe.services.service.seine.NonTargetCatchService; -import fr.ird.observe.services.service.seine.NonTargetSampleService; -import fr.ird.observe.services.service.seine.ObjectObservedSpeciesService; -import fr.ird.observe.services.service.seine.ObjectSchoolEstimateService; -import fr.ird.observe.services.service.seine.RouteService; -import fr.ird.observe.services.service.seine.SchoolEstimateService; -import fr.ird.observe.services.service.seine.SetSeineService; -import fr.ird.observe.services.service.seine.TargetCatchService; -import fr.ird.observe.services.service.seine.TargetSampleService; -import fr.ird.observe.services.service.seine.TransmittingBuoyOperationService; -import fr.ird.observe.services.service.seine.TripSeineGearUseService; -import fr.ird.observe.services.service.seine.TripSeineService; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.jdesktop.beans.AbstractSerializableBean; -import org.nuiton.version.Version; - -import javax.swing.JOptionPane; -import javax.swing.event.EventListenerList; -import java.io.Closeable; -import java.io.File; -import java.util.Locale; -import java.util.Set; - -import static org.nuiton.i18n.I18n.t; - -/** - * @author Sylvain Bavencoff - bavencoff@codelutin.com - */ -public class ObserveSwingDataSource extends AbstractSerializableBean implements Closeable, ObserveServicesProvider { - - private static final long serialVersionUID = 1L; - - private static final Log log = LogFactory.getLog(ObserveSwingDataSource.class); - - /** le conteneur de listeners */ - protected final EventListenerList listenerList; - - protected final ObserveDataSourceConfiguration configuration; - - protected final ObserveReferentialCache referentialCache; - - protected ObserveDataSourceConnection connection; - - // indique que la connexion a expiré mais que la source n'est pas complétement fermer - private boolean expired; - - public ObserveSwingDataSource(ObserveDataSourceConfiguration configuration) { - this.configuration = configuration; - this.listenerList = new EventListenerList(); - this.referentialCache = new ObserveReferentialCache(); - this.expired = false; - } - - public ObserveDataSourceConfiguration getConfiguration() { - return configuration; - } - - public ObserveDataSourceConnection getConnection() { - return connection; - } - - public String getLabel() { - return configuration.getLabel(); - } - - public boolean isSqlDataSource() { - return ObserveDataSourceType.SQL == configuration.getType(); - } - -// public String getAuthenticationToken() { -// String result = null; -// if (connection != null) { -// result = connection.getAuthenticationToken(); -// } -// return result; -// } - - public boolean canWriteData() { - boolean result = connection != null && connection.canWriteData(); - return result; - } - - public Version getVersion() { - Version result = null; - if (connection != null) { - result = connection.getVersion(); - } - return result; - } - - public boolean canReadReferential() { - boolean result = connection != null && connection.canReadReferential(); - return result; - } - - public boolean canReadData() { - boolean result = connection != null && connection.canReadData(); - return result; - } - - public boolean canWriteReferential() { - boolean result = connection != null && connection.canWriteReferential(); - return result; - } - - public ObserveDataSourceInformation getInformation() { - return new ObserveDataSourceInformation( - canReadReferential(), - canWriteReferential(), - canReadData(), - canWriteData(), - getVersion(), - getVersion(), - ImmutableList.of()); - } - - public void open() throws DatabaseConnexionNotAuthorizedException, DatabaseNotFoundException, BabModelVersionException { - - checkIsNotAlreadyOpen(); - - fireNewMessage(t("observe.storage.message.opening", getLabel())); - fireOpening(); - - - DataSourceService dataSourceService = newDataSourceService(); - - connection = dataSourceService.open(configuration); - - fireNewMessage(t("observe.storage.message.opened", getLabel())); - fireOpened(); - } - - public void create(DataSourceCreateConfigurationDto createDto) - throws IncompatibleDataSourceCreateConfigurationException, DataSourceCreateWithNoReferentialImportException, - DatabaseNotFoundException, DatabaseConnexionNotAuthorizedException, BabModelVersionException { - - checkIsNotAlreadyOpen(); - - fireNewMessage(t("observe.storage.message.creating", getLabel())); - fireOpening(); - - DataSourceService dataSourceService = newDataSourceService(); - - connection = dataSourceService.create(configuration, createDto); - - fireNewMessage(t("observe.storage.message.created", getLabel())); - fireOpened(); - } - - @Override - public void close() { - - checkIsOpen(); - - fireNewMessage(t("observe.storage.message.closing", getLabel())); - fireClosing(); - - referentialCache.close(); - - try { - // si la connection a expirée la source a deja été fermer pas le serveur - if (!expired) { - DataSourceService dataSourceService = newDataSourceService(); - - dataSourceService.close(); - } - } finally { - connection = null; - expired = false; - - fireNewMessage(t("observe.storage.message.closed", getLabel())); - fireClosed(); - } - - } - - public void destroy() throws DatabaseDestroyNotAuthorizedException { - - checkIsOpen(); - - fireNewMessage(t("observe.storage.message.destroying", getLabel())); - fireClosing(); - - referentialCache.close(); - - DataSourceService dataSourceService = newDataSourceService(); - - dataSourceService.destroy(); - - connection = null; - - fireNewMessage(t("observe.storage.message.destroyed", getLabel())); - fireClosed(); - - } - - public Set<ObserveDbUserDto> getUsers() { - - checkIsNotOpen(); - - DataSourceService dataSourceService = newDataSourceService(); - - Set<ObserveDbUserDto> users = dataSourceService.getUsers(getConfiguration()); - - return users; - } - - - public void applySecurity(Set<ObserveDbUserDto> users) { - - checkIsNotOpen(); - - DataSourceService dataSourceService = newDataSourceService(); - - dataSourceService.applySecurity(getConfiguration(), users); - } - - public void migrateData(ObserveDataSourceInformation dataSourceInformation, Version targetVersion) { - - checkIsNotOpen(); - - Version dbVersion = dataSourceInformation.getVersion(); - if (!dataSourceInformation.getMigrations().isEmpty()) { - - if (dbVersion.before(dataSourceInformation.getMinnimumVersion())) { - - JOptionPane.showMessageDialog( - null, - t("observe.storage.migrate.not.possible.before.version.3.0.message", targetVersion, dbVersion), - t("observe.storage.migrate.not.possible.before.version.3.0.title", targetVersion), - JOptionPane.WARNING_MESSAGE); - - } else { - - int answer = JOptionPane.showConfirmDialog( - null, - t("observe.storage.migrate.askUser.message", dbVersion, targetVersion, dataSourceInformation.getMigrations()), - t("observe.storage.migrate.askUser.title", targetVersion), - JOptionPane.YES_NO_OPTION, - JOptionPane.WARNING_MESSAGE); - - if (answer == JOptionPane.YES_OPTION) { - - DataSourceService dataSourceService = newDataSourceService(); - - - if (log.isInfoEnabled()) { - log.info("Migrate data source " + getLabel() + " in " + dbVersion + " to " + targetVersion); - } - - dataSourceService.migrateData(getConfiguration()); - } - } - } - - } - - public ImmutableMap<Class<?>, ReferentialReferenceSet<?>> updateReferentialReferenceSetsCache(String referentialReferenceSetsRequestName) { - - ReferentialService referentialService = newReferentialService(); - return referentialCache.loadReferenceSets(referentialService, referentialReferenceSetsRequestName); - - } - - protected <D extends ReferentialDto> ReferentialReferenceSet<D> getReferentialReferenceSet(Class<D> type) { - - checkIsOpen(); - - ReferentialService referentialService = newReferentialService(); - return referentialCache.getReferentialReferenceSet(referentialService, type); - } - - public <D extends ReferentialDto> Set<ReferentialReference<D>> getReferentialReferences(Class<D> type) { - - ReferentialReferenceSet<D> referentialReferenceSet = getReferentialReferenceSet(type); - return referentialReferenceSet.getReferences(); - - } - - public <D extends ReferentialDto> ReferentialReference<D> getReferentialReference(Class<D> type, String id) { - - ReferentialReferenceSet<D> referentialReferenceSet = getReferentialReferenceSet(type); - return referentialReferenceSet.getReferenceById(id); - - } - - public boolean isOpen() { - return connection != null; - } - - @Override - public SetLonglineService newSetLonglineService() { - return newService(SetLonglineService.class); - } - - public ObserveDataSourceInformation checkCanConnect() throws DatabaseConnexionNotAuthorizedException, DatabaseNotFoundException { - - checkIsNotAlreadyOpen(); - - DataSourceService dataSourceService = newDataSourceService(); - - ObserveDataSourceInformation dataSourceInformation = dataSourceService.checkCanConnect(configuration); - - return dataSourceInformation; - - } - - public boolean isLocal() { - return configuration instanceof ObserveDataSourceConfigurationTopiaH2; - } - - public boolean isRemote() { - return configuration instanceof ObserveDataSourceConfigurationTopiaPG; - } - - public boolean isServer() { - return configuration instanceof ObserveDataSourceConfigurationRest; - } - - public void addObserveSwingDataSourceListener(ObserveSwingDataSourceListener listener) { - listenerList.add(ObserveSwingDataSourceListener.class, listener); - } - - public ObserveSwingDataSourceListener[] getObserveSwingDataSourceListener() { - return listenerList.getListeners(ObserveSwingDataSourceListener.class); - } - -// public boolean containsObserveSwingDataSourceListener(ObserveSwingDataSourceListener listener) { -// ObserveSwingDataSourceListener[] listeners = getObserveSwingDataSourceListener(); -// for (ObserveSwingDataSourceListener l : listeners) { -// if (l.equals(listener)) { -// return true; -// } -// } -// return false; -// } - - public void removeObserveSwingDataSourceListener(ObserveSwingDataSourceListener listener) { - if (log.isInfoEnabled()) { - log.info("removing listener " + listener); - } - listenerList.remove(ObserveSwingDataSourceListener.class, listener); - } - - public void removeObserveSwingDataSourceListeners() { - // remove all listeners - for (ObserveSwingDataSourceListener listener : getObserveSwingDataSourceListener()) { - removeObserveSwingDataSourceListener(listener); - } - } - - public void fireNewMessage(String message) { - fireNewMessage(message, ObserveSwingDataSourceEvent.MessageLevel.INFO); - } - - public void fireNewMessage(String message, ObserveSwingDataSourceEvent.MessageLevel level) { - ObserveSwingDataSourceEvent evt = new ObserveSwingDataSourceEvent(this, message, level); - for (ObserveSwingDataSourceListener listener : getObserveSwingDataSourceListener()) { - listener.onNewMessage(evt); - } - } - - public boolean isExpired() { - return expired; - } - - public void expired() { - this.expired = true; - } - - protected ObserveServiceInitializer getObserveServiceInitializer() { - - ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); - - ObserveSwingApplicationConfig config = context.getConfig(); - - Locale locale = config.getLocale(); - - File tmpDirectory = config.getTmpDirectory(); - - ReferentialLocale referentialLocale = ReferentialLocale.valueOf(locale); - - ObserveDataSourceConfigurationAndConnection configurationAndConnection = new ObserveDataSourceConfigurationAndConnection(configuration, connection); - - ObserveSpeciesListConfiguration speciesListConfiguration = new ObserveSpeciesListConfiguration(); - speciesListConfiguration.setSpeciesListLonglineCatchId(config.getSpeciesListLonglineCatchId()); - speciesListConfiguration.setSpeciesListLonglineDepredatorId(config.getSpeciesListLonglineDepredatorId()); - speciesListConfiguration.setSpeciesListLonglineEncounterId(config.getSpeciesListLonglineEncounterId()); - speciesListConfiguration.setSpeciesListSeineNonTargetCatchId(config.getSpeciesListSeineNonTargetCatchId()); - speciesListConfiguration.setSpeciesListSeineObjectObservedSpeciesId(config.getSpeciesListSeineObjectObservedSpeciesId()); - speciesListConfiguration.setSpeciesListSeineObjectSchoolEstimateId(config.getSpeciesListSeineObjectSchoolEstimateId()); - speciesListConfiguration.setSpeciesListSeineSchoolEstimateId(config.getSpeciesListSeineSchoolEstimateId()); - speciesListConfiguration.setSpeciesListSeineTargetCatchId(config.getSpeciesListSeineTargetCatchId()); - - ObserveServiceInitializer observeServiceInitializer = ObserveServiceInitializer.create( - locale, - referentialLocale, - tmpDirectory, - speciesListConfiguration, - configurationAndConnection); - - return observeServiceInitializer; - } - - protected void fireOpening() { - ObserveSwingDataSourceEvent evt = new ObserveSwingDataSourceEvent(this); - for (ObserveSwingDataSourceListener listener : getObserveSwingDataSourceListener()) { - listener.onOpening(evt); - } - } - - protected void fireOpened() { - ObserveSwingDataSourceEvent evt = new ObserveSwingDataSourceEvent(this); - for (ObserveSwingDataSourceListener listener : getObserveSwingDataSourceListener()) { - listener.onOpened(evt); - } - } - - protected void fireClosing() { - ObserveSwingDataSourceEvent evt = new ObserveSwingDataSourceEvent(this); - for (ObserveSwingDataSourceListener listener : getObserveSwingDataSourceListener()) { - listener.onClosing(evt); - } - } - - protected void fireClosed() { - ObserveSwingDataSourceEvent evt = new ObserveSwingDataSourceEvent(this); - for (ObserveSwingDataSourceListener listener : getObserveSwingDataSourceListener()) { - listener.onClosed(evt); - } - } - - protected void checkIsOpen() { - Preconditions.checkState(isOpen(), "Connection is not open"); - } - - protected void checkIsNotAlreadyOpen() { - Preconditions.checkState(!isOpen(), "Connection is already open"); - } - - protected void checkIsNotOpen() { - Preconditions.checkState(!isOpen(), "Connection is open"); - } - - private <S extends ObserveService> S newService(Class<S> serviceType) { - - ObserveServiceInitializer observeServiceInitializer = getObserveServiceInitializer(); - - ObserveServiceMainFactory serviceFactory = ObserveServiceMainFactory.get(); - - S service = serviceFactory.newService(observeServiceInitializer, serviceType); - return service; - } - - @Override - public SqlScriptProducerService newSqlScriptProducerService() { - return newService(SqlScriptProducerService.class); - } - - @Override - public ValidateService newValidateService() { - return newService(ValidateService.class); - } - - @Override - public ReportService newReportService() { - return newService(ReportService.class); - } - - @Override - public PingService newPingService() { - return newService(PingService.class); - } - - @Override - public ReplicateTripService newReplicateTripService() { - return newService(ReplicateTripService.class); - } - - @Override - public ConsolidateDataService newConsolidateDataService() { - return newService(ConsolidateDataService.class); - } - - @Override - public UnidirectionalReferentialSynchronizeLocalService newUnidirectionalReferentialSynchronizeLocalService() { - return newService(UnidirectionalReferentialSynchronizeLocalService.class); - } - - @Override - public DataSynchronizeService newDataSynchronizeService() { - return newService(DataSynchronizeService.class); - } - - @Override - public ReferentialSynchronizeService newReferentialSynchronizeService() { - return newService(ReferentialSynchronizeService.class); - } - - @Override - public ReferentialSynchronizeDiffService newReferentialSynchronizeDiffService() { - return newService(ReferentialSynchronizeDiffService.class); - } - - @Override - public DataSourceService newDataSourceService() { - return newService(DataSourceService.class); - } - - @Override - public ReferentialService newReferentialService() { - return newService(ReferentialService.class); - } - - @Override - public TripSeineService newTripSeineService() { - return newService(TripSeineService.class); - } - - @Override - public RouteService newRouteService() { - return newService(RouteService.class); - } - - @Override - public FloatingObjectService newFloatingObjectService() { - return newService(FloatingObjectService.class); - } - - @Override - public ActivitySeineService newActivitySeineService() { - return newService(ActivitySeineService.class); - } - - @Override - public SetSeineService newSetSeineService() { - return newService(SetSeineService.class); - } - - @Override - public TripLonglineService newTripLonglineService() { - return newService(TripLonglineService.class); - } - - @Override - public ActivityLonglineService newActivityLonglineService() { - return newService(ActivityLonglineService.class); - } - - @Override - public ActivitySeineObservedSystemService newActivitySeineObservedSystemService() { - return newService(ActivitySeineObservedSystemService.class); - } - - @Override - public SetLonglineGlobalCompositionService newSetLonglineGlobalCompositionService() { - return newService(SetLonglineGlobalCompositionService.class); - } - - @Override - public SetLonglineDetailCompositionService newSetLonglineDetailCompositionService() { - return newService(SetLonglineDetailCompositionService.class); - } - - @Override - public TransmittingBuoyOperationService newTransmittingBuoyOperationService() { - return newService(TransmittingBuoyOperationService.class); - } - - @Override - public BranchlineService newBranchlineService() { - return newService(BranchlineService.class); - } - - @Override - public SetLonglineCatchService newSetLonglineCatchService() { - return newService(SetLonglineCatchService.class); - } - - @Override - public ActivityLongLineEncounterService newActivityLongLineEncounterService() { - return newService(ActivityLongLineEncounterService.class); - } - - @Override - public TripLonglineGearUseService newTripLonglineGearUseService() { - return newService(TripLonglineGearUseService.class); - } - - @Override - public ActivityLongLineSensorUsedService newActivityLongLineSensorUsedService() { - return newService(ActivityLongLineSensorUsedService.class); - } - - @Override - public TdrService newTdrService() { - return newService(TdrService.class); - } - - @Override - public TripSeineGearUseService newTripSeineGearUseService() { - return newService(TripSeineGearUseService.class); - } - - @Override - public NonTargetCatchService newNonTargetCatchService() { - return newService(NonTargetCatchService.class); - } - - @Override - public NonTargetSampleService newNonTargetSampleService() { - return newService(NonTargetSampleService.class); - } - - @Override - public ObjectObservedSpeciesService newObjectObservedSpeciesService() { - return newService(ObjectObservedSpeciesService.class); - } - - @Override - public ObjectSchoolEstimateService newObjectSchoolEstimateService() { - return newService(ObjectSchoolEstimateService.class); - } - - @Override - public SchoolEstimateService newSchoolEstimateService() { - return newService(SchoolEstimateService.class); - } - - @Override - public TargetCatchService newTargetCatchService() { - return newService(TargetCatchService.class); - } - - @Override - public TargetSampleService newTargetSampleService() { - return newService(TargetSampleService.class); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/db/constants/ConnexionStatus.java b/observe-application-swing/src/main/java/fr/ird/observe/db/constants/ConnexionStatus.java deleted file mode 100644 index f87c840..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/db/constants/ConnexionStatus.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.constants; - -import static org.nuiton.i18n.I18n.n; - -/** - * Pour caractériser l'état d'une connexion à un service de persistance. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public enum ConnexionStatus { - - /** lorsque la connexion n'as pas encore ete testee */ - UNTESTED( - n("observe.storage.connexionStatut.untested"), - n("observe.storage.connexionStatut.untested.description") - ), - /** lorsque le test de connexion a abouti */ - SUCCESS( - n("observe.storage.connexionStatut.success"), - n("observe.storage.connexionStatut.success.description") - ), - /** lorsque le test de connexion a echoue */ - FAILED( - n("observe.storage.connexionStatut.failed"), - n("observe.storage.connexionStatut.failed.description") - ); - - private final String label; - - private final String description; - - ConnexionStatus(String label, String description) { - this.label = label; - this.description = description; - } - - public String getLabel() { - return label; - } - - public String getDescription() { - return description; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/db/constants/CreationMode.java b/observe-application-swing/src/main/java/fr/ird/observe/db/constants/CreationMode.java deleted file mode 100644 index d895f88..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/db/constants/CreationMode.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.constants; - -import fr.ird.observe.services.dto.DataSourceCreateConfigurationDto; - -import static org.nuiton.i18n.I18n.n; - -/** - * Pour caractériser comment créer une base locale. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public enum CreationMode { - - /** creer une nouvelle base locale vide */ - EMPTY( - n("observe.storage.creationMode.empty"), - n("observe.storage.creationMode.empty.description") - ), - /** creer une nouvelle base a partir du dump embarque */ - IMPORT_INTERNAL_DUMP( - n("observe.storage.creationMode.internalDump"), - n("observe.storage.creationMode.internalDump.description") - ), - /** creer une nouvelle base a partir d'un dump sur fs */ - IMPORT_EXTERNAL_DUMP( - n("observe.storage.creationMode.externalDump"), - n("observe.storage.creationMode.externalDump.description") - ), - /** - * creer une nouvelle base vide et importer le referentiel via une base - * locale. - */ - IMPORT_LOCAL_STORAGE( - n("observe.storage.creationMode.importLocalStorage"), - n("observe.storage.creationMode.importLocalStorage.description") - ), - /** - * creer une nouvelle base vide et importer le referentiel via une base - * distante. - */ - IMPORT_REMOTE_STORAGE( - n("observe.storage.creationMode.importRemoteStorage"), - n("observe.storage.creationMode.importRemoteStorage.description") - ), - /** - * creer une nouvelle base vide et importer le referentiel via une base - * distante. - */ - IMPORT_SERVER_STORAGE( - n("observe.storage.creationMode.importServerStorage"), - n("observe.storage.creationMode.importServerStorage.description") - ); - - private final String label; - - private final String description; - - CreationMode(String label, String description) { - this.label = label; - this.description = description; - } - - public String getLabel() { - return label; - } - - public String getDescription() { - return description; - } - - public static CreationMode valueOf(DataSourceCreateConfigurationDto createConfigurationDto) { - CreationMode result = EMPTY; - - if (createConfigurationDto != null) { - if (createConfigurationDto.isImportData()) { - result = IMPORT_INTERNAL_DUMP; - } else if (createConfigurationDto.isImportDatabase()) { - result = IMPORT_REMOTE_STORAGE; - } else if (createConfigurationDto.isImportReferential()) { - result = IMPORT_EXTERNAL_DUMP; - } - } - - return result; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/db/constants/DataContextType.java b/observe-application-swing/src/main/java/fr/ird/observe/db/constants/DataContextType.java deleted file mode 100644 index 10fb27a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/db/constants/DataContextType.java +++ /dev/null @@ -1,331 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.constants; - -import fr.ird.observe.db.DataContext; -import fr.ird.observe.services.dto.longline.ActivityLonglineDto; -import fr.ird.observe.services.dto.longline.SetLonglineDto; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.services.dto.seine.FloatingObjectDto; -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.services.dto.seine.SetSeineDto; -import fr.ird.observe.services.dto.seine.TripSeineDto; - -/** - * Les types de données connues par le {@link DataContext}. - * - * Chaque constant permet de récupérer des données du context de données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public enum DataContextType { - - Program(ProgramDto.class, DataContext.PROPERTY_OPEN_PROGRAM) { - @Override - public boolean isOpen(DataContext context) { - return context.isOpenProgram(); - } - - @Override - public String getOpenId(DataContext context) { - return context.getOpenProgramId(); - } - - @Override - public void setOpenId(DataContext dataContext, String id) { - dataContext.setOpenProgramId(id); - } - - @Override - public String getSelectedId(DataContext context) { - return context.getSelectedProgramId(); - } - - @Override - public void setSelectedId(DataContext context, String id) { - context.setSelectedProgramId(id); - } - }, - - TripSeine(TripSeineDto.class, DataContext.PROPERTY_OPEN_TRIP) { - @Override - public boolean isOpen(DataContext context) { - return context.isOpenTripSeine(); - } - - @Override - public String getOpenId(DataContext context) { - return context.getOpenTripSeineId(); - } - - @Override - public void setOpenId(DataContext dataContext, String id) { - dataContext.setOpenTripSeineId(id); - } - - @Override - public String getSelectedId(DataContext context) { - return context.getSelectedTripSeineId(); - } - - @Override - public void setSelectedId(DataContext context, String id) { - context.setSelectedTripId(id); - } - }, - - TripLongline(TripLonglineDto.class, DataContext.PROPERTY_OPEN_TRIP) { - @Override - public boolean isOpen(DataContext context) { - return context.isOpenTripLongline(); - } - - @Override - public String getOpenId(DataContext context) { - return context.getOpenTripLonglineId(); - } - - @Override - public void setOpenId(DataContext dataContext, String id) { - dataContext.setOpenTripLonglineId(id); - } - - @Override - public String getSelectedId(DataContext context) { - return context.getSelectedTripLonglineId(); - } - - @Override - public void setSelectedId(DataContext context, String id) { - context.setSelectedTripId(id); - } - }, - - Route(RouteDto.class, DataContext.PROPERTY_OPEN_ROUTE) { - @Override - public boolean isOpen(DataContext context) { - return context.isOpenRoute(); - } - - @Override - public String getOpenId(DataContext context) { - return context.getOpenRouteId(); - } - - @Override - public void setOpenId(DataContext dataContext, String id) { - dataContext.setOpenRouteId(id); - } - - @Override - public String getSelectedId(DataContext context) { - return context.getSelectedRouteId(); - } - - @Override - public void setSelectedId(DataContext context, String id) { - context.setSelectedRouteId(id); - } - }, - - ActivitySeine(ActivitySeineDto.class, DataContext.PROPERTY_OPEN_ACTIVITY) { - @Override - public boolean isOpen(DataContext context) { - return context.isOpenActivityLongline(); - } - - @Override - public String getOpenId(DataContext context) { - return context.getOpenActivitySeineId(); - } - - @Override - public void setOpenId(DataContext dataContext, String id) { - dataContext.setOpenActivitySeineId(id); - } - - @Override - public String getSelectedId(DataContext context) { - return context.getSelectedActivitySeineId(); - } - - @Override - public void setSelectedId(DataContext context, String id) { - context.setSelectedActivityId(id); - } - }, - - ActivityLongline(ActivityLonglineDto.class, DataContext.PROPERTY_OPEN_ACTIVITY) { - @Override - public boolean isOpen(DataContext context) { - return context.isOpenActivityLongline(); - } - - @Override - public String getOpenId(DataContext context) { - return context.getOpenActivityLonglineId(); - } - - @Override - public void setOpenId(DataContext dataContext, String id) { - dataContext.setOpenActivityLonglineId(id); - } - - @Override - public String getSelectedId(DataContext context) { - return context.getSelectedActivityLonglineId(); - } - - @Override - public void setSelectedId(DataContext context, String id) { - context.setSelectedActivityId(id); - } - }, - - SetSeine(SetSeineDto.class, DataContext.PROPERTY_OPEN_SET) { - @Override - public boolean isOpen(DataContext context) { - return context.isOpenSetSeine(); - } - - @Override - public String getOpenId(DataContext context) { - return context.getOpenSetSeineId(); - } - - @Override - public void setOpenId(DataContext dataContext, String id) { - dataContext.setOpenSetSeineId(id); - } - - @Override - public String getSelectedId(DataContext context) { - return context.getSelectedSetSeineId(); - } - - @Override - public void setSelectedId(DataContext context, String id) { - context.setSelectedSetId(id); - } - }, - - SetLongline(SetLonglineDto.class, DataContext.PROPERTY_OPEN_SET) { - @Override - public boolean isOpen(DataContext context) { - return context.isOpenSetLongline(); - } - - @Override - public String getOpenId(DataContext context) { - return context.getOpenSetLonglineId(); - } - - @Override - public void setOpenId(DataContext dataContext, String id) { - dataContext.setOpenSetLonglineId(id); - } - - @Override - public String getSelectedId(DataContext context) { - return context.getSelectedSetLonglineId(); - } - - @Override - public void setSelectedId(DataContext context, String id) { - context.setSelectedSetId(id); - } - }, - - FloatingObject(FloatingObjectDto.class, null) { - @Override - public String getSelectedId(DataContext context) { - return context.getSelectedFloatingObjectId(); - } - - @Override - public void setSelectedId(DataContext context, String id) { - context.setSelectedFloatingObjectId(id); - } - }; - - private final Class<?> type; - - private final String openProperty; - - DataContextType(Class<?> type, String openProperty) { - this.type = type; - this.openProperty = openProperty; - } - - public boolean acceptType(Class<?> type) { - return type.equals(getType()); - } - - public boolean acceptId0(String id) { - return id.startsWith(getType().getName()); - } - - public Class<?> getType() { - return type; - } - - public String getOpenProperty() { - return openProperty; - } - - public boolean canOpen() { - return openProperty != null; - } - - public boolean isOpen(DataContext context) { - return false; - } - - public String getOpenId(DataContext context) { - return null; - } - - public abstract String getSelectedId(DataContext context); - - public abstract void setSelectedId(DataContext context, String id); - - public static DataContextType acceptId(String s) { - DataContextType result = null; - for (DataContextType type : DataContextType.values()) { - - String[] entityFullClass = s.split("#")[0].split("\\."); - String typeName = type.getType().getSimpleName(); - if (typeName.startsWith(entityFullClass[entityFullClass.length - 1])) { - result = type; - break; - } - } - return result; - } - - public void setOpenId(DataContext dataContext, String id) { - // rien a faire par defaut - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/db/constants/DbMode.java b/observe-application-swing/src/main/java/fr/ird/observe/db/constants/DbMode.java deleted file mode 100644 index d484d0c..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/db/constants/DbMode.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.constants; - -import static org.nuiton.i18n.I18n.n; - -/** - * Pour caractériser le type de connexion requis. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public enum DbMode { - /** Pour utiliser une base locale */ - USE_LOCAL( - n("observe.storage.dbMode.useLocal"), - n("observe.storage.dbMode.useLocal.description") - ), - /** Pour creer une base locale */ - CREATE_LOCAL( - n("observe.storage.dbMode.createLocal"), - n("observe.storage.dbMode.createLocal.description") - ), - /** Pour utiliser une base distante */ - USE_REMOTE( - n("observe.storage.dbMode.useRemote"), - n("observe.storage.dbMode.useRemote.description") - ), - /** Pour utiliser une base via un serveur web distant */ - USE_SERVER( - n("observe.storage.dbMode.useServer"), - n("observe.storage.dbMode.useServer.description") - ); - - private final String label; - - private final String description; - - DbMode(String label, String description) { - this.label = label; - this.description = description; - } - - public String getLabel() { - return label; - } - - public String getDescription() { - return description; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/db/event/ObserveSwingDataSourceEvent.java b/observe-application-swing/src/main/java/fr/ird/observe/db/event/ObserveSwingDataSourceEvent.java deleted file mode 100644 index 637247a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/db/event/ObserveSwingDataSourceEvent.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.event; - -import fr.ird.observe.db.ObserveSwingDataSource; - -import java.util.EventObject; - -/** - * Les évènements produits lors des changements du cycle de vie d'une source - * de données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ObserveSwingDataSourceEvent extends EventObject { - - private static final long serialVersionUID = 1L; - - /** an extra message to be used when using {@link ObserveSwingDataSourceListener#onNewMessage(ObserveSwingDataSourceEvent)}. */ - protected String message; - - public enum MessageLevel { - FATAL, - ERROR, - WARN, - INFO, - DEBUG, - TRACE - } - - protected MessageLevel messageLevel; - - /** - * Constructs a prototypical Event. - * - * @param source The object on which the Event initially occurred. - * @throws IllegalArgumentException if source is null. - */ - public ObserveSwingDataSourceEvent(ObserveSwingDataSource source) { - super(source); - } - - public ObserveSwingDataSourceEvent(ObserveSwingDataSource source, - String message, - MessageLevel messageLevel) { - super(source); - this.message = message; - this.messageLevel = messageLevel; - } - - @Override - public ObserveSwingDataSource getSource() { - return (ObserveSwingDataSource) super.getSource(); - } - - public String getMessage() { - return message; - } - - public MessageLevel getMessageLevel() { - return messageLevel; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/db/event/ObserveSwingDataSourceListener.java b/observe-application-swing/src/main/java/fr/ird/observe/db/event/ObserveSwingDataSourceListener.java deleted file mode 100644 index 8ae2593..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/db/event/ObserveSwingDataSourceListener.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.event; - -import fr.ird.observe.db.ObserveSwingDataSource; - -import java.util.EventListener; - -/** - * Le contrat d'un listener sur une source de données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public interface ObserveSwingDataSourceListener extends EventListener { - - - /** - * Déclanché avant l'ouverture d'un service (i.e au debut de la méthode - * {@link ObserveSwingDataSource#open()}). - * - * @param event l'evenement de pre-ouverture - */ - void onOpening(ObserveSwingDataSourceEvent event); - - /** - * Déclanché apres une ouverture d'un service (i.e à la fin de la méthode - * {@link ObserveSwingDataSource#open()}). - * - * @param event l'evenement d'ouverture - */ - void onOpened(ObserveSwingDataSourceEvent event); - - /** - * Déclanché avant la fermeture d'un service (i.e au avant la méthode {@link - * ObserveSwingDataSource#close()}). - * - * @param event l'evenement de pre-fermeture - */ - void onClosing(ObserveSwingDataSourceEvent event); - - /** - * Déclanché apres la fermeture d'un service (i.e apres de la méthode {@link - * ObserveSwingDataSource#close()}). - * - * @param event l'evenement de fermeture - */ - void onClosed(ObserveSwingDataSourceEvent event); - - /** - * Déclanché pour envoyer un nouveau message. - * - * @param event l'evenement de message - */ - void onNewMessage(ObserveSwingDataSourceEvent event); -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/db/event/ObserveSwingDataSourceListenerAdapter.java b/observe-application-swing/src/main/java/fr/ird/observe/db/event/ObserveSwingDataSourceListenerAdapter.java deleted file mode 100644 index 1345ab8..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/db/event/ObserveSwingDataSourceListenerAdapter.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.db.event; - -/** - * Un adapteur de {@link ObserveSwingDataSourceListener}. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ObserveSwingDataSourceListenerAdapter implements ObserveSwingDataSourceListener { - - @Override - public void onOpening(ObserveSwingDataSourceEvent event) { - // ne fait rien - } - - @Override - public void onOpened(ObserveSwingDataSourceEvent event) { - // ne fait rien - } - - @Override - public void onClosing(ObserveSwingDataSourceEvent event) { - // ne fait rien - } - - @Override - public void onClosed(ObserveSwingDataSourceEvent event) { - // ne fait rien - } - - @Override - public void onNewMessage(ObserveSwingDataSourceEvent event) { - // ne fait rien - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/package.html b/observe-application-swing/src/main/java/fr/ird/observe/package.html deleted file mode 100644 index 061a248..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/package.html +++ /dev/null @@ -1,36 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<html> -<body> -<h1>Paquetage principal fr.ird.observe</h1> - -Le paquetage contenant la classe de lancement de l'application (ObserveMain), la -configuration (ObserveSwingApplicationConfig) et le -contexte applicatif (ObserveContext), ainsi que des services (non ui) : - -- DecoratorProvider un provider de décorateurs. - -- SelectionScope une énumération pour traiter facilement l'état ouvert d'une -entité dans le contexte. - -</body> -</html> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/ObserveCommon.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/ObserveCommon.jcss deleted file mode 100644 index 53043c7..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/ObserveCommon.jcss +++ /dev/null @@ -1,94 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -JToolBar { - borderPainted:false; - floatable:false; - opaque:false; -} - -JTabbedPane { - _notBlocking: true; -} - -JXDatePicker { - formats:{"dd/MM/yyyy"}; -} - -DateTimeEditor { - dateFormat:{"dd/MM/yyyy"}; - showTimeEditorSlider: {config.isShowTimeEditorSlider()}; - _selectOnFocus: true; -} - -TimeEditor { - showTimeEditorSlider: {config.isShowTimeEditorSlider()}; - _selectOnFocus: true; -} - -NumberEditor { - autoPopup:{config.isAutoPopupNumberEditor()}; - showPopupButton:{config.isShowNumberEditorButton()}; - showReset:true; -} - -CoordinatesEditor { - format: {org.nuiton.jaxx.widgets.gis.CoordinateFormat.dms}; -} - -FilterableDoubleList { - showDecorator:false; - showReset:true; - showSelectPopupEnabled: true; - filterable:false; - _notBlocking: true; -} - -BeanComboBox { - showReset:true; -} - -BlockingLayerUI { - acceptedComponentTypes: {javax.swing.JScrollBar.class}; -} - -.resetButton { - opaque:false; - actionIcon:combobox-reset; - focusTraversalKeysEnabled:false; - focusable:false; -} - -.integer { - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - useFloat:false; -} - -.float { - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL3_PATTERN}; - useFloat:true; -} - -.float2 { - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL2_PATTERN}; - useFloat:true; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/ObserveMainUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/ObserveMainUI.jaxx deleted file mode 100644 index 4aad01d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/ObserveMainUI.jaxx +++ /dev/null @@ -1,341 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<JFrame id='mainFrame' width='800' height='800' - onWindowClosing='new fr.ird.observe.ui.actions.CloseApplicationAction(this).run()'> - - <import> - fr.ird.observe.ObserveSwingApplicationContext - fr.ird.observe.configuration.ObserveSwingApplicationConfig - fr.ird.observe.db.DataContext - - fr.ird.observe.services.dto.referential.ProgramDto - fr.ird.observe.services.dto.seine.ActivitySeineDto - fr.ird.observe.services.dto.seine.RouteDto - fr.ird.observe.services.dto.seine.SetSeineDto - fr.ird.observe.services.dto.seine.TripSeineDto - fr.ird.observe.services.dto.constants.ReferentialLocale - - fr.ird.observe.ui.actions.shared.ReOpenUIAction - - fr.ird.observe.ui.admin.AdminStep - fr.ird.observe.ui.actions.ChangeStorageAction - fr.ird.observe.ui.actions.CloseStorageAction - fr.ird.observe.ui.actions.ReloadStorageAction - fr.ird.observe.ui.actions.SaveStorageToFileAction - fr.ird.observe.ui.actions.ShowStorageInfoAction - fr.ird.observe.ui.content.ContentUIManager - fr.ird.observe.ui.tree.ObserveTreeHelper - fr.ird.observe.ui.tree.NavigationTreeCellRenderer - - jaxx.runtime.swing.CardLayout2 - jaxx.runtime.swing.CardLayout2Ext - jaxx.runtime.swing.BlockingLayerUI - jaxx.runtime.swing.StatusMessagePanel - jaxx.runtime.validator.swing.SwingValidatorMessageTableModel - - org.jdesktop.swingx.JXTitledPanel - - java.util.Locale - - javax.swing.BoxLayout - javax.swing.JComponent - javax.swing.UIManager - javax.swing.Icon - - <!-- FIXME --> - <!--fr.ird.observe.services.dto.TripDto--> - <!--fr.ird.observe.services.dto.ActivityDto--> - <!--fr.ird.observe.services.dto.SetDto--> - </import> - - <ObserveUIMode id='mode' javaBean='ObserveUIMode.NO_DB'/> - - <Boolean id='h2WebServer' javaBean='Boolean.FALSE'/> - - <ChangeStorageAction id="changeStorageAction" constructorParams='this'/> - <CloseStorageAction id="closeStorageAction" constructorParams='this'/> - <ReloadStorageAction id="reloadStorageAction" constructorParams='this'/> - <SaveStorageToFileAction id="saveStorageToFileAction" constructorParams='this'/> - <ShowStorageInfoAction id="showStorageInfoAction" constructorParams='this'/> - - - <ContentUIManager id='contentUIManager' initializer='ObserveSwingApplicationContext.get().getContentUIManager()'/> - - <JPopupMenu id='scopeUpPopup'/> - <JPopupMenu id='scopeDownPopup'/> - <JPopupMenu id='navigationPopup'> - <JMenuItem id="navigationNoAction"/> - <JMenu id="navigationMoveAction"/> - <JMenuItem id="navigationOpenAction"/> - <JMenuItem id="navigationCloseAction"/> - <JMenuItem id="navigationDeleteAction"/> - </JPopupMenu> - - <ObserveSwingApplicationConfig id='config' initializer='ObserveSwingApplicationContext.get().getConfig()'/> - - <ObserveMainUIHandler id='handler' initializer='getContextValue(ObserveMainUIHandler.class)'/> - - <ObserveTreeHelper id='treeHelper' initializer='getContextValue(ObserveTreeHelper.class)'/> - - <DataContext id='dataContext' initializer='ObserveSwingApplicationContext.get().getDataContext()'/> - - <Boolean id='mainFromSynchro' javaBean='false'/> - - <Boolean id='busy' javaBean='false'/> - - <CardLayout2 id='contentLayout'/> - - <CardLayout2Ext id='bodyLayout' constructorParams='this, "body"'/> - - <BlockingLayerUI id='busyBlockLayerUI'/> - - <script><![CDATA[ - -protected Icon updateStorageSatutIcon(boolean isOpened) { - return getHandler().updateStorageSatutIcon(this, isOpened); -} - -protected String updateStorageSatutText(boolean isOpened) { - return getHandler().updateStorageSatutText(this, isOpened); -} - -protected String updateStorageStatutToolTipText(boolean isOpened) { - return getHandler().updateStorageStatutToolTipText(this, isOpened); -} - -@Override -public void dispose() { - log.debug("dispose main ui " + this); - destroy(); - super.dispose(); -} - -public void destroy() { - log.info("destroy ui " + getName()); - UIHelper.destroy(this); -} - -@Override -protected void finalize() throws Throwable { - super.finalize(); - destroy(); -} - -void $afterCompleteSetup() { - getHandler().$afterCompleteSetup(this); -} - -]]> - </script> - - <!-- menu --> - <JMenuBar id='menu'> - - <JMenu id='menuFile'> - <JMenuItem id='menuFileReloadApplication'/> - <JMenuItem id='menuFileCloseApplication'/> - </JMenu> - - <JMenu id='menuStorage'> - <JMenuItem id='menuStorageChange'/> - <JMenuItem id='menuStorageReload'/> - <JMenuItem id='menuStorageClose'/> - <JMenuItem id='menuStorageInfo'/> - <JSeparator/> - <JMenuItem id='menuStorageLoadFromFile'/> - <JMenuItem id='menuStorageSaveToFile'/> - <JMenuItem id='menuStorageStartServerMode'/> - </JMenu> - - <JMenu id='menuActions'> - <JMenuItem id='menuActionsSynchronize'/> - <JMenuItem id='menuActionsReferentialSynchro'/> - <JMenuItem id='menuActionsDataSynchro'/> - <JSeparator/> - <JMenuItem id='menuActionsValidateData'/> - <JMenuItem id='menuActionsExportData'/> - <JMenuItem id='menuActionsReport'/> - <JMenuItem id='menuActionsConsolidate'/> - </JMenu> - - <JMenu id='menuNavigation'> - <JMenuItem id='menuNavigationProgram' - onActionPerformed="getTreeHelper().selectOpenNode(ProgramDto.class)"/> - <JMenuItem id='menuNavigationTrip' - onActionPerformed="getTreeHelper().selectOpenNode(TripSeineDto.class)"/> - <JMenuItem id='menuNavigationRoute' - onActionPerformed="getTreeHelper().selectOpenNode(RouteDto.class)"/> - <JMenuItem id='menuNavigationActivity' - onActionPerformed="getTreeHelper().selectOpenNode(ActivitySeineDto.class)"/> - <JMenuItem id='menuNavigationSet' - onActionPerformed="getTreeHelper().selectOpenNode(SetSeineDto.class)"/> - <JSeparator/> - <JMenuItem id='menuNavigationReferentiel' - onActionPerformed='getTreeHelper().selectNode("observe.common.referentiel")'/> - </JMenu> - <JMenu id='menuConfiguration'> - <JMenu id='menuLanguage'> - <JMenu id='menuApplicationLanguage'> - <JMenuItem id='menuApplicationLanguageUK'/> - <JMenuItem id='menuApplicationLanguageFR'/> - <JMenuItem id='menuApplicationLanguageES'/> - </JMenu> - <JMenu id='menuDbLanguage'> - <JMenuItem id='menuDbLanguageUK'/> - <JMenuItem id='menuDbLanguageFR'/> - <JMenuItem id='menuDbLanguageES'/> - </JMenu> - </JMenu> - <JSeparator/> - <JMenuItem id='menuFileConfiguration'/> - <JMenuItem id='menuConfigurationReloadDefault'/> - <JMenuItem id='menuConfigurationReloadResources'/> - </JMenu> - - <JMenu id='menuHelp'> - <JMenuItem id='menuHelpSite'/> - <JMenuItem id='menuHelpAbout'/> - </JMenu> - - <JToolBar id='toolbar'> - - <javax.swing.Box.Filler - constructorParams='UIHelper.newMinDimension(), UIHelper.newMinDimension(), UIHelper.newMaxXDimension()'/> - <!-- pour afficher le status du service de persistance et changer de - service de persistance --> - <JButton id='storageStatus' - enabled='{getHandler().acceptMode(getMode(), !isBusy(), ObserveUIMode.DB, ObserveUIMode.NO_DB)}' - onActionPerformed="JComponent c = (JComponent) event.getSource(); storageStatusPopup.show(c, 0, c.getHeight());"/> - </JToolBar> - - </JMenuBar> - - <!-- contenu principal --> - - <JPanel id='body' constraints="BorderLayout.CENTER" decorator='boxed'> - - <JPanel constraints='"invisible"'> - - <JPopupMenu id='storageStatusPopup'> - <JMenuItem id='storageStatusChange'/> - <JMenuItem id='storageStatusReload'/> - <JMenuItem id='storageStatusClose'/> - <JMenuItem id='storageStatusInfo'/> - </JPopupMenu> - </JPanel> - - <!-- ecran lorsqu'aucune source de données n'est chargée --> - - <JLabel id="modeNoDb" constraints='ObserveUIMode.NO_DB.name()'/> - - <!-- ecran avec une navigation sur les données d'une source --> - - <JSplitPane id='splitpane' constraints="ObserveUIMode.DB.name()"> - - <!-- left : navigation --> - - <JXTitledPanel id='navigationView'> - <JScrollPane id='navigationScrollPane'> - <JTree id="navigation"/> - </JScrollPane> - </JXTitledPanel> - - <!-- right : (content + messages) --> - - <JSplitPane id='splitpane2'> - - <!-- right up : content --> - - <JPanel id="content"/> - - <!-- right down : message view --> - <JXTitledPanel id='messageView'> - <JScrollPane> - <JTable id='errorTable'/> - </JScrollPane> - </JXTitledPanel> - - </JSplitPane> - </JSplitPane> - - <!-- ecran pour les opérations de synchronisation et validation --> - - <JXTitledPanel id='synchroWizard' constraints='ObserveUIMode.SYNCHRO.name()'/> - - <!-- ecran du mode serveur --> - - <JXTitledPanel id='serverMode' constraints='ObserveUIMode.SERVER.name()'> - <JPanel layout='{new BorderLayout()}'> - - <JPanel layout='{new GridLayout(0,1)}' constraints='BorderLayout.NORTH'> - - <JLabel id='serverModeInfo'/> - - <Table id='serverModeParameters' fill="both"> - <row> - <cell> - <JLabel id="serverModeURLLabel"/> - </cell> - <cell weightx='1' fill="both"> - <JTextField id='serverModeURL'/> - </cell> - </row> - <row> - <cell> - <JLabel id="serverModeLoginLabel"/> - </cell> - <cell> - <JTextField id='serverModeLogin'/> - </cell> - </row> - <row> - <cell> - <JLabel id="serverModePasswordLabel"/> - </cell> - <cell> - <JTextField id='serverModePassword'/> - </cell> - </row> - - </Table> - - </JPanel> - - <JPanel constraints='BorderLayout.CENTER' layout='{new GridLayout(0,1)}'> - <JButton id="stopServerMode"/> - <JSeparator/> - <JButton id="startH2WebServer"/> - <JButton id="stopH2WebServer"/> - - </JPanel> - - </JPanel> - - </JXTitledPanel> - - </JPanel> - - <!-- status message bar --> - <StatusMessagePanel id='status' constraints="BorderLayout.SOUTH"/> - -</JFrame> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/ObserveMainUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/ObserveMainUI.jcss deleted file mode 100644 index d9bed5c..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/ObserveMainUI.jcss +++ /dev/null @@ -1,474 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -JToolBar { - borderPainted: false; - floatable: false; - opaque: false; -} - -JSplitPane { - oneTouchExpandable: true; - continuousLayout: false; - dividerSize: 6; -} - -#mainFrame { - defaultCloseOperation: "do_nothing_on_close"; - iconImage: {SwingUtil.createImageIcon("logo-OT_web.png").getImage()}; -} - -#menu { - enabled: {!isBusy()}; -} - -#navigationNoAction { - text: "observe.navigationMenu.noAction"; - toolTipText: "observe.navigationMenu.noAction"; - enabled: false; -} - -// trip menu - -#navigationOpenAction { - action: {new fr.ird.observe.ui.actions.shared.ReOpenUIAction(this)}; -} - -#navigationCloseAction { - action: {new fr.ird.observe.ui.actions.shared.CloseOpenUIAction(this)}; -} - -#navigationDeleteAction { - action: {new fr.ird.observe.ui.actions.shared.DeleteDataUIAction(this)}; -} - -#menuFile { - text: "observe.menu.file"; - mnemonic: F; - enabled: {getHandler().acceptMode(getMode(), !isBusy(), !isMainFromSynchro(), ObserveUIMode.NO_DB, ObserveUIMode.DB)}; -} - -#menuFileConfiguration { - action: {new fr.ird.observe.ui.actions.ShowConfigAction(this)}; -} - -#menuConfiguration { - text: "observe.menu.configuration"; - toolTipText: "observe.menu.configuration.tip"; - mnemonic: C; - enabled: {getHandler().acceptMode(getMode(), !isBusy(), !isMainFromSynchro(), ObserveUIMode.DB, ObserveUIMode.NO_DB)}; -} - -#menuLanguage { - text: "observe.menu.locale"; - toolTipText: "observe.menu.locale"; - actionIcon: "translate"; - mnemonic: L; - enabled: {getHandler().acceptMode(getMode(), !isBusy(), !isMainFromSynchro(), ObserveUIMode.DB, ObserveUIMode.NO_DB)}; -} - -#menuApplicationLanguage { - text: "observe.menu.application.locale"; - toolTipText: "observe.menu.application.locale"; - actionIcon: "application-translate"; - mnemonic: A; -} - -#menuApplicationLanguageFR { - action: {new fr.ird.observe.ui.actions.ChangeApplicationLanguageAction(this, Locale.FRANCE, t("observe.action.locale.fr"), t("observe.action.locale.fr.tip"))}; - enabled: {!getHandler().acceptLocale(getConfig().getLocale(), "fr_FR")}; -} - -#menuApplicationLanguageUK { - action: {new fr.ird.observe.ui.actions.ChangeApplicationLanguageAction(this, Locale.UK, t("observe.action.locale.uk"), t("observe.action.locale.uk.tip"))}; - enabled: {!getHandler().acceptLocale(getConfig().getLocale(), "en_GB")}; -} - -#menuApplicationLanguageES { - action: {new fr.ird.observe.ui.actions.ChangeApplicationLanguageAction(this, new Locale("es","ES"), t("observe.action.locale.es"), t("observe.action.locale.es.tip"))}; - enabled: {!getHandler().acceptLocale(getConfig().getLocale(), "es_ES")}; -} - -#menuDbLanguage { - text: "observe.menu.db.locale"; - toolTipText: "observe.menu.db.locale"; - actionIcon: "db-translate"; - mnemonic: D; -} - -#menuDbLanguageFR { - action: {new fr.ird.observe.ui.actions.ChangeDbLanguageAction(this, ReferentialLocale.FR, t("observe.action.locale.fr"), t("observe.action.db.locale.fr.tip"))}; - enabled: {!getHandler().acceptLocale(getConfig().getDbLocale(), "fr_FR")}; -} - -#menuDbLanguageUK { - action: {new fr.ird.observe.ui.actions.ChangeDbLanguageAction(this, ReferentialLocale.UK, t("observe.action.locale.uk"), t("observe.action.db.locale.uk.tip"))}; - enabled: {!getHandler().acceptLocale(getConfig().getDbLocale(), "en_GB")}; -} - -#menuDbLanguageES { - action: {new fr.ird.observe.ui.actions.ChangeDbLanguageAction(this, ReferentialLocale.ES, t("observe.action.locale.es"), t("observe.action.db.locale.es.tip"))}; - enabled: {!getHandler().acceptLocale(getConfig().getDbLocale(), "es_ES")}; -} - -#menuConfigurationReloadDefault { - action: {new fr.ird.observe.ui.actions.ReloadDefaultConfigurationAction(this)}; -} - -#menuConfigurationReloadResources { - action: {new fr.ird.observe.ui.actions.ReloadResourcesAction(this)}; - visible: {getConfig().isDevMode()}; -} - -#menuFileReloadApplication { - action: {new fr.ird.observe.ui.actions.ReloadApplicationAction(this)}; -} - -#menuFileCloseApplication { - action: {new fr.ird.observe.ui.actions.CloseApplicationAction(this)}; -} - -#menuStorage { - text: "observe.menu.storage"; - mnemonic: S; - enabled: {getHandler().acceptMode(getMode(), !isBusy(), !isMainFromSynchro(), ObserveUIMode.DB, ObserveUIMode.NO_DB)}; -} - -#menuStorageInfo { - action: {new fr.ird.observe.ui.actions.ShowStorageInfoAction(this)}; -} - -#reloadStorageAction { - enabled: {getHandler().acceptMode(getMode(), getConfig().isMainStorageOpened(), ObserveUIMode.DB)}; -} - -#closeStorageAction { - enabled: {getHandler().acceptMode(getMode(), getConfig().isMainStorageOpened(), ObserveUIMode.DB)}; -} - -#saveStorageToFileAction { - enabled: {getHandler().acceptMode(getMode(), getConfig().isMainStorageOpened(), ObserveUIMode.DB)}; -} - -#menuStorageReload { - action: {reloadStorageAction}; - enabled: {reloadStorageAction.isEnabled()}; -} - -#menuStorageClose { - action: {closeStorageAction}; - enabled: {closeStorageAction.isEnabled()}; -} - -#menuStorageStartServerMode { - action: {new fr.ird.observe.ui.actions.StartServerModeAction(this)}; - visible: {getHandler().acceptMode(getMode(), getConfig().isLocalStorageExist() && !isBusy() && !isMainFromSynchro(), ObserveUIMode.NO_DB)}; -} - -#menuStorageChange { - action: {changeStorageAction}; -} - -#menuStorageLoadFromFile { - action: {new fr.ird.observe.ui.actions.ImportStorageFromFileAction(this)}; - enabled: {getHandler().acceptMode(getMode(), ObserveUIMode.DB, ObserveUIMode.NO_DB)}; -} - -#menuStorageSaveToFile { - action: {saveStorageToFileAction}; - enabled: {saveStorageToFileAction.isEnabled()}; -} - -#menuActions { - text: "observe.menu.actions"; - mnemonic: A; - enabled: {getHandler().acceptMode(getMode(), !isBusy() && !isMainFromSynchro(), ObserveUIMode.DB, ObserveUIMode.NO_DB)}; -} - -#menuActionsDataSynchro { - action: {new fr.ird.observe.ui.actions.LaunchAdminAction(this, AdminStep.DATA_SYNCHRONIZE)}; -} - -#menuActionsReferentialSynchro { - action: {new fr.ird.observe.ui.actions.LaunchAdminAction(this, AdminStep.REFERENTIAL_SYNCHRONIZE)}; -} - -#menuActionsSynchronize { - action: {new fr.ird.observe.ui.actions.LaunchAdminAction(this, AdminStep.SYNCHRONIZE)}; -} - -#menuActionsValidateData { - action: {new fr.ird.observe.ui.actions.LaunchAdminAction(this, AdminStep.VALIDATE)}; -} - -#menuActionsExportData { - action: {new fr.ird.observe.ui.actions.LaunchAdminAction(this, AdminStep.EXPORT_DATA)}; -} - -#menuActionsReport { - action: {new fr.ird.observe.ui.actions.LaunchAdminAction(this, AdminStep.REPORT)}; -} - -#menuActionsConsolidate { - action: {new fr.ird.observe.ui.actions.LaunchAdminAction(this, AdminStep.CONSOLIDATE)}; -} - -#menuNavigation { - text: "observe.menu.navigation"; - mnemonic: n; - enabled: {getHandler().acceptMode(getMode(), !isBusy(), ObserveUIMode.DB)}; -} - -#menuNavigationProgram { - text: "observe.content.action.goto.open.program.short"; - toolTipText: "observe.content.action.goto.open.program.tip"; - icon: "navigation.fr.ird.observe.services.dto.referential.ProgramDto"; - mnemonic: P; - enabled: {getDataContext().isOpenProgram()}; -} - -#menuNavigationTrip { - text: "observe.content.action.goto.open.trip.short"; - toolTipText: "observe.content.action.goto.open.trip.tip"; - icon: "navigation.fr.ird.observe.services.dto.TripDto"; - mnemonic: M; - enabled: {getDataContext().isOpenTrip()}; -} - -#menuNavigationRoute { - text: "observe.content.action.goto.open.route.short"; - toolTipText: "observe.content.action.goto.open.route.tip"; - icon: "navigation.fr.ird.observe.services.dto.seine.RouteDto"; - mnemonic: R; - enabled: {getDataContext().isOpenRoute()}; -} - -#menuNavigationActivity { - text: "observe.content.action.goto.open.activity.short"; - toolTipText: "observe.content.action.goto.open.activity.tip"; - icon: "navigation.fr.ird.observe.services.dto.ActivityDto"; - mnemonic: A; - enabled: {getDataContext().isOpenActivity()}; -} - -#menuNavigationSet { - text: "observe.content.action.goto.open.set.short"; - toolTipText: "observe.content.action.goto.open.set.tip"; - icon: "navigation.fr.ird.observe.services.dto.SetDto"; - mnemonic: C; - enabled: {getDataContext().isOpenSet()}; -} - -#menuNavigationReferentiel { - text: "observe.action.goto.referentiel.short"; - toolTipText: "observe.action.goto.referentiel.tip"; - icon: "navigation.referentiel"; - mnemonic: f; -} - -#menuHelp { - text: "observe.menu.help"; - mnemonic: e; - enabled: {!isBusy()}; -} - -#menuHelpHelp { - text: "observe.action.help"; - toolTipText: "observe.action.help.tip"; - actionIcon: "help"; - mnemonic: e; -} - -#menuHelpSite { - action: {new fr.ird.observe.ui.actions.GotoSiteAction(this)}; -} - -#menuHelpAbout { - action: {new fr.ird.observe.ui.actions.ShowAboutAction(this)}; -} - -#storageStatus { - opaque: false; - borderPainted: false; - focusable: false; - toolTipText: {updateStorageStatutToolTipText(getConfig().isMainStorageOpened())}; - text: {updateStorageSatutText(getConfig().isMainStorageOpened())}; - icon: {updateStorageSatutIcon(getConfig().isMainStorageOpened())}; - _localIcon: {SwingUtil.getUIManagerActionIcon("db-local")}; - _remoteIcon: {SwingUtil.getUIManagerActionIcon("db-remote")}; - _serverIcon: {SwingUtil.getUIManagerActionIcon("db-server")}; - _noneIcon: {SwingUtil.getUIManagerActionIcon("db-none")}; -} - -#storageStatusInfo { - action: {showStorageInfoAction}; -} - -#storageStatusChange { - action: {changeStorageAction}; -} - -#storageStatusClose { - action: {closeStorageAction}; - enabled: {closeStorageAction.isEnabled()}; -} - -#storageStatusReload { - action: {reloadStorageAction}; - enabled: {reloadStorageAction.isEnabled()}; -} - -#closeHelp { - action: {new fr.ird.observe.ui.actions.CloseHelpAction(this)}; - borderPainted: false; - rolloverEnabled: false; - focusable: false; -} - -#errorTable { - rowSelectionAllowed: true; - autoCreateRowSorter: true; - autoResizeMode: 2; - cellSelectionEnabled: false; - selectionMode: 0; - minimumSize: {UIHelper.newMinDimension()}; - model: {getContextValue(SwingValidatorMessageTableModel.class)}; -} - -#busyBlockLayerUI { - useIcon: false; - blockingColor: {UIManager.getColor("BlockingLayerUI.blockingColor")}; - block: {isBusy()}; - acceptedComponentNames: {UIHelper.ACCEPTABLE_COMPONENTS}; -} - -#navigation { - rootVisible: false; - largeModel: true; - minimumSize: {UIHelper.newMinDimension()}; - font-size:11; - model: {getTreeHelper().getModel()}; - selectionModel: {getTreeHelper().newNavigationSelectionModel()}; - cellRenderer: {new NavigationTreeCellRenderer()}; -} - -#splitpane { - orientation: {JSplitPane.HORIZONTAL_SPLIT}; - resizeWeight: 1.0; -} - -#splitpane2 { - orientation: {JSplitPane.VERTICAL_SPLIT}; - resizeWeight: 0.80; -} - -#contentLayout { - useOnlyVisibleComponentDimension: true; -} - -#navigationView { - title: "observe.view.navigation"; -} - -#messageView { - title: "observe.view.message"; -} - -#modeNoDb { - text: "observe.message.db.none.loaded"; - horizontalAlignment: center; -} - -#serverMode { - title: "observe.view.server"; -} - -#serverModeInfo { - text: "observe.message.server.info"; - horizontalAlignment: center; -} - -#serverModeURLLabel { - text: "observe.message.h2.server.url"; - labelFor: {serverModeURL}; -} - -#serverModeURL { - editable: false; -} - -#serverModeLoginLabel { - text: "observe.message.h2.server.login"; - labelFor: {serverModeLogin}; -} - -#serverModeLogin { - editable: false; -} - -#serverModePasswordLabel { - text: "observe.message.h2.server.password"; - labelFor: {serverModePassword}; -} - -#serverModePassword { - editable: false; -} - -#startH2WebServer{ - action: {new fr.ird.observe.ui.actions.StartH2WebServerAction(this)}; - enabled: {!isH2WebServer()}; -} - -#stopH2WebServer{ - action: {new fr.ird.observe.ui.actions.StopH2WebServerAction(this)}; - enabled: {isH2WebServer()}; -} - -#stopServerMode { - action: {new fr.ird.observe.ui.actions.StopServerModeAction(this)}; -} - -#serverModeParameters { - border: {new TitledBorder(t("observe.title.h2.server.parameters"))}; -} - -#bodyLayout { - selected: {getMode().name()}; -} -#body { - layout: {bodyLayout}; -} - -#content { - layout: {contentLayout}; -} - -#status { - showBusy: {true}; - busy: {isBusy()}; -} - -#toolbar { - layout: {new BoxLayout(toolbar, 0)}; - enabled: {!isBusy()}; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/ObserveMainUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/ObserveMainUIHandler.java deleted file mode 100755 index 6731e48..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/ObserveMainUIHandler.java +++ /dev/null @@ -1,512 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.AbstractObserveDto; -import fr.ird.observe.services.dto.constants.ReferentialLocale; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.ContentUI; -import fr.ird.observe.ui.content.ContentUIManager; -import fr.ird.observe.ui.content.ContentUIModel; -import fr.ird.observe.ui.content.ObserveContentUI; -import fr.ird.observe.ui.tree.ObserveNavigationTreeShowPopupAction; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.ui.util.ObserveSwingValidatorMessageTableModel; -import fr.ird.observe.ui.util.ObserveValidatorMessageTableRenderer; -import jaxx.runtime.JAXXContext; -import jaxx.runtime.context.DefaultApplicationContext; -import jaxx.runtime.context.JAXXInitialContext; -import jaxx.runtime.swing.ErrorDialogUI; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; -import jaxx.runtime.validator.swing.SwingValidatorUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.i18n.I18n; - -import javax.swing.Icon; -import javax.swing.SwingUtilities; -import javax.swing.event.TreeExpansionEvent; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.event.TreeWillExpandListener; -import javax.swing.tree.ExpandVetoException; -import javax.swing.tree.TreePath; -import java.awt.Cursor; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; - -import static org.nuiton.i18n.I18n.t; - -/** - * Le handler de l'ui principale. - * - * @author Tony Chemit - chemit@codelutin.com - * @see ObserveMainUI - * @since 1.0 - */ -@DefaultApplicationContext.AutoLoad -public class ObserveMainUIHandler { - - /** Logger */ - private static final Log log = LogFactory.getLog(ObserveMainUIHandler.class); - - public void changeNavigationNode(ObserveMainUI ui, TreeSelectionEvent event) { - - - ObserveSwingDataSource source = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); - if (source == null || !source.isOpen()) { - - // no open data source - if (log.isDebugEnabled()) { - log.debug("No open Data source."); - } - return; - } - if (ui.getNavigation().isSelectionEmpty()) { - if (log.isDebugEnabled()) { - log.debug("No selection, do nothing..."); - } - return; - } - - TreePath path = event.getPath(); - ObserveNode node = (ObserveNode) path.getLastPathComponent(); - ContentUIManager manager = ui.getContentUIManager(); - - // obtain the ui type to show - Class<? extends ObserveContentUI<?>> uiClass = manager.convertNodeToContentUI(node); - if (log.isDebugEnabled()) { - log.debug("new selected path = " + node + ", ui = " + uiClass); - } - - if (uiClass == null) { - - // pas d'ui trouvé, on ne fait donc rien - return; - } - - ui.setBusy(true); - - try { - - doOpencontent(ui, path, uiClass); - - } catch (Exception e) { - UIHelper.handlingError(e); - } finally { - ui.setBusy(false); - String params; - if (node.isStringNode()) { - params = t(node.getId()); - } else { - params = t(DecoratorService.getEntityLabel(node.getInternalClass())); - } - ui.getStatus().setStatus(t("observe.action.open.screen", params)); - } - } - - public void doOpencontent(ObserveMainUI ui, - TreePath path, - Class<? extends ObserveContentUI<?>> uiClass) { - - ContentUIManager manager = ui.getContentUIManager(); - - // compute the selected ids to put in data context - Object[] nodes = path.getPath(); - List<String> ids = new ArrayList<>(); - for (Object o : nodes) { - ObserveNode n = (ObserveNode) o; - - if (n.isStringNode() || n.isReferentielNode() || n.isRoot() || !n.isDataNode()) { - continue; - } - ids.add(n.getId()); - } - - if (log.isDebugEnabled()) { - log.debug("new selected ids from tree = " + ids); - } - String[] selectedIds = ids.toArray(new String[ids.size()]); - - // update selected ids in data context - DataContext context = ui.getDataContext(); - context.populateSelectedIds(selectedIds); - - // on recherche l'ui (voir si elle existe déjà) - ObserveContentUI<?> content = manager.getContent(uiClass); - - if (content == null) { - - content = manager.createContent(uiClass); - } - - // on ouvre l'écran - manager.openContent(content); - } - - /** - * Methode pour initialiser l'ui principale sans l'afficher. - * - * @param context le context applicatif - * @param config la configuration a utiliser - * @return l'ui instancie et initialisee mais non visible encore - */ - public ObserveMainUI initUI(ObserveSwingApplicationContext context, ObserveSwingApplicationConfig config) { - - SwingValidatorMessageTableModel errorModel = - new ObserveSwingValidatorMessageTableModel(); - - DecoratorService decoratorService = context.getDecoratorService(); - - boolean reloadDecorators = false; - Locale currentLocale = I18n.getDefaultLocale(); -// if (!config.getLocale().equals( -// I18n.getStore().getLanguage().getLocale())) { - Locale configurationLocale = config.getLocale(); - if (!configurationLocale.equals(currentLocale)) { - if (log.isInfoEnabled()) { - log.info("re-init I18n with locale " + configurationLocale); - } - I18n.setDefaultLocale(configurationLocale); -// I18n.init(configurationLocale); - reloadDecorators = true; - } - if (!config.getDbLocale().equals( - decoratorService.getReferentialLocale().getLocale())) { - if (log.isInfoEnabled()) { - log.info("re-init db with locale " + config.getDbLocale()); - } - decoratorService.setReferentialLocale(ReferentialLocale.valueOf(config.getDbLocale())); - - reloadDecorators = true; - } - - if (reloadDecorators) { - if (log.isInfoEnabled()) { - log.info("reload decorators"); - } - decoratorService.reload(); - } - - ObserveTreeHelper treeHelper = new ObserveTreeHelper(); - ObserveSwingDataSource source = context.getDataSourcesManager().getMainDataSource(); - - boolean open = context.getDataContext().getEnabled(); - if (open) { - treeHelper.createModel(source); - } else { - treeHelper.createEmptyModel(); - } - - JAXXInitialContext tx = new JAXXInitialContext(); - - tx.add(context).add(treeHelper).add(errorModel); - - // show main ui - ObserveMainUI ui = new ObserveMainUI(tx); - ui.setUndecorated(config.isFullScreen()); - - String title = t("observe.title.welcome.admin"); - title += " v " + config.getVersion(); - ui.setTitle(title); - - context.setMainUI(ui); - - ErrorDialogUI.init(ui); - - // set fullscreen propery on main ui - ui.getGraphicsConfiguration().getDevice().setFullScreenWindow(config.isFullScreen() ? ui : null); - - // on enregistre les actions communes à toutes les écrans d'édition - // les bouttons utilisant ces actions seront automatiquement - // chargés (à partir des actions) lors de l'ouverture des ui - // et mis à jour - - context.registerShareActions(); - - new ObserveNavigationTreeShowPopupAction(treeHelper, ui.getNavigationScrollPane(), ui.getNavigationPopup()); - - return ui; - } - - public static final String H2_SERVER_URL_PATTERN = "jdbc:h2:%s/%s/obstuna"; - - public static void restartEdit() { - ContentUI<?> selectedUI = ObserveSwingApplicationContext.get().getContentUIManager().getSelectedContentUI(); - if (selectedUI == null) { - - // pas d'écran selectionne - return; - } - ContentUIModel<? extends AbstractObserveDto> model = selectedUI.getModel(); - if (!model.isEditable()) { - - // modele non editable - return; - } - - ContentMode contentMode = model.getMode(); - if (ContentMode.UPDATE != contentMode) { - - // ecran non en mode mis a jour - return; - } - - if (log.isDebugEnabled()) { - log.debug("Will restart edit for " + selectedUI.getName()); - } - selectedUI.restartEdit(); - - } - - /** - * Permet de recharger l'ui principale et de changer de le mode - * d'affichage. - * - * @param rootContext le contexte applicatif - * @param config la configuration a utiliser - */ - protected void reloadUI(ObserveSwingApplicationContext rootContext, ObserveSwingApplicationConfig config) { - - // must remove all properties listener on config - config.removeJaxxPropertyChangeListener(); - - // scan main ui - ObserveMainUI ui = getUI(rootContext); - - ObserveSwingDataSource mainStorage = rootContext.getDataSourcesManager().getMainDataSource(); - - ObserveUIMode oldMode = null; - String[] ids = null; - if (ui != null) { - - oldMode = ui.getMode(); - - ids = ui.getTreeHelper().getSelectedIds(); - - ErrorDialogUI.init(null); - - rootContext.removeMainUI(); - - ui.dispose(); - - ui.setVisible(false); - - System.runFinalization(); - } - - ui = initUI(rootContext, config); - - if (oldMode == null) { - if (mainStorage == null) { - oldMode = ObserveUIMode.NO_DB; - - } else { - oldMode = ObserveUIMode.DB; - } - } - - ui.setMode(oldMode); - - if (oldMode == ObserveUIMode.DB) { - - // on conserve les noeuds a reselectionner - rootContext.setNodesToReselect(ids); - - // selection du noeud d'ouverture (le noeud precedemment selectionne, - // ou le noeud le plus ouvert - // ou le premier program si aucune donnée ouverte) - ui.getTreeHelper().selectInitialNode(); - } - - // show ui - UIHelper.setMainUIVisible(ui); - } - - protected Icon updateStorageSatutIcon(ObserveMainUI ui, boolean isOpened) { - Icon icon; - - if (ui.getConfig().isMainStorageOpened()) { - - ObserveSwingDataSource service = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); - - if (service.isLocal()) { - icon = (Icon) ui.storageStatus.getClientProperty("localIcon"); - } else if (service.isRemote()) { - icon = (Icon) ui.storageStatus.getClientProperty("remoteIcon"); - } else { - icon = (Icon) ui.storageStatus.getClientProperty("serverIcon"); - } - } else { - icon = (Icon) ui.storageStatus.getClientProperty("noneIcon"); - } - return icon; - } - - protected String updateStorageSatutText(ObserveMainUI ui, boolean isOpened) { - String text; - if (ui.getConfig().isMainStorageOpened()) { - ObserveSwingDataSource source = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); - text = source.getLabel(); - } else { - text = t("observe.message.db.none.loaded"); - } - return text; - } - - protected String updateStorageStatutToolTipText(ObserveMainUI ui, boolean isOpened) { - String text; - if (ui.getConfig().isMainStorageOpened()) { - ObserveSwingDataSource source = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); - text = t("observe.message.loaded.tip", source.getLabel()); - } else { - text = t("observe.message.db.none.loaded.tip"); - } - return text; - } - - public boolean acceptMode(ObserveUIMode mode, ObserveUIMode... modes) { - return acceptMode(mode, true, modes); - } - - public boolean acceptMode(ObserveUIMode mode, boolean condition, ObserveUIMode... modes) { - if (condition) { - for (ObserveUIMode m : modes) { - if (m.equals(mode)) { - return true; - } - } - } - return false; - } - - public boolean acceptMode(ObserveUIMode mode, boolean notBusy, boolean condition, ObserveUIMode... modes) { - if (notBusy && condition) { - for (ObserveUIMode m : modes) { - if (m.equals(mode)) { - return true; - } - } - } - return false; - } - - public boolean rejectMode(ObserveUIMode mode, ObserveUIMode... modes) { - for (ObserveUIMode m : modes) { - if (m.equals(mode)) { - return false; - } - } - return true; - } - - public boolean acceptLocale(Locale l, String expected) { - return l != null && l.toString().equals(expected); - } - - public ObserveMainUI getUI(JAXXContext context) { - if (context instanceof ObserveMainUI) { - return (ObserveMainUI) context; - } - ObserveMainUI ui = ObserveSwingApplicationContext.get().getMainUI(); - return ui; - } - - protected void $afterCompleteSetup(final ObserveMainUI ui) { - - ui.getStatus().init(); - - // ajout d'un ecouteur sur la navigation pour toujours mettre la scrollbar - // tout à droite a chaque selection - TreeSelectionListener listener; - listener = e -> { - changeNavigationNode(ui, e); - SwingUtilities.invokeLater(() -> { - ui.getNavigationScrollPane().getHorizontalScrollBar().setValue(0); - ui.getSplitpane2().resetToPreferredSizes(); - }); - }; - TreeWillExpandListener veteobableTreeWillExpand = new TreeWillExpandListener() { - @Override - public void treeWillExpand(TreeExpansionEvent event) { - } - - @Override - public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException { - - // le seul posant problème est la fermeture d'un noeud parent - // du noeud courant : cela va changer la selection - ObserveNode selectedNode = ui.getTreeHelper().getSelectedNode(); - if (selectedNode == null) { - // pas de noeud selectionne - return; - } - - ObserveNode o = (ObserveNode) event.getPath().getLastPathComponent(); - if (selectedNode.equals(o) || !selectedNode.isNodeAncestor(o)) { - return; - } - boolean canChange = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); - if (!canChange) { - throw new ExpandVetoException(event, "Can not collapse node " + event.getPath()); - } - } - }; - - ui.getTreeHelper().setUI(ui.getNavigation(), true, true, listener, veteobableTreeWillExpand); - - SwingValidatorUtil.installUI(ui.getErrorTable(), new ObserveValidatorMessageTableRenderer()); - - // installation layer de blocage en mode busy - UIHelper.setLayerUI(ui.getBody(), ui.getBusyBlockLayerUI()); - - // ecoute des changements de l'état busy - ui.addPropertyChangeListener(ObserveMainUI.PROPERTY_BUSY, evt -> { - Boolean newvalue = (Boolean) evt.getNewValue(); - updateBusyState(ui, newvalue != null && newvalue); - }); - } - - protected void updateBusyState(ObserveMainUI ui, boolean busy) { - if (busy) { - // ui bloquee - if (log.isDebugEnabled()) { - log.debug("block ui in busy mode"); - } - ui.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); - } else { - // ui debloquee - if (log.isDebugEnabled()) { - log.debug("unblock ui in none busy mode"); - } - ui.setCursor(Cursor.getDefaultCursor()); - } - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/ObserveUICallback.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/ObserveUICallback.java deleted file mode 100644 index 97ef533..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/ObserveUICallback.java +++ /dev/null @@ -1,115 +0,0 @@ -package fr.ird.observe.ui; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveRunner; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.ui.actions.CloseApplicationAction; -import fr.ird.observe.ui.actions.ReloadStorageAction; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.ImageIcon; - -import static org.nuiton.i18n.I18n.n; - -/** - * Définition des callback possibles lors d'une action. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public enum ObserveUICallback implements Runnable { - - application(n("observe.action.reload.application"), - "application-reload") { - @Override - public void run() { - if (log.isInfoEnabled()) { - log.info("will reload application"); - } - ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); - ObserveMainUIHandler handler = new ObserveMainUIHandler(); - ObserveMainUI ui = handler.getUI(context); - - if (log.isDebugEnabled()) { - log.debug("Ask to reload."); - } - ObserveRunner.getRunner().setReload(true); - new CloseApplicationAction(ui).run(); - } - }, - ui(n("observe.action.reload.ui"), - "ui-reload") { - @Override - public void run() { - if (log.isInfoEnabled()) { - log.info("will reload ui"); - } - ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); - ObserveMainUIHandler handler = new ObserveMainUIHandler(); - ObserveMainUI ui = handler.getUI(context); - ObserveSwingApplicationConfig config = ui.getConfig(); - handler.reloadUI(context, config); - } - }, - db(n("observe.action.reload.storage"), - "db-reload") { - @Override - public void run() { - if (log.isInfoEnabled()) { - log.info("will reload db"); - } - - ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); - ObserveMainUIHandler handler = new ObserveMainUIHandler(); - ObserveMainUI ui = handler.getUI(context); - new ReloadStorageAction(ui).run(); -// handler.launchReloadStorage(ui); - } - }; - - /** Logger. */ - private static final Log log = LogFactory.getLog(ObserveUICallback.class); - - private final String label; - - private final String iconPath; - - ObserveUICallback(String label, String iconPath) { - this.iconPath = iconPath; - this.label = label; - - getIcon(); - } - - public ImageIcon getIcon() { - ImageIcon icon = UIHelper.createActionIcon(iconPath); - return icon; - } - - public String getLabel() { - return label; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/ObserveUIMode.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/ObserveUIMode.java deleted file mode 100644 index 3e04cd3..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/ObserveUIMode.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui; - -/** - * Pour caractériser le mode en cours d'utilisation. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public enum ObserveUIMode { - - /** Pas de source de données chargé */ - NO_DB, - - /** Affichage - édition d'une source de données */ - DB, - - /** Pour affiher le mode server */ - SERVER, - - /** Opérations complexes */ - SYNCHRO -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/UIHelper.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/UIHelper.java deleted file mode 100644 index ae824cb..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/UIHelper.java +++ /dev/null @@ -1,595 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.ObserveSwingTechnicalException; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.services.dto.DataDto; -import fr.ird.observe.services.dto.DataFileDto; -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.security.InvalidAuthenticationTokenException; -import fr.ird.observe.ui.util.table.ObserveBooleanTableCellRenderer; -import jaxx.runtime.FileChooserUtil; -import jaxx.runtime.JAXXObject; -import jaxx.runtime.SwingUtil; -import jaxx.runtime.swing.ErrorDialogUI; -import jaxx.runtime.swing.renderer.DecoratorTableCellRenderer; -import org.apache.commons.io.FileUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.jdesktop.swingx.painter.Painter; -import org.nuiton.decorator.Decorator; - -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.JTree; -import javax.swing.SwingUtilities; -import javax.swing.UIDefaults; -import javax.swing.event.HyperlinkEvent; -import javax.swing.table.TableCellEditor; -import javax.swing.table.TableCellRenderer; -import java.awt.Color; -import java.awt.Component; -import java.awt.Desktop; -import java.awt.Toolkit; -import java.awt.datatransfer.Clipboard; -import java.awt.datatransfer.StringSelection; -import java.io.File; -import java.io.IOException; -import java.net.URISyntaxException; -import java.net.URL; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -import static org.nuiton.i18n.I18n.t; - -/** - * Une classe d'aide pour les ui - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class UIHelper extends SwingUtil { - - /** Logger */ - static private final Log log = LogFactory.getLog(UIHelper.class); - - /** - * Pattern to use for short numeric values in editors with max 3 digits. - * - * @since 2.3 - */ - public static final String INT_3_DIGITS_PATTERN = "\\d{0,3}"; - - /** - * Pattern to use for integer numeric values in editors with max 6 digits. - * - * @since 2.3 - */ - public static final String INT_6_DIGITS_PATTERN = "\\d{0,6}"; - - /** - * Pattern to use for integer numeric values in editors with max 7 digits. - * - * @since 2.3 - */ - public static final String INT_7_DIGITS_PATTERN = "\\d{0,7}"; - - /** - * Pattern to use for long numeric values in editors with max 10 digits. - * - * @since 3.7 - */ - public static final String LONG_10_DIGITS_PATTERN = "\\d{0,10}"; - - /** - * Pattern to use for decimal numeric values with 1 decimal digits in - * editors. - * - * @since 2.3 - */ - public static final String DECIMAL1_PATTERN = "\\d{0,6}|\\d{1,6}.\\d{0,1}"; - - /** - * Pattern to use for decimal numeric values with 2 decimal digits in - * editors. - * - * @since 2.3 - */ - public static final String DECIMAL2_PATTERN = "\\d{0,6}|\\d{1,6}.\\d{0,2}"; - - /** - * Pattern to use for decimal numeric values with 3 decimal digits in - * editors. - * - * @since 2.3 - */ - public static final String DECIMAL3_PATTERN = "\\d{0,6}|\\d{1,6}.\\d{0,3}"; - - /** - * Components which must NOT be blocked by any layer in ui. - * - * @since 2.0 - */ - public static final String[] ACCEPTABLE_COMPONENTS = { - // show progress ui in acess import - "showProgressButton", - // copy global progression of resume admin tab to clipboard - "globalProgressionCopyToClipBoard", - // copy progression of any admin tab to clipboard - "progressionTopCopyCliptBoard" - }; - - public static void displayInfo(String text) { - - ObserveMainUI ui = ObserveSwingApplicationContext.get().getMainUI(); - if (ui == null) { - JOptionPane.showMessageDialog(null, text); - } else { - ui.getStatus().setStatus(text); - } - } - - public static void displayWarning(String title, String text) { - - ObserveMainUI ui = ObserveSwingApplicationContext.get().getMainUI(); - JOptionPane.showMessageDialog(ui, text, title, JOptionPane.WARNING_MESSAGE); - - } - - public static int askUser(String title, - String message, - int typeMessage, - Object[] options, - int defaultOption) { - return askUser( - null, - title, - message, - typeMessage, - options, - defaultOption - ); - } - - public static int askUser(Component parent, - String title, - Object message, - int typeMessage, - Object[] options, - int defaultOption) { - if (parent == null) { - ObserveSwingApplicationContext tx = ObserveSwingApplicationContext.get(); - if (tx != null) { - parent = ObserveSwingApplicationContext.get().getMainUI(); - } - } - int response = JOptionPane.showOptionDialog( - parent, - message, - title, - JOptionPane.DEFAULT_OPTION, - typeMessage, - null, - options, - options[defaultOption] - ); - return response; - } - - /** - * Choisir un fichier via un sélecteur graphique de fichiers. - * - * @param parent le component swing appelant le controle - * @param title le titre du dialogue de sélection - * @param buttonLabel le label du boutton d'acceptation - * @param incoming le fichier de base à utilier - * @param filters les filtres + descriptions sur le sélecteur de - * fichiers - * @return le fichier choisi ou le fichier incoming si l'opération a été - * annulée - */ - public static File chooseFile(Component parent, - String title, - String buttonLabel, - File incoming, - String... filters) { - File oldBasedir = FileChooserUtil.getCurrentDirectory(); - if (incoming != null) { - File basedir; - if (incoming.isFile()) { - basedir = incoming.getParentFile(); - } else { - basedir = incoming; - } - if (basedir.exists()) { - FileChooserUtil.setCurrentDirectory(basedir); - } - } - File file = FileChooserUtil.getFile(title, buttonLabel, parent, filters); - if (log.isDebugEnabled()) { - log.debug(title + " : " + file); - } - FileChooserUtil.setCurrentDirectory(oldBasedir); - File result = file == null ? incoming : file; - return result; - } - - /** - * Choisir un répertoire via un sélecteur graphique de fichiers. - * - * @param parent le component swing appelant le controle - * @param title le titre de la boite de dialogue de sléection - * @param buttonLabel le label de l'action d'acceptation - * @param incoming le fichier de base à utiliser - * @return le répertoire choisi ou le répertoire incoming si l'opération a - * été annulée - */ - public static File chooseDirectory(Component parent, - String title, - String buttonLabel, - File incoming) { - File oldBasedir = FileChooserUtil.getCurrentDirectory(); - if (incoming != null) { - File basedir; - if (incoming.isFile()) { - basedir = incoming.getParentFile(); - } else { - basedir = incoming; - } - if (basedir.exists()) { - FileChooserUtil.setCurrentDirectory(basedir); - } - } - String file = FileChooserUtil.getDirectory(parent, title, buttonLabel); - if (log.isDebugEnabled()) { - log.debug(title + " : " + file); - } - FileChooserUtil.setCurrentDirectory(oldBasedir); - return file == null ? incoming : new File(file); - } - - /** - * Ouvre une demande de confirmation, avant suppression d'une entité. - * - * @param <E>le type de l'entité à supprimer - * @param parent le component graphique demande l'action - * @param beanClass le tyê de l'entité à supprimer - * @param bean l'entité à supprimer - * @return {@code true} si l'utilisateur a confitmé la suppression, - * {@code false} sinon. - */ - public static <E extends IdDto> boolean confirmForEntityDelete( - JAXXObject parent, - Class<E> beanClass, - E bean) { - - return confirmForEntityDelete(parent, beanClass, bean, null); - } - - /** - * Ouvre une demande de confirmation, avant suppression d'une entité. - * - * @param <E> le type de l'entité à supprimer - * @param parent le component graphique demande l'action - * @param beanClass le tyê de l'entité à supprimer - * @param bean l'entité à supprimer - * @param extraMessage un message supplémentaire a ajouter - * @return {@code true} si l'utilisateur a confitmé la suppression, - * {@code false} sinon. - */ - public static <E extends IdDto> boolean confirmForEntityDelete( - JAXXObject parent, - Class<E> beanClass, - E bean, - String extraMessage) { - ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); - - if (parent == null) { - // on cherche l'ui principale - parent = mainUI; - } - - if (mainUI != null) { - mainUI.setBusy(true); - } - DecoratorService decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); - Decorator<E> decorator = decoratorService.getDecoratorByType(beanClass); - String beanStr; - String messageDelete; - String type = DecoratorService.getEntityLabel(beanClass); - type = t(type); - - if (bean == null || bean.getId() == null || decorator == null) { - // delete new entity - messageDelete = t("observe.message.delete.new", type); - } else { - try { - // delete existing entity - beanStr = decorator.toString(bean); - messageDelete = t("observe.message.delete", type, beanStr); - } catch (Exception e) { - messageDelete = t("observe.message.delete.new", type); - } - } - - if (extraMessage != null) { - messageDelete += '\n' + extraMessage; - } - - int response = askUser((Component) parent, - t("observe.title.delete"), - messageDelete, - JOptionPane.WARNING_MESSAGE, - new Object[]{t("observe.choice.confirm.delete"), - t("observe.choice.cancel")}, - 1); - if (mainUI != null) { - mainUI.setBusy(true); - } - return response == 0; - } - - public static boolean confirmOverwriteFileIfExist(Component parent, File file) { - boolean write = true; - if (file.exists()) { - write = UIHelper.askUser( - parent, - t("observe.common.saveFile.overwrite.title"), - t("observe.common.saveFile.overwrite"), - JOptionPane.OK_CANCEL_OPTION, - new Object[] { - t("observe.common.saveFile.overwrite.ok"), - t("observe.common.saveFile.overwrite.cancel")}, - 1) == 0; - } - - return write; - } - - - public static DecoratorTableCellRenderer newDecorateTableCellRenderer( - TableCellRenderer renderer, Class<?> entityClass) { - Decorator<?> decorator = ObserveSwingApplicationContext.get().getDecoratorService().getDecoratorByType(entityClass); - return new DecoratorTableCellRenderer(renderer, decorator); - } - - public static DecoratorTableCellRenderer newDecorateTableCellRenderer( - TableCellRenderer renderer, Class<?> entityClass, String context) { - Decorator<?> decorator = ObserveSwingApplicationContext.get().getDecoratorService().getDecoratorByType(entityClass, context); - return new DecoratorTableCellRenderer(renderer, decorator); - } - - public static <T extends DataDto> DecoratorTableCellRenderer newDataReferenceDecorateTableCellRenderer(TableCellRenderer renderer, - Class<T> entityClass, - String context) { - Decorator<?> decorator = ObserveSwingApplicationContext.get().getDecoratorService().getDataReferenceDecorator(entityClass, context); - return new DecoratorTableCellRenderer(renderer, decorator); - } - - public static <T extends ReferentialDto> DecoratorTableCellRenderer newReferentialReferenceDecorateTableCellRenderer(TableCellRenderer renderer, - Class<T> entityClass) { - Decorator<?> decorator = ObserveSwingApplicationContext.get().getDecoratorService().getReferentialReferenceDecorator(entityClass); - return new DecoratorTableCellRenderer(renderer, decorator); - } - - /** - * Pour trier les types du référentiel selon leur décoration. - * - * @param classes les classes à trier - * @since 1.5 - */ - public static void sortReferentiel(List<Class> classes) { - - Collections.sort(classes, REFERENTIEL_COMPARATOR); - } - - /** - * Copy to clipBoard the content of the given text. - * - * @param text text to copy to clipboard - * @since 2.0 - */ - public static void copyToClipBoard(String text) { - - Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); - if (log.isInfoEnabled()) { - log.info("Put in clipboard :\n" + text); - } - StringSelection selection = new StringSelection(text); - clipboard.setContents(selection, selection); - } - - public static void setMainUIVisible(final ObserveMainUI ui) { - - // force le redimensionnement du splitpane - ui.getSplitpane().revalidate(); - - // force le redimensionnement du splitpane2 - ui.getSplitpane2().revalidate(); - - // affichage de l'interface graphique - SwingUtilities.invokeLater(() -> ui.setVisible(true)); - } - - public static <E extends IdDto> E getEntity(List<E> list, E entity) { - for (E e : list) { - if (e.getId().equals(entity.getId())) { - return e; - } - } - return null; - } - - public static final Comparator<Class> REFERENTIEL_COMPARATOR = new Comparator<Class>() { - - @Override - public int compare(Class o1, Class o2) { - String s1 = t(DecoratorService.getEntityLabel(o1)); - String s2 = t(DecoratorService.getEntityLabel(o2)); - return s1.compareTo(s2); - } - }; - - /** - * Open a link coming from a {@link HyperlinkEvent}. - * - * And try to open the link if an url in a browser. - * - * @param he the event to treate - * @since 1.6.0 - */ - public static void openLink(HyperlinkEvent he) { - if (he.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { - - if (Desktop.isDesktopSupported()) { - try { - URL u = he.getURL(); - if (u.getProtocol().equalsIgnoreCase("mailto") || - u.getProtocol().equalsIgnoreCase("http") || - u.getProtocol().equalsIgnoreCase("ftp") || - u.getProtocol().equalsIgnoreCase("file")) { - Desktop.getDesktop().browse(u.toURI()); - } - } catch (IOException | URISyntaxException e) { - if (log.isErrorEnabled()) { - log.error("Error while opening link", e); - } - } - } - } - } - - public static void stopEditing(JTable table) { - TableCellEditor cellEditor = table.getCellEditor(); - if (cellEditor != null) { - cellEditor.cancelCellEditing(); - } - } - - public static TableCellRenderer newBooleanTableCellRenderer( - TableCellRenderer renderer) { - return new ObserveBooleanTableCellRenderer(renderer); - } - - public static DataFileDto fileToDataFileDto(File file) { - - DataFileDto result = new DataFileDto(); - - try { - - byte[] fileContent = FileUtils.readFileToByteArray(file); - - result.setContent(fileContent); - result.setName(file.getName()); - - } catch (IOException e) { - throw new ObserveSwingTechnicalException("Could not read file: " + file, e); - } - - return result; - } - - public static void handlingError(Exception e) { - handlingError(e.getMessage(), e); - - } - - public static void handlingError(String message, Exception e) { - - if (log.isErrorEnabled()) { - log.error(message, e); - } - - if (containsExceptionInStack(e, InvalidAuthenticationTokenException.class)) { - - ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); - - // on indique que la source de donnée a expiré - context.getDataSourcesManager().getMainDataSource().expired(); - - ObserveMainUI observeMainUI = context.getMainUI(); - - int result = askUser(observeMainUI, - t("observe.storage.server.sessionExpire.title"), - t("observe.storage.server.sessionExpire"), - JOptionPane.OK_CANCEL_OPTION, - new Object[] { - t("observe.storage.server.sessionExpire.reload"), - t("observe.storage.server.sessionExpire.change"), - t("observe.storage.server.sessionExpire.close")}, - 0); - - - // FIXME SBavencoff 23/03/2016 est on sùr que l'erreur proviens du main storage ? - switch (result) { - case 0 : observeMainUI.getReloadStorageAction().run(); break; - case 1 : observeMainUI.getChangeStorageAction().run(); break; - default: observeMainUI.getCloseStorageAction().run(); break; - } - - } else { - ErrorDialogUI.showError(e); - } - - } - - static protected <E extends Throwable> boolean containsExceptionInStack(Throwable e, Class<E> type) { - - if (type.isInstance(e)) { - return true; - } - - while (e.getCause() != null) { - e = e.getCause(); - - if (type.isInstance(e)) { - return true; - } - - } - - return false; - - } - - - public static void initUI(JScrollPane selectedTreePane, JTree tree) { - - // customize tree selection colors - UIDefaults defaults = new UIDefaults(); - - Painter<JComponent> painter = (g, c, w, h) -> g.fillRect(0, 0, w, h); - defaults.put("Tree:TreeCell[Enabled+Selected].backgroundPainter", painter); - defaults.put("Tree:TreeCell[Enabled+Focused].backgroundPainter", painter); - defaults.put("Tree:TreeCell[Focused+Selected].backgroundPainter", painter); - - tree.putClientProperty("Nimbus.Overrides", defaults); - // Fix http://forge.codelutin.com/issues/2781 - selectedTreePane.getViewport().setBackground(Color.WHITE); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/AbstractObserveAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/AbstractObserveAction.java deleted file mode 100644 index fdeb04f..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/AbstractObserveAction.java +++ /dev/null @@ -1,54 +0,0 @@ -package fr.ird.observe.ui.actions; - -/*- - * #%L - * ObServe :: Application Swing - * %% - * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import javax.swing.AbstractAction; -import javax.swing.Icon; -import java.beans.PropertyChangeListener; - -/** - * Created on 03/11/15. - * - * @author Tony Chemit - chemit@codelutin.com - */ -public abstract class AbstractObserveAction extends AbstractAction { - - private static final long serialVersionUID = 1L; - - protected AbstractObserveAction(String name, Icon icon) { - super(name, icon); - } - - public synchronized void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { - if (changeSupport != null) { - changeSupport.addPropertyChangeListener(propertyName,listener); - } - - } - - public synchronized void removePropertyChangeListener(String propertyName,PropertyChangeListener listener) { - if (changeSupport != null) { - changeSupport.removePropertyChangeListener(propertyName,listener); - } - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ChangeApplicationLanguageAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ChangeApplicationLanguageAction.java deleted file mode 100644 index d25e755..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ChangeApplicationLanguageAction.java +++ /dev/null @@ -1,82 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.configuration.ObserveSwingApplicationConfigOption; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.ObserveUICallback; -import jaxx.runtime.SwingUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.AbstractAction; -import java.awt.event.ActionEvent; -import java.util.Locale; - -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.13 - */ -public class ChangeApplicationLanguageAction extends AbstractAction { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(ChangeApplicationLanguageAction.class); - - private final ObserveMainUI ui; - - private final Locale newLocale; - - public ChangeApplicationLanguageAction(ObserveMainUI ui, Locale newLocale, String name, String description) { - - super(name, SwingUtil.getUIManagerActionIcon("i18n-" + newLocale.getLanguage())); - this.ui = ui; - this.newLocale = newLocale; - putValue(SHORT_DESCRIPTION, description); - putValue(MNEMONIC_KEY, (int) newLocale.getLanguage().toUpperCase().charAt(0)); - - } - - @Override - public void actionPerformed(ActionEvent event) { - - if (log.isInfoEnabled()) { - log.info("ObServe changing application language..."); - } - boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); - if (canContinue) { - ObserveSwingApplicationConfig config = ui.getConfig(); - - // sauvegarde de la nouvelle locale - config.setOption(ObserveSwingApplicationConfigOption.LOCALE, newLocale); - ObserveUICallback.ui.run(); - } - - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ChangeDbLanguageAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ChangeDbLanguageAction.java deleted file mode 100644 index caedd2c..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ChangeDbLanguageAction.java +++ /dev/null @@ -1,83 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.configuration.ObserveSwingApplicationConfigOption; -import fr.ird.observe.services.dto.constants.ReferentialLocale; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.ObserveUICallback; -import jaxx.runtime.SwingUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.AbstractAction; -import java.awt.event.ActionEvent; - -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.13 - */ -public class ChangeDbLanguageAction extends AbstractAction { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(ChangeDbLanguageAction.class); - - private final ObserveMainUI ui; - - private final ReferentialLocale newLocale; - - public ChangeDbLanguageAction(ObserveMainUI ui, ReferentialLocale newLocale, String name, String description) { - - super(name, SwingUtil.getUIManagerActionIcon("i18n-" + newLocale.getLocale().getLanguage())); - this.ui = ui; - this.newLocale = newLocale; - putValue(SHORT_DESCRIPTION, description); - putValue(MNEMONIC_KEY, (int) newLocale.getLocale().getLanguage().toUpperCase().charAt(0)); - - } - - @Override - public void actionPerformed(ActionEvent event) { - - if (log.isInfoEnabled()) { - log.info("ObServe changing db language..."); - } - boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); - if (!canContinue) { - return; - } - ObserveSwingApplicationConfig config = ui.getConfig(); - - // sauvegarde de la nouvelle locale - config.setOption(ObserveSwingApplicationConfigOption.DB_LOCALE, newLocale.getLocale()); - ObserveUICallback.ui.run(); - - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ChangeStorageAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ChangeStorageAction.java deleted file mode 100644 index 48274ee..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ChangeStorageAction.java +++ /dev/null @@ -1,97 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.constants.DbMode; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.storage.StorageUILauncher; -import jaxx.runtime.SwingUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.AbstractAction; -import java.awt.event.ActionEvent; -import java.util.EnumSet; -import java.util.Set; -import java.util.stream.Collectors; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.13 - */ -public class ChangeStorageAction extends AbstractAction { - - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(ChangeStorageAction.class); - - private final ObserveMainUI ui; - - private final Set<DbMode> dbModes; - - private final String title; - - public ChangeStorageAction(ObserveMainUI ui) { - this(ui, null, null); - } - - public ChangeStorageAction(ObserveMainUI ui, Set<DbMode> dbModes, String title) { - - super(t("observe.action.change.storage"), SwingUtil.getUIManagerActionIcon("db-change")); - this.ui = ui; - this.dbModes = dbModes == null ? EnumSet.noneOf(DbMode.class) : dbModes; - this.title = title; - putValue(SHORT_DESCRIPTION, t("observe.action.change.storage.tip")); - putValue(MNEMONIC_KEY, (int) 'C'); - - } - - @Override - public void actionPerformed(ActionEvent e) { - - run(); - - } - - public void run() { - - boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); - if (canContinue) { - - if (log.isInfoEnabled()) { - log.info("Start change storage with dbMode: " + dbModes.stream().map(DbMode::name).collect(Collectors.joining(", "))); - } - - StorageUILauncher.changeStorage(ui, ui, dbModes, t(title)); - - } - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/CloseApplicationAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/CloseApplicationAction.java deleted file mode 100644 index 4103f10..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/CloseApplicationAction.java +++ /dev/null @@ -1,87 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveRunner; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.ui.ObserveMainUI; -import jaxx.runtime.SwingUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.AbstractAction; -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.13 - */ -public class CloseApplicationAction extends AbstractAction { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(CloseApplicationAction.class); - - private final ObserveMainUI ui; - - public CloseApplicationAction(ObserveMainUI ui) { - - super(t("observe.action.exit"), SwingUtil.getUIManagerActionIcon("exit")); - this.ui = ui; - putValue(SHORT_DESCRIPTION, t("observe.action.exit.tip")); - putValue(MNEMONIC_KEY, (int) 'X'); - - } - - @Override - public void actionPerformed(ActionEvent e) { - - - run(); - } - - public void run() { - - if (log.isInfoEnabled()) { - log.info("ObServe quitting..."); - } - boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); - if (canContinue) { - try { - ui.dispose(); - } finally { - if (log.isDebugEnabled()) { - log.debug("Ask to release runner."); - } - ObserveRunner.unlock(); - } - } - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/CloseHelpAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/CloseHelpAction.java deleted file mode 100644 index 72c08e4..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/CloseHelpAction.java +++ /dev/null @@ -1,76 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.ObserveUIMode; -import jaxx.runtime.SwingUtil; - -import javax.swing.AbstractAction; -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.13 - */ -public class CloseHelpAction extends AbstractAction { - - private static final long serialVersionUID = 1L; - - private final ObserveMainUI ui; - - public CloseHelpAction(ObserveMainUI ui) { - - super(null, SwingUtil.getUIManagerActionIcon("closeTab")); - this.ui = ui; - putValue(SHORT_DESCRIPTION, t("observe.action.quitHelp.tip")); - putValue(MNEMONIC_KEY, (int) 'F'); - - } - - @Override - public void actionPerformed(ActionEvent event) { - - ObserveUIMode oldMode = ui.getContextValue(ObserveUIMode.class, "oldMode"); - if (oldMode == null) { - - // on regarde si une base est chargee - ObserveSwingDataSource mainStorage = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); - - if (mainStorage == null) { - oldMode = ObserveUIMode.NO_DB; - } else { - oldMode = ObserveUIMode.DB; - } - } - ui.setMode(oldMode); - - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/CloseStorageAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/CloseStorageAction.java deleted file mode 100644 index 930884b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/CloseStorageAction.java +++ /dev/null @@ -1,86 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.ui.ObserveMainUI; -import jaxx.runtime.SwingUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.13 - */ -public class CloseStorageAction extends AbstractObserveAction { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(CloseStorageAction.class); - - private final ObserveMainUI ui; - - public CloseStorageAction(ObserveMainUI ui) { - - super(t("observe.action.close.storage"), SwingUtil.getUIManagerActionIcon("db-none")); - this.ui = ui; - putValue(SHORT_DESCRIPTION, t("observe.action.close.storage.tip")); - putValue(MNEMONIC_KEY, (int) 'F'); - - } - - @Override - public void actionPerformed(ActionEvent e) { - - run(); - - } - - public void run() { - - boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); - if (canContinue) { - ui.setBusy(true); - - try { - ObserveSwingDataSource source = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); - if (log.isDebugEnabled()) { - log.debug(">>> close main storage " + source); - } - // on doit fermer le storage en cours d'utilisation - source.close(); - } finally { - ui.setBusy(false); - } - } - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/GotoSiteAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/GotoSiteAction.java deleted file mode 100644 index af15e41..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/GotoSiteAction.java +++ /dev/null @@ -1,87 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.UIHelper; -import jaxx.runtime.SwingUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.AbstractAction; -import java.awt.Desktop; -import java.awt.event.ActionEvent; -import java.net.URL; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class GotoSiteAction extends AbstractAction { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(GotoSiteAction.class); - - private final ObserveMainUI ui; - - public GotoSiteAction(ObserveMainUI ui) { - - super(t("observe.action.site"), SwingUtil.getUIManagerActionIcon("site")); - this.ui = ui; - putValue(SHORT_DESCRIPTION, t("observe.action.site.tip")); - putValue(MNEMONIC_KEY, (int) 's'); - - } - - @Override - public void actionPerformed(ActionEvent e) { - - ObserveSwingApplicationConfig config = ui.getConfig(); - - URL siteURL = config.getOptionAsURL("application.site.url"); - - UIHelper.displayInfo( - t("observe.message.goto.site", siteURL)); - - if (log.isInfoEnabled()) { - log.info("goto " + siteURL); - } - if (Desktop.isDesktopSupported() && - Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) { - try { - Desktop.getDesktop().browse(siteURL.toURI()); - } catch (Exception ex) { - UIHelper.handlingError(ex); - } - } - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ImportStorageFromFileAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ImportStorageFromFileAction.java deleted file mode 100644 index 725d064..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ImportStorageFromFileAction.java +++ /dev/null @@ -1,105 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.constants.CreationMode; -import fr.ird.observe.db.constants.DbMode; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.storage.StorageStep; -import fr.ird.observe.ui.storage.StorageUI; -import fr.ird.observe.ui.storage.StorageUIHandler; -import fr.ird.observe.ui.storage.StorageUILauncher; -import fr.ird.observe.ui.storage.StorageUIModel; -import jaxx.runtime.SwingUtil; - -import javax.swing.AbstractAction; -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.13 - */ -public class ImportStorageFromFileAction extends AbstractAction { - - private static final long serialVersionUID = 1L; - - private final ObserveMainUI ui; - - public ImportStorageFromFileAction(ObserveMainUI ui) { - - super(t("observe.action.load.from.file"), SwingUtil.getUIManagerActionIcon("local-import")); - this.ui = ui; - putValue(SHORT_DESCRIPTION, t("observe.action.load.from.file.tip")); - putValue(MNEMONIC_KEY, (int) 'I'); - - } - - @Override - public void actionPerformed(ActionEvent e) { - - boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); - if (canContinue) { - - new StorageUILauncher(ui, ui, t("observe.title.import.localDB")) { - @Override - protected void init(StorageUI ui) { - super.init(ui); - StorageUIModel model = ui.getModel(); - - model.setCanCreateLocalService(true); - model.setCanUseLocalService(false); - model.setCanUseRemoteService(false); - model.setCanUseServerService(false); - model.setDbMode(DbMode.CREATE_LOCAL); - model.setCreationMode(CreationMode.IMPORT_EXTERNAL_DUMP); - if (model.isLocalStorageExist()) { - // sauvegarde base locale possible - model.setSteps(StorageStep.CONFIG, - StorageStep.BACKUP, - StorageStep.CONFIRM); - - // et requise par défaut - model.setDoBackup(true); - } else { - model.setSteps(StorageStep.CONFIG, StorageStep.CONFIRM); - } - } - - @Override - protected void doAction(StorageUI ui) { - super.doAction(ui); - StorageUIHandler handler = getStorageUIHandler(); - handler.doChangeStorage(ui.getModel()); - } - - }.start(); - } - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/LaunchAdminAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/LaunchAdminAction.java deleted file mode 100644 index eeb5abe..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/LaunchAdminAction.java +++ /dev/null @@ -1,79 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.admin.AdminStep; -import fr.ird.observe.ui.admin.AdminUILauncher; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.AbstractAction; -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.13 - */ -public class LaunchAdminAction extends AbstractAction { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(LaunchAdminAction.class); - - private final ObserveMainUI ui; - - private final AdminStep action; - - public LaunchAdminAction(ObserveMainUI ui, AdminStep action) { - - super(t(action.getOperationLabel()), action.getIcon()); - this.ui = ui; - this.action = action; - putValue(SHORT_DESCRIPTION, t(action.getOperationDescription())); - putValue(MNEMONIC_KEY, (int) t(action.getOperationLabel()).charAt(0)); - - } - - @Override - public void actionPerformed(ActionEvent event) { - - boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); - if (canContinue) { - - if (log.isInfoEnabled()) { - log.info("Will start admin action: " + action.getLabel()); - } - AdminUILauncher launcher = AdminUILauncher.newLauncher(ui, action); - launcher.start(); - } - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ReloadApplicationAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ReloadApplicationAction.java deleted file mode 100644 index 7263b23..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ReloadApplicationAction.java +++ /dev/null @@ -1,73 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.ObserveUICallback; -import jaxx.runtime.SwingUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.AbstractAction; -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ReloadApplicationAction extends AbstractAction { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(ReloadApplicationAction.class); - - private final ObserveMainUI ui; - - public ReloadApplicationAction(ObserveMainUI ui) { - - super(t("observe.action.restart.application"), SwingUtil.getUIManagerActionIcon("application-reload")); - this.ui = ui; - putValue(SHORT_DESCRIPTION, t("observe.action.restart.application.tip")); - putValue(MNEMONIC_KEY, (int) 'X'); - - } - - @Override - public void actionPerformed(ActionEvent event) { - - if (log.isInfoEnabled()) { - log.info("ObServe reloading..."); - } - boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); - if (canContinue) { - ObserveUICallback.application.run(); - } - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ReloadDefaultConfigurationAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ReloadDefaultConfigurationAction.java deleted file mode 100644 index 71e3173..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ReloadDefaultConfigurationAction.java +++ /dev/null @@ -1,95 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.ObserveUICallback; -import jaxx.runtime.SwingUtil; -import org.apache.commons.io.FileUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.AbstractAction; -import java.awt.event.ActionEvent; -import java.io.File; -import java.io.IOException; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ReloadDefaultConfigurationAction extends AbstractAction { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(ReloadDefaultConfigurationAction.class); - - private final ObserveMainUI ui; - - public ReloadDefaultConfigurationAction(ObserveMainUI ui) { - - super(t("observe.action.reloadDefaultConfiguration"), SwingUtil.getUIManagerActionIcon("application-reload")); - this.ui = ui; - putValue(SHORT_DESCRIPTION, t("observe.action.reloadDefaultConfiguration.tip")); - putValue(MNEMONIC_KEY, (int) 'R'); - - } - - @Override - public void actionPerformed(ActionEvent event) { - - if (log.isInfoEnabled()) { - log.info("ObServe reloading default configuration..."); - } - - boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); - if (canContinue) { - ObserveSwingApplicationConfig config = ui.getConfig(); - - File directory = config.getResourcesDirectory(); - - if (log.isInfoEnabled()) { - log.info(t("observe.message.delete.directory", directory)); - } - - // suppression du répertoire des ressources - try { - FileUtils.deleteDirectory(directory); - } catch (IOException e) { - if (log.isErrorEnabled()) { - log.error("Could not delete resources directory: " + directory, e); - } - } - - ObserveUICallback.application.run(); - } - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ReloadResourcesAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ReloadResourcesAction.java deleted file mode 100644 index 6d51e6b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ReloadResourcesAction.java +++ /dev/null @@ -1,109 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.ObserveRunner; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.ObserveUICallback; -import jaxx.runtime.SwingUtil; -import org.apache.commons.io.FileUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.i18n.I18n; - -import javax.swing.AbstractAction; -import java.awt.event.ActionEvent; -import java.io.File; -import java.io.IOException; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.13 - */ -public class ReloadResourcesAction extends AbstractAction { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(ReloadResourcesAction.class); - - private final ObserveMainUI ui; - - public ReloadResourcesAction(ObserveMainUI ui) { - - super(t("observe.action.reloadResources"), SwingUtil.getUIManagerActionIcon("application-reload")); - this.ui = ui; - putValue(SHORT_DESCRIPTION, t("observe.action.reloadResources.tip")); - putValue(MNEMONIC_KEY, (int) 'R'); - - } - - @Override - public void actionPerformed(ActionEvent event) { - - if (log.isInfoEnabled()) { - log.info("ObServe reloading resources..."); - } - - boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); - if (canContinue) { - ObserveSwingApplicationConfig config = ui.getConfig(); - - File directory = config.getResourcesDirectory(); - - if (log.isInfoEnabled()) { - log.info(t("observe.message.delete.directory", directory)); - } - - // suppression du répertoire - try { - FileUtils.deleteDirectory(directory); - } catch (IOException e) { - if (log.isErrorEnabled()) { - log.error("Could not delete resources directory: " + directory, e); - } - } - - I18n.reload(); - - DecoratorService decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); - - if (log.isInfoEnabled()) { - log.info("reload decorators"); - } - decoratorService.reload(); - - ObserveRunner.getRunner().loadUIConfig(config); - - ObserveUICallback.ui.run(); - } - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ReloadStorageAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ReloadStorageAction.java deleted file mode 100644 index 1896580..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ReloadStorageAction.java +++ /dev/null @@ -1,125 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaH2; -import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaPG; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.UIHelper; -import jaxx.runtime.SwingUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.t; -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.13 - */ -public class ReloadStorageAction extends AbstractObserveAction { - - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(ReloadStorageAction.class); - - private final ObserveMainUI ui; - - public ReloadStorageAction(ObserveMainUI ui) { - - super(t("observe.action.reload.storage"), SwingUtil.getUIManagerActionIcon("db-reload")); - this.ui = ui; - putValue(SHORT_DESCRIPTION, t("observe.action.reload.storage.tip")); - putValue(MNEMONIC_KEY, (int) 'R'); - - } - - @Override - public void actionPerformed(ActionEvent e) { - - run(); - - } - - public void run() { - - ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); - boolean canContinue = context.getContentUIManager().closeSelectedContentUI(); - - ObserveSwingDataSource storage = context.getDataSourcesManager().getMainDataSource(); - - if (canContinue && storage != null) { - - ui.setBusy(false); - - String[] ids = ui.getTreeHelper().getSelectedIds(); - - try { - - if (log.isDebugEnabled()) { - log.debug(">>> close main storage " + storage); - } - // fermeture du storage courant - storage.close(); - - ObserveSwingApplicationConfig appConfig = context.getConfig(); - - if (storage.isLocal()) { - - ObserveDataSourceConfigurationTopiaH2 h2Config = (ObserveDataSourceConfigurationTopiaH2) storage.getConfiguration(); - - h2Config.setCanMigrate(appConfig.isCanMigrateH2()); - } else if (storage.isRemote()) { - ObserveDataSourceConfigurationTopiaPG pgConfig = (ObserveDataSourceConfigurationTopiaPG) storage.getConfiguration(); - pgConfig.setCanMigrate(appConfig.isCanMigrateObstuna()); - } - - try { - - - // on conserve les noeuds a selectionner - context.setNodesToReselect(ids); - - // attachement a l'ui - context.prepareMainStorage(storage, false); - - // ouverture du service - storage.open(); - } catch (Exception e) { - UIHelper.handlingError(e); - } - - } finally { - ui.setBusy(false); - } - - } - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/SaveStorageToFileAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/SaveStorageToFileAction.java deleted file mode 100644 index f47772a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/SaveStorageToFileAction.java +++ /dev/null @@ -1,92 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.storage.StorageBackupUILauncher; -import jaxx.runtime.SwingUtil; - -import javax.swing.JOptionPane; -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.13 - */ -public class SaveStorageToFileAction extends AbstractObserveAction { - - private static final long serialVersionUID = 1L; - - private final ObserveMainUI ui; - - public SaveStorageToFileAction(ObserveMainUI ui) { - - super(t("observe.action.save.to.file"), SwingUtil.getUIManagerActionIcon("local-export")); - this.ui = ui; - putValue(SHORT_DESCRIPTION, t("observe.action.save.to.file.tip")); - putValue(MNEMONIC_KEY, (int) 'L'); - - } - - @Override - public void actionPerformed(ActionEvent e) { - - boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); - if (canContinue) { - - // on teste que l'utilisateur peut lire-ecrire sur la source de données - - ObserveSwingDataSource service = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); - - if (!service.isLocal() && !(service.canReadData() && service.canWriteData())) { - - UIHelper.askUser( - null, - t("observe.title.can.not.export.obstuna"), - t("observe.storage.required.rw.on.data", service), - JOptionPane.ERROR_MESSAGE, - new Object[]{t("observe.choice.cancel")}, - 0 - ); - return; - } - - String title = service.isLocal() ? - t("observe.title.save.localDB") : - t("observe.title.save.remoteDB"); - - StorageBackupUILauncher launcher = - new StorageBackupUILauncher(ui, ui, title); - launcher.start(); - } - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ShowAboutAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ShowAboutAction.java deleted file mode 100644 index 7c760ea..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ShowAboutAction.java +++ /dev/null @@ -1,126 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveRunner; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.UIHelper; -import jaxx.runtime.SwingUtil; -import jaxx.runtime.swing.AboutPanel; -import org.nuiton.util.Resource; - -import javax.swing.AbstractAction; -import javax.swing.Icon; -import javax.swing.JEditorPane; -import javax.swing.JLabel; -import javax.swing.JScrollPane; -import java.awt.BorderLayout; -import java.awt.event.ActionEvent; -import java.io.File; -import java.net.MalformedURLException; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.13 - */ -public class ShowAboutAction extends AbstractAction { - - private static final long serialVersionUID = 1L; - - private final ObserveMainUI ui; - - public ShowAboutAction(ObserveMainUI ui) { - - super(t("observe.action.about"), SwingUtil.getUIManagerActionIcon("about")); - this.ui = ui; - putValue(SHORT_DESCRIPTION, t("observe.action.about.tip")); - putValue(MNEMONIC_KEY, (int) 'A'); - - } - - @Override - public void actionPerformed(ActionEvent event) { - - AboutPanel about = new AboutPanel() { - - private static final long serialVersionUID = 1L; - - @Override - public void buildTopPanel() { - topPanel.setLayout(new BorderLayout()); - JLabel labelIcon; - Icon logoIcon; - logoIcon = Resource.getIcon("/icons/logo-OT_web.png"); - labelIcon = new JLabel(logoIcon); - topPanel.add(labelIcon, BorderLayout.WEST); - - logoIcon = Resource.getIcon("/icons/logo_ird.png"); - labelIcon = new JLabel(logoIcon); - topPanel.add(labelIcon, BorderLayout.EAST); - } - }; - - String name = ObserveRunner.getRunner().getRunnerName(); - about.setTitle(t("observe.title.about")); - about.setAboutText(t("observe.about.message")); - about.setBottomText(ui.getConfig().getCopyrightText()); - about.setIconPath("/icons/logo-OT_web.png"); - about.setLicenseFile("META-INF/" + name + "-LICENSE.txt"); - about.setThirdpartyFile("META-INF/" + name + "-THIRD-PARTY.txt"); - about.buildTopPanel(); - - // - // translate tab - // - - JScrollPane translatePane = new JScrollPane(); - JEditorPane translateArea = new JEditorPane(); - translateArea.setContentType("text/html"); - translateArea.setEditable(false); - if (translateArea.getFont() != null) { - translateArea.setFont(translateArea.getFont().deriveFont((float) 11)); - } - - translateArea.setBorder(null); - File csvFile = new File(ui.getConfig().getI18nDirectory(), "observe-i18n.csv"); - String translateText; - try { - translateText = t("observe.about.translate.content", csvFile.toURI().toURL()); - } catch (MalformedURLException e) { - throw new RuntimeException("Could not obtain url from " + csvFile, e); - } - translateArea.setText(translateText); - translatePane.getViewport().add(translateArea); - translateArea.addHyperlinkListener(UIHelper::openLink); - - about.getTabs().add(t("observe.about.translate.title"), translatePane); - - about.init(); - about.showInDialog(ui, true); - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ShowConfigAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ShowConfigAction.java deleted file mode 100644 index 4b44693..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ShowConfigAction.java +++ /dev/null @@ -1,500 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.configuration.ObserveSwingApplicationConfigOption; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.SpeciesListDto; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.ObserveMainUIHandler; -import fr.ird.observe.ui.ObserveUICallback; -import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; -import jaxx.runtime.SwingUtil; -import jaxx.runtime.swing.config.ConfigUIHelper; -import jaxx.runtime.swing.config.model.ConfigUIModelBuilder; -import jaxx.runtime.swing.config.model.MainCallBackFinalizer; -import jaxx.runtime.swing.editor.bean.BeanFilterableComboBox; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.jdesktop.swingx.renderer.DefaultTableRenderer; -import org.nuiton.config.ConfigOptionDef; -import org.nuiton.decorator.Decorator; -import org.nuiton.decorator.MultiJXPathDecorator; - -import javax.swing.AbstractAction; -import javax.swing.DefaultCellEditor; -import javax.swing.Icon; -import javax.swing.JComboBox; -import javax.swing.JTable; -import java.awt.Component; -import java.awt.event.ActionEvent; -import java.awt.event.MouseEvent; -import java.util.Collection; -import java.util.EventObject; -import java.util.Map; -import java.util.Set; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.13 - */ -public class ShowConfigAction extends AbstractAction { - - private static final long serialVersionUID = 3038774900992805790L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(ShowConfigAction.class); - - private final ObserveMainUI ui; - - public ShowConfigAction(ObserveMainUI ui) { - - super(t("observe.action.configuration"), SwingUtil.getUIManagerActionIcon("config")); - this.ui = ui; - putValue(SHORT_DESCRIPTION, t("observe.action.configuration.tip")); - putValue(MNEMONIC_KEY, (int) 'C'); - - } - - @Override - public void actionPerformed(ActionEvent event) { - - - if (log.isInfoEnabled()) { - log.info("ObServe opening configuration ui..."); - } - boolean canContinue = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); - if (canContinue) { - - ObserveSwingDataSource dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); - - ObserveSwingApplicationConfig config = ui.getConfig(); - - ObserveConfigUIBuilder helper; - - helper = buildUI(config, dataSource); - - helper.buildUI(ui, "observe.config.category.directories"); - - helper.displayUI(ui, false); - - } - - } - - protected ObserveConfigUIBuilder buildUI(ObserveSwingApplicationConfig config, ObserveSwingDataSource dataSource) { - - SpeciesListTableCellEditor editor = null; - SpeciesListsTableCellRenderer renderer = null; - - if (dataSource != null) { - - Set<ReferentialReference<SpeciesListDto>> speciesLists = dataSource.getReferentialReferences(SpeciesListDto.class); - - Map<String, ReferentialReference<SpeciesListDto>> speciesListMap = ReferentialReference.splitById(speciesLists); - - ReferentialReferenceDecorator<SpeciesListDto> referenceDecorator = ObserveSwingApplicationContext.get().getDecoratorService().getReferentialReferenceDecorator(SpeciesListDto.class); - - editor = new SpeciesListTableCellEditor(speciesLists, speciesListMap, referenceDecorator); - renderer = new SpeciesListsTableCellRenderer(speciesListMap, referenceDecorator); - - } - - ObserveConfigUIBuilder helper = new ObserveConfigUIBuilder(config, editor, renderer); - - - for (ObserveUICallback callback : ObserveUICallback.values()) { - helper.registerCallBack(callback); - } - - helper.setFinalizer(new MainCallBackFinalizer(ObserveUICallback.application.name())); - - helper.setCloseAction(ObserveMainUIHandler::restartEdit); - - // categorie repertoires - addDirectoriesOptions(helper); - - // categorie h2 - addH2Options(helper); - - // categorie obtuna - addObstunaOptions(helper); - - // categorie change storage - addChangeStorageOptions(helper); - - // categorie gps - addGpsOptions(helper); - - // categorie synchro - addSynchroOptions(helper); - - // categorie observations (seine) - addObservationsOptions(helper); - - if (dataSource != null) { - - // categorie speciesList (seine) - addSeineSpeciesListOptions(helper); - - // categorie speciesList (longline) - addLonglineSpeciesListOptions(helper); - - } - - // catégories map - addMapOptions(helper); - - // others - addOthersOptions(helper); - - return helper; - - } - - protected void addDirectoriesOptions(ObserveConfigUIBuilder helper) { - - helper.addCategory( - n("observe.config.category.directories"), - n("observe.config.category.directories.description")); - - helper.addOption(ObserveSwingApplicationConfigOption.CONFIG_FILE); - helper.addOption(ObserveSwingApplicationConfigOption.DATA_DIRECTORY); - helper.addOption(ObserveSwingApplicationConfigOption.DB_DIRECTORY); - helper.addOption(ObserveSwingApplicationConfigOption.BACKUP_DIRECTORY); - helper.addOption(ObserveSwingApplicationConfigOption.TMP_DIRECTORY); - helper.addOption(ObserveSwingApplicationConfigOption.VALIDATION_REPORT_DIRECTORY); - helper.addOption(ObserveSwingApplicationConfigOption.RESOURCES_DIRECTORY, ObserveUICallback.application); - - } - - protected void addH2Options(ObserveConfigUIBuilder helper) { - - helper.addCategory(n("observe.config.category.h2"), - n("observe.config.category.h2.description")); - - helper.addOption(ObserveSwingApplicationConfigOption.H2_LOGIN); - helper.addOption(ObserveSwingApplicationConfigOption.H2_PASSWORD); - helper.addOption(ObserveSwingApplicationConfigOption.H2_CAN_MIGRATE); - helper.addOption(ObserveSwingApplicationConfigOption.H2_SERVER_PORT); - - } - - protected void addObstunaOptions(ObserveConfigUIBuilder helper) { - - helper.addCategory(n("observe.config.category.obstuna"), - n("observe.config.category.obstuna.description")); - - helper.addOption(ObserveSwingApplicationConfigOption.OBSTUNA_URL); - helper.addOption(ObserveSwingApplicationConfigOption.OBSTUNA_LOGIN); - helper.addOption(ObserveSwingApplicationConfigOption.OBSTUNA_USE_SSL_CERT); -// helper.addOption(ObserveSwingApplicationConfigOption.OBSTUNA_SSL_CERTIFICAT_FILE); - - helper.addOption(ObserveSwingApplicationConfigOption.OBSTUNA_CAN_MIGRATE, ObserveUICallback.db); - - } - - protected void addChangeStorageOptions(ObserveConfigUIBuilder helper) { - - helper.addCategory( - n("observe.config.category.changeStorage"), - n("observe.config.category.changeStorage.description")); - - helper.addOption(ObserveSwingApplicationConfigOption.DEFAULT_DB_MODE); - helper.addOption(ObserveSwingApplicationConfigOption.DEFAULT_CREATION_MODE); - helper.addOption(ObserveSwingApplicationConfigOption.STORE_REMOTE_STORAGE); - helper.addOption(ObserveSwingApplicationConfigOption.SHOW_MIGRATION_PROGRESSION); - helper.addOption(ObserveSwingApplicationConfigOption.SHOW_MIGRATION_SQL); - helper.addOption(ObserveSwingApplicationConfigOption.SHOW_SQL, ObserveUICallback.application); - - } - - protected void addGpsOptions(ObserveConfigUIBuilder helper) { - - helper.addCategory(n("observe.config.category.gps"), - n("observe.config.category.gps.description")); - - helper.addOption(ObserveSwingApplicationConfigOption.DEFAULT_GPS_MAX_DELAY); - helper.addOption(ObserveSwingApplicationConfigOption.DEFAULT_GPS_MAX_SPEED); - - } - - protected void addSynchroOptions(ObserveConfigUIBuilder helper) { - - helper.addCategory(n("observe.config.category.synchro"), - n("observe.config.category.synchro.description")); - - helper.addOption(ObserveSwingApplicationConfigOption.CHANGE_SYNCHRO_SRC); - helper.addOption(ObserveSwingApplicationConfigOption.H2_CAN_MIGRATE); - - } - - protected void addObservationsOptions(ObserveConfigUIBuilder helper) { - - helper.addCategory( - n("observe.config.category.observation"), - n("observe.config.category.observation.description"), - ObserveUICallback.ui.name()); - - helper.addOption(ObserveSwingApplicationConfigOption.DETAILLED_ACTIVITIES_OBSERVATION); - helper.addOption(ObserveSwingApplicationConfigOption.NON_TARGET_OBSERVATION); - helper.addOption(ObserveSwingApplicationConfigOption.BAIT_OBSERVATION); - helper.addOption(ObserveSwingApplicationConfigOption.MAMMALS_OBSERVATION); - helper.addOption(ObserveSwingApplicationConfigOption.SAMPLES_OBSERVATION); - helper.addOption(ObserveSwingApplicationConfigOption.OBJECTS_OBSERVATION); - helper.addOption(ObserveSwingApplicationConfigOption.BIRDS_OBSERVATION); - helper.addOption(ObserveSwingApplicationConfigOption.TARGET_DISCARDS_OBSERVATION); - - } - - protected void addSeineSpeciesListOptions(ObserveConfigUIBuilder helper) { - - helper.addCategory( - n("observe.config.category.speciesList.seine"), - n("observe.config.category.speciesList.seine.description"), - ObserveUICallback.ui.name()); - - helper.addSpeciesListOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_TARGET_CATCH_ID); - helper.addSpeciesListOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_SCHOOL_ESTIMATE_ID); - helper.addSpeciesListOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_OBJECT_SCHOOL_ESTIMATE_ID); - helper.addSpeciesListOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_NON_TARGET_CATCH_ID); - helper.addSpeciesListOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_SEINE_OBJECT_OBSERVED_SPECIES_ID); - - } - - protected void addLonglineSpeciesListOptions(ObserveConfigUIBuilder helper) { - - - helper.addCategory( - n("observe.config.category.speciesList.longline"), - n("observe.config.category.speciesList.longline.description"), - ObserveUICallback.ui.name()); - - helper.addSpeciesListOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_LONGLINE_CATCH_ID); - helper.addSpeciesListOption(ObserveSwingApplicationConfigOption.SPECIES_LIST_LONGLINE_ENCOUNTER_ID); - - } - - protected void addMapOptions(ObserveConfigUIBuilder helper) { - - helper.addCategory( - n("observe.config.category.map"), - n("observe.config.category.map.description"), - ObserveUICallback.ui.name()); - - helper.addOption(ObserveSwingApplicationConfigOption.MAP_BACKGROUND_COLOR); - for (ObserveSwingApplicationConfigOption layerOption : ObserveSwingApplicationConfigOption.MAP_LAYERS) { - helper.addOption(layerOption); - } - helper.addOption(ObserveSwingApplicationConfigOption.MAP_STYLE_FILE); - - } - - protected void addOthersOptions(ObserveConfigUIBuilder helper) { - - helper.addCategory(n("observe.config.category.other"), - n("observe.config.category.other.description")); - - helper.addOption(ObserveSwingApplicationConfigOption.SHOW_NUMBER_EDITOR_BUTTON); - helper.addOption(ObserveSwingApplicationConfigOption.AUTO_POPUP_NUMBER_EDITOR); - helper.addOption(ObserveSwingApplicationConfigOption.SHOW_DATE_TIME_EDITOR_SLIDER); - helper.addOption(ObserveSwingApplicationConfigOption.LOAD_LOCAL_STORAGE, ObserveUICallback.application); -// helper.addOption(ObserveSwingApplicationConfigOption.FULL_SCREEN, ObserveUICallback.ui); - helper.addOption(ObserveSwingApplicationConfigOption.LOCALE, ObserveUICallback.ui); - helper.addOption(ObserveSwingApplicationConfigOption.DB_LOCALE, ObserveUICallback.ui); - - } - - protected class ObserveConfigUIBuilder extends ConfigUIHelper { - - private final SpeciesListTableCellEditor speciesListTableCellEditor; - - private final SpeciesListsTableCellRenderer speciesListsTableCellRenderer; - - protected ObserveConfigUIBuilder(ObserveSwingApplicationConfig config, - SpeciesListTableCellEditor speciesListTableCellEditor, - SpeciesListsTableCellRenderer speciesListsTableCellRenderer) { - super(config); - this.speciesListTableCellEditor = speciesListTableCellEditor; - this.speciesListsTableCellRenderer = speciesListsTableCellRenderer; - } - - @Override - public ConfigUIModelBuilder addOption(ConfigOptionDef option) { - - // add the option - super.addOption(option); - - String beanProperty = ((ObserveSwingApplicationConfigOption) option).getPropertyKey(); - - if (StringUtils.isNotEmpty(beanProperty)) { - setOptionPropertyName(beanProperty); - } - - return modelBuilder; - - } - - public ConfigUIModelBuilder addOption(ObserveSwingApplicationConfigOption option, ObserveUICallback callBack) { - - addOption(option); - setOptionCallBack(callBack.name()); - - return modelBuilder; - - } - - public ConfigUIModelBuilder registerCallBack(ObserveUICallback callback) { - - String name = callback.name(); - String description = callback.getLabel(); - Icon icon = callback.getIcon(); - Runnable action = callback; - registerCallBack(name, description, icon, action); - - return modelBuilder; - - } - - protected ConfigUIModelBuilder addSpeciesListOption(ObserveSwingApplicationConfigOption option) { - - addOption(option) - .setOptionPropertyName(option.getPropertyKey()) - .setOptionEditor(speciesListTableCellEditor) - .setOptionRenderer(speciesListsTableCellRenderer); - - return modelBuilder; - - } - - } - - protected class SpeciesListsTableCellRenderer extends DefaultTableRenderer { - - private static final long serialVersionUID = 1L; - - private final Map<String, ReferentialReference<SpeciesListDto>> entityMap; - - private final Decorator<ReferentialReference<SpeciesListDto>> decorator; - - public SpeciesListsTableCellRenderer(Map<String, ReferentialReference<SpeciesListDto>> entityMap, Decorator<ReferentialReference<SpeciesListDto>> decorator) { - this.entityMap = entityMap; - this.decorator = decorator; - } - - @Override - public Component getTableCellRendererComponent(JTable table, Object value, - boolean isSelected, boolean hasFocus, - int row, int column) { - - String speciesListId = String.valueOf(value); - ReferentialReference<SpeciesListDto> speciesList = entityMap.get(speciesListId); - return super.getTableCellRendererComponent(table, decorator.toString(speciesList), isSelected, hasFocus, row, column); - - } - } - - protected class SpeciesListTableCellEditor extends DefaultCellEditor { - - private static final long serialVersionUID = 1L; - - private final Map<String, ReferentialReference<SpeciesListDto>> entityMap; - - private final ReferentialReferenceDecorator<SpeciesListDto> decorator; - - protected SpeciesListTableCellEditor(Collection<ReferentialReference<SpeciesListDto>> entities, - Map<String, ReferentialReference<SpeciesListDto>> entityMap, - ReferentialReferenceDecorator<SpeciesListDto> decorator) { - - super(new JComboBox()); - - this.entityMap = entityMap; - this.decorator = decorator; - - final BeanFilterableComboBox<ReferentialReference<SpeciesListDto>> component = new BeanFilterableComboBox<>(); - component.setI18nPrefix("observe.common."); - component.setShowReset(true); - component.setBeanType((Class) ReferentialReference.class); - - setClickCountToStart(1); - - editorComponent = component; - delegate = new DefaultCellEditor.EditorDelegate() { - - private static final long serialVersionUID = 1L; - - @Override - public void setValue(Object value) { - if (value != null && String.class.isInstance(value)) { - - value = SpeciesListTableCellEditor.this.entityMap.get(value); - } - component.setSelectedItem(value); - } - - @Override - public Object getCellEditorValue() { - String result = null; - Object selectedItem = component.getSelectedItem(); - if (selectedItem != null && ReferentialReference.class.isInstance(selectedItem)) { - ReferentialReference reference = (ReferentialReference) selectedItem; - result = reference.getId(); - } - return result; - } - - @Override - public boolean shouldSelectCell(EventObject anEvent) { - if (anEvent instanceof MouseEvent) { - MouseEvent e = (MouseEvent) anEvent; - return e.getID() != MouseEvent.MOUSE_DRAGGED; - } - return true; - } - - @Override - public boolean stopCellEditing() { - if (component.isEditable()) { - // Commit edited value. - component.getCombobox().actionPerformed( - new ActionEvent(SpeciesListTableCellEditor.this, 0, "")); - } - return super.stopCellEditing(); - } - }; - - component.init((MultiJXPathDecorator) this.decorator, Lists.newArrayList(entities)); - } - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ShowStorageInfoAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ShowStorageInfoAction.java deleted file mode 100644 index dc46a97..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/ShowStorageInfoAction.java +++ /dev/null @@ -1,81 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.ObserveTextGenerator; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.ui.ObserveMainUI; -import jaxx.runtime.SwingUtil; - -import javax.swing.AbstractAction; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.13 - */ -public class ShowStorageInfoAction extends AbstractAction { - - private static final long serialVersionUID = 1L; - - private final ObserveMainUI ui; - - public ShowStorageInfoAction(ObserveMainUI ui) { - - super(t("observe.action.info.storage"), SwingUtil.getUIManagerActionIcon("information")); - this.ui = ui; - putValue(SHORT_DESCRIPTION, t("observe.action.info.storage.tip")); - putValue(MNEMONIC_KEY, (int) 'I'); - - } - - @Override - public void actionPerformed(ActionEvent e) { - - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - - ObserveSwingDataSource source; - if (ui.getConfig().isMainStorageOpened()) { - source = applicationContext.getDataSourcesManager().getMainDataSource(); - } else { - source = null; - } - - ObserveTextGenerator textGenerator = applicationContext.getTextGenerator(); - String text = textGenerator.getDataSourceInfo(source); - JOptionPane.showMessageDialog( - ui, - new JLabel(text), - t("observe.title.storage.info"), - JOptionPane.INFORMATION_MESSAGE); - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/StartH2WebServerAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/StartH2WebServerAction.java deleted file mode 100644 index 140a92a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/StartH2WebServerAction.java +++ /dev/null @@ -1,100 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.UIHelper; -import jaxx.runtime.SwingUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.h2.tools.Server; - -import javax.swing.AbstractAction; -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.13 - */ -public class StartH2WebServerAction extends AbstractAction { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(StartH2WebServerAction.class); - - private final ObserveMainUI ui; - - public StartH2WebServerAction(ObserveMainUI ui) { - - super(t("observe.action.start.h2.web.server"), SwingUtil.getUIManagerActionIcon("db-start-server")); - this.ui = ui; - putValue(SHORT_DESCRIPTION, t("observe.action.start.h2.web.server.tip")); - putValue(MNEMONIC_KEY, (int) 'S'); - - } - - @Override - public void actionPerformed(ActionEvent event) { - - if (ui.isH2WebServer()) { - - if (log.isWarnEnabled()) { - log.warn("Can not start h2 web server... (web server already found)"); - } - - } else { - - if (log.isInfoEnabled()) { - log.info("Will start h2 web server ..."); - } - - try { - - Server server = Server.createWebServer("-webAllowOthers"); - server.start(); - - Server.openBrowser(server.getURL()); - - // On mémorise l'instance du server dans le contexte applicatif afin de pouvoir la récupérer plus tard, - // par exemple lorsque l'on souhaitera arrêter le server. - ObserveSwingApplicationContext.get().setH2WebServer(server); - - ui.setH2WebServer(true); - - } catch (Exception e) { - - UIHelper.handlingError("Could not start h2 web server ", e); - } - - } - - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/StartServerModeAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/StartServerModeAction.java deleted file mode 100644 index 5ee4398..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/StartServerModeAction.java +++ /dev/null @@ -1,127 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.ObserveMainUIHandler; -import fr.ird.observe.ui.ObserveUIMode; -import jaxx.runtime.SwingUtil; -import jaxx.runtime.swing.ErrorDialogUI; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.h2.tools.Server; - -import javax.swing.AbstractAction; -import java.awt.event.ActionEvent; -import java.io.File; -import java.sql.SQLException; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.13 - */ -public class StartServerModeAction extends AbstractAction { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(StartServerModeAction.class); - - private final ObserveMainUI ui; - - public StartServerModeAction(ObserveMainUI ui) { - - super(t("observe.action.start.server.mode"), SwingUtil.getUIManagerActionIcon("db-start-server")); - this.ui = ui; - putValue(SHORT_DESCRIPTION, t("observe.action.start.server.mode.tip")); - putValue(MNEMONIC_KEY, (int) 'S'); - - } - - @Override - public void actionPerformed(ActionEvent e) { - - run(); - - } - - public void run() { - - if (log.isInfoEnabled()) { - log.info("Will start server mode..."); - } - ObserveSwingApplicationConfig config = ui.getConfig(); - File dbDirectory = new File(config.getLocalDBDirectory(), "obstuna"); - String h2Login = config.getH2Login(); - String h2Password = new String(config.getH2Password()); - Integer port = config.getH2ServerPort(); - - ui.setMode(ObserveUIMode.SERVER); - - try { - - Server server = Server.createTcpServer("-tcp", - "-tcpAllowOthers", - "-ifExists", - "-baseDir", dbDirectory.getAbsolutePath(), - "-tcpDaemon", - "-tcpPort", - String.valueOf(port)); - - String url = String.format(ObserveMainUIHandler.H2_SERVER_URL_PATTERN, - server.getURL(), - dbDirectory.getAbsolutePath()); - - server.start(); - if (log.isInfoEnabled()) { - log.info("server starts at " + url); - } - - String text = t("observe.message.server.info", dbDirectory); - ui.getServerModeInfo().setText(text); - - ui.getServerModeURL().setText(url); - ui.getServerModeLogin().setText(h2Login); - ui.getServerModePassword().setText(h2Password); - - // On mémorise l'instance du server dans le contexte applicatif afin de pouvoir la récupérer plus tard, - // par exemple lorsque l'on souhaitera arrêter le server. - ObserveSwingApplicationContext.get().setH2Server(server); - - } catch (SQLException e) { - - if (log.isErrorEnabled()) { - log.error("Could not start h2 server ", e); - } - ErrorDialogUI.showError(e); - } - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/StopH2WebServerAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/StopH2WebServerAction.java deleted file mode 100644 index 6e19bf8..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/StopH2WebServerAction.java +++ /dev/null @@ -1,82 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.ui.ObserveMainUI; -import jaxx.runtime.SwingUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.h2.tools.Server; - -import javax.swing.AbstractAction; -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.13 - */ -public class StopH2WebServerAction extends AbstractAction { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(StopH2WebServerAction.class); - - private final ObserveMainUI ui; - - public StopH2WebServerAction(ObserveMainUI ui) { - - super(t("observe.action.stop.h2.web.server"), SwingUtil.getUIManagerActionIcon("db-stop-server")); - this.ui = ui; - putValue(SHORT_DESCRIPTION, t("observe.action.stop.h2.web.server.tip")); - putValue(MNEMONIC_KEY, (int) 'S'); - - } - - @Override - public void actionPerformed(ActionEvent e) { - - if (ui.isH2WebServer()) { - if (log.isInfoEnabled()) { - log.info("Will stop web server mode..."); - } - - Server server = ObserveSwingApplicationContext.get().getH2WebServer(); - if (server != null) { - server.stop(); - } - ui.setH2WebServer(false); - } else { - if (log.isWarnEnabled()) { - log.warn("Can not stop h2 web server... (no web server found)"); - } - } - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/StopServerModeAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/StopServerModeAction.java deleted file mode 100644 index 9ed7c8d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/StopServerModeAction.java +++ /dev/null @@ -1,105 +0,0 @@ -package fr.ird.observe.ui.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.ObserveUIMode; -import jaxx.runtime.SwingUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.h2.tools.Server; - -import javax.swing.AbstractAction; -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 1/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.13 - */ -public class StopServerModeAction extends AbstractAction { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(StopServerModeAction.class); - - private final ObserveMainUI ui; - - public StopServerModeAction(ObserveMainUI ui) { - - super(t("observe.action.stop.server.mode"), SwingUtil.getUIManagerActionIcon("db-stop-server")); - this.ui = ui; - putValue(SHORT_DESCRIPTION, t("observe.action.stop.server.mode.tip")); - putValue(MNEMONIC_KEY, (int) 'S'); - - } - - @Override - public void actionPerformed(ActionEvent e) { - - if (log.isInfoEnabled()) { - log.info("Will stop server mode..."); - } - - Server server = ObserveSwingApplicationContext.get().getH2Server(); - - if (server != null) { - server.stop(); - } - ui.setMode(ObserveUIMode.NO_DB); - - if (ui.isH2WebServer()) { - - // stop also the h2 web server - launchStopH2WebServer(ui); - } - - } - - public void launchStopH2WebServer(ObserveMainUI ui) { - - if (ui.isH2WebServer()) { - if (log.isInfoEnabled()) { - log.info("Will stop web server mode..."); - } - - Server server = ObserveSwingApplicationContext.get().getH2WebServer(); - if (server != null) { - server.stop(); - } - ui.setH2WebServer(false); - } else { - if (log.isWarnEnabled()) { - log.warn("Can not stop h2 web server... (no web server found)"); - } - } - - } - - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/AbstractUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/AbstractUIAction.java deleted file mode 100644 index 4f4fde1..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/AbstractUIAction.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.actions.shared; - -import fr.ird.observe.db.DataContext; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.content.ObserveContentUI; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import jaxx.runtime.SwingUtil; - -import javax.swing.AbstractAction; -import javax.swing.AbstractButton; -import javax.swing.Icon; -import javax.swing.JTree; -import javax.swing.tree.TreePath; - -import static org.nuiton.i18n.I18n.t; - -/** - * Pour implanter les actions communes. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public abstract class AbstractUIAction extends AbstractAction { - - private static final long serialVersionUID = 1L; - - private final ObserveMainUI mainUI; - - private final String actionId; - - public AbstractUIAction(ObserveMainUI mainUI, - String actionId, - String label, - String shortDescription, - String actionIcon) { - super(t(label), SwingUtil.getUIManagerActionIcon(actionIcon)); - this.actionId = actionId; - this.mainUI = mainUI; - putValue(SHORT_DESCRIPTION, t(shortDescription)); - } - - public ObserveMainUI getMainUI() { - return mainUI; - } - - public String getActionId() { - return actionId; - } - - public void initAction(ObserveContentUI<?> ui, AbstractButton editor) { - editor.setAction(this); - editor.putClientProperty("mainUI", mainUI); - } - - public void updateAction(ObserveContentUI<?> ui, AbstractButton editor) { - editor.putClientProperty("ui", ui); - String tip = (String) editor.getClientProperty("toolTipText"); - if (tip != null) { - editor.setToolTipText(tip); - } - String text = (String) editor.getClientProperty("text"); - if (text != null) { - editor.setText(text); - } - String actionIcon = (String) editor.getClientProperty("actionIcon"); - if (actionIcon != null) { - Icon icon = SwingUtil.getUIManagerActionIcon(actionIcon); - editor.setIcon(icon); - } - } - - public static boolean isOpenActivityNodeCollapsed(JTree tree, - ObserveTreeHelper treeHelper, - DataContext dataContext) { - - // on regarde si le noeud de l'activity ouverte est collapsé - - ObserveNode node = treeHelper.getSelectedNode(); - - TreePath path = tree.getSelectionPath(); - - String id = dataContext.getOpenActivityId(); - - ObserveNode node1 = treeHelper.findNode(node, id); - - TreePath activityPath = path.pathByAddingChild(node1); - - boolean wasCollapsed = tree.isCollapsed(activityPath); - return wasCollapsed; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/CancelCreateUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/CancelCreateUIAction.java deleted file mode 100644 index 79b6d18..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/CancelCreateUIAction.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.actions.shared; - -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.content.ContentUI; -import fr.ird.observe.ui.tree.ObserveNode; - -import javax.swing.JComponent; -import javax.swing.SwingUtilities; -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.n; - -/** - * Action pour sélectionner un noeud (attaché à l'éditeur) dans l'arbre de - * navigation. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class CancelCreateUIAction extends AbstractUIAction { - - private static final long serialVersionUID = 1L; - - public static final String ACTION_NAME = "cancelCreate"; - - public CancelCreateUIAction(ObserveMainUI mainUI) { - super(mainUI, - ACTION_NAME, - n("observe.action.cancel"), - n("observe.action.cancel.create.tip"), - "cancel" - ); - } - - @Override - public void actionPerformed(final ActionEvent e) { - SwingUtilities.invokeLater(() -> { - JComponent c = (JComponent) e.getSource(); - ContentUI<?> ui = (ContentUI<?>) - c.getClientProperty("ui"); - if (ui == null) { - throw new IllegalStateException( - "could not find client property " + - "ui on component" + c); - } - ui.stopEdit(); - ObserveNode parentNode = ui.getTreeHelper().removeNode(ui.getTreeHelper().getSelectedNode()); - ui.getTreeHelper().selectNode(parentNode); - }); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/CloseAndCreateUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/CloseAndCreateUIAction.java deleted file mode 100644 index 4e9bd7b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/CloseAndCreateUIAction.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.actions.shared; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.longline.ActivityLonglineDto; -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.content.ContentUI; -import fr.ird.observe.ui.content.list.impl.longline.ActivityLonglinesUI; -import fr.ird.observe.ui.content.list.impl.seine.ActivitySeinesUI; -import fr.ird.observe.ui.content.open.ContentOpenableUI; -import fr.ird.observe.ui.content.open.impl.longline.ActivityLonglineUI; -import fr.ird.observe.ui.content.open.impl.seine.ActivitySeineUI; -import fr.ird.observe.ui.tree.ObserveTreeHelper; - -import javax.swing.JComponent; -import javax.swing.JTree; -import javax.swing.SwingUtilities; -import javax.swing.tree.TreePath; -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.n; - -/** - * Action pour fermer l'objet sous-jacent à l'écran et en créer un nouveau. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.5 - */ -public class CloseAndCreateUIAction extends AbstractUIAction { - - private static final long serialVersionUID = 1L; - - public static final String ACTION_NAME = "closeAndCreate"; - - public CloseAndCreateUIAction(ObserveMainUI mainUI) { - super(mainUI, - ACTION_NAME, - n("observe.content.action.closeAndCreate"), - n("observe.content.action.closeAndCreate.tip"), - "add" - ); - } - - @Override - public void actionPerformed(final ActionEvent e) { - - SwingUtilities.invokeLater(() -> { - JComponent c = (JComponent) e.getSource(); - ContentUI<?> ui = (ContentUI<?>) - c.getClientProperty("ui"); - if (ui == null) { - throw new IllegalStateException( - "could not find client property " + - "ui on component" + c); - } - if (ui instanceof ContentOpenableUI) { - ((ContentOpenableUI<?>) ui).closeAndCreateData(); - return; - } - - if (ui instanceof ActivitySeinesUI) { - - // cas particulier pour l'écran des activitys - - JTree tree = getMainUI().getNavigation(); - ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); - - boolean wasCollapsed = isOpenActivityNodeCollapsed( - tree, - treeHelper, - getMainUI().getDataContext() - ); - - // selection du noeud de l'activity ouverte - treeHelper.selectOpenNode(ActivitySeineDto.class); - - // on conserve le path de l'activity - TreePath path = tree.getSelectionPath(); - - // recuperation de l'écran associé - ActivitySeineUI selectedUI = (ActivitySeineUI) - ObserveSwingApplicationContext.get().getContentUIManager().getSelectedContentUI(); - - // fermeture de l'activity et création d'une nouvelle - selectedUI.closeAndCreateData(); - - if (wasCollapsed) { - - // on ferme le noeud de l'activity (qui a ete ouvert - // lors de la selection de celle-ci) - tree.collapsePath(path); - } - - return; - } - - if (ui instanceof ActivityLonglinesUI) { - - // cas particulier pour l'écran des activitys - - JTree tree = getMainUI().getNavigation(); - ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); - - boolean wasCollapsed = isOpenActivityNodeCollapsed( - tree, - treeHelper, - getMainUI().getDataContext() - ); - - // selection du noeud de l'activity ouverte - treeHelper.selectOpenNode(ActivityLonglineDto.class); - - // on conserve le path de l'activity - TreePath path = tree.getSelectionPath(); - - // recuperation de l'écran associé - ActivityLonglineUI selectedUI = (ActivityLonglineUI) - ObserveSwingApplicationContext.get().getContentUIManager().getSelectedContentUI(); - - // fermeture de l'activity et création d'une nouvelle - selectedUI.closeAndCreateData(); - - if (wasCollapsed) { - - // on ferme le noeud de l'activity (qui a ete ouvert - // lors de la selection de celle-ci) - tree.collapsePath(path); - } - - return; - } - - throw new IllegalStateException("Can not come here!"); - }); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/CloseOpenUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/CloseOpenUIAction.java deleted file mode 100644 index 65779c5..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/CloseOpenUIAction.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.actions.shared; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.longline.ActivityLonglineDto; -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.content.ContentUI; -import fr.ird.observe.ui.content.list.impl.longline.ActivityLonglinesUI; -import fr.ird.observe.ui.content.list.impl.seine.ActivitySeinesUI; -import fr.ird.observe.ui.content.open.ContentOpenableUI; -import fr.ird.observe.ui.content.open.impl.longline.ActivityLonglineUI; -import fr.ird.observe.ui.content.open.impl.seine.ActivitySeineUI; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; - -import javax.swing.JComponent; -import javax.swing.JTree; -import javax.swing.SwingUtilities; -import javax.swing.tree.TreePath; -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.n; - -/** - * Action pour fermer l'objet sous-jacent à l'écran. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class CloseOpenUIAction extends AbstractUIAction { - - private static final long serialVersionUID = 1L; - - public static final String ACTION_NAME = "closeOpen"; - - public CloseOpenUIAction(ObserveMainUI mainUI) { - super(mainUI, - ACTION_NAME, - n("observe.action.close.open"), - n("observe.action.close.open.tip"), - "close" - ); - } - - @Override - public void actionPerformed(final ActionEvent e) { - - SwingUtilities.invokeLater(() -> { - JComponent c = (JComponent) e.getSource(); - ContentUI<?> ui = (ContentUI<?>) - c.getClientProperty("ui"); - if (ui == null) { - throw new IllegalStateException( - "could not find client property " + - "ui on component" + c); - } - - if (ui instanceof ContentOpenableUI) { - ((ContentOpenableUI<?>) ui).closeData(); - return; - } - - if (ui instanceof ActivitySeinesUI) { - - // cas particulier pour l'écran des activités - - JTree tree = getMainUI().getNavigation(); - ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); - - // recuperation du noeud courant (activitys) - ObserveNode node = treeHelper.getSelectedNode(); - - boolean wasCollapsed = isOpenActivityNodeCollapsed( - tree, - treeHelper, - getMainUI().getDataContext() - ); - - // selection du noeud de l'activity ouverte - treeHelper.selectOpenNode(ActivitySeineDto.class); - - // on conserve le path de l'activity - TreePath path = tree.getSelectionPath(); - - // recuperation de l'écran associé - ActivitySeineUI selectedUI = (ActivitySeineUI) - ObserveSwingApplicationContext.get().getContentUIManager().getSelectedContentUI(); - - // fermeture de l'activity - selectedUI.closeData(); - - if (wasCollapsed) { - - // on ferme le noeud de l'activity (qui a ete ouvert - // lors de la selection de celle-ci) - tree.collapsePath(path); - } - - // retour sur le noeud des activitys - treeHelper.selectNode(node); - - return; - } - - if (ui instanceof ActivityLonglinesUI) { - - // cas particulier pour l'écran des activités - - JTree tree = getMainUI().getNavigation(); - ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); - - // recuperation du noeud courant (activitys) - ObserveNode node = treeHelper.getSelectedNode(); - - boolean wasCollapsed = isOpenActivityNodeCollapsed( - tree, - treeHelper, - getMainUI().getDataContext() - ); - - // selection du noeud de l'activity ouverte - treeHelper.selectOpenNode(ActivityLonglineDto.class); - - // on conserve le path de l'activity - TreePath path = tree.getSelectionPath(); - - // recuperation de l'écran associé - ActivityLonglineUI selectedUI = (ActivityLonglineUI) - ObserveSwingApplicationContext.get().getContentUIManager().getSelectedContentUI(); - - // fermeture de l'activity - selectedUI.closeData(); - - if (wasCollapsed) { - - // on ferme le noeud de l'activity (qui a ete ouvert - // lors de la selection de celle-ci) - tree.collapsePath(path); - } - - // retour sur le noeud des activitys - treeHelper.selectNode(node); - - return; - } - - throw new IllegalStateException("Can not come here!"); - }); - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/DeleteDataUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/DeleteDataUIAction.java deleted file mode 100644 index 68188c7..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/DeleteDataUIAction.java +++ /dev/null @@ -1,80 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.actions.shared; - -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.content.ContentUI; - -import javax.swing.JComponent; -import javax.swing.SwingUtilities; -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.n; - -/** - * Action pour sélectionner un noeud (attaché à l'éditeur) dans l'arbre de - * navigation. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class DeleteDataUIAction extends AbstractUIAction { - - private static final long serialVersionUID = 1L; - - public static final String ACTION_NAME = "deleteData"; - - public DeleteDataUIAction(ObserveMainUI mainUI) { - super(mainUI, - ACTION_NAME, - n("observe.action.delete"), - n("observe.action.delete.tip"), - "delete" - ); - } - - @Override - public void actionPerformed(final ActionEvent e) { - - getMainUI().setBusy(true); - - SwingUtilities.invokeLater(() -> { - try { - - JComponent c = (JComponent) e.getSource(); - ContentUI<?> ui = (ContentUI<?>) - c.getClientProperty("ui"); - if (ui == null) { - throw new IllegalStateException( - "could not find client property " + - "ui on component" + c); - } - - - ui.delete(); - } finally { - getMainUI().setBusy(false); - } - - }); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/DeleteReferenceUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/DeleteReferenceUIAction.java deleted file mode 100644 index 744da68..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/DeleteReferenceUIAction.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.actions.shared; - -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.content.ContentUI; - -import javax.swing.JComponent; -import javax.swing.SwingUtilities; -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.n; - -/** - * Action pour sélectionner un noeud (attaché à l'éditeur) dans l'arbre de - * navigation. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class DeleteReferenceUIAction extends AbstractUIAction { - - private static final long serialVersionUID = 1L; - - public static final String ACTION_NAME = "deleteReferentiel"; - - public DeleteReferenceUIAction(ObserveMainUI mainUI) { - super(mainUI, - ACTION_NAME, - n("observe.action.delete"), - n("observe.action.delete.tip"), - "delete" - ); - } - - @Override - public void actionPerformed(final ActionEvent e) { - SwingUtilities.invokeLater(() -> { - try { - JComponent c = (JComponent) e.getSource(); - - ContentUI<?> ui = (ContentUI<?>) - c.getClientProperty("ui"); - if (ui == null) { - throw new IllegalStateException( - "could not find client property " + - "ui on component" + c); - } - ui.delete(); - } finally { - getMainUI().setBusy(false); - } - }); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/GoDownUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/GoDownUIAction.java deleted file mode 100644 index 24a0124..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/GoDownUIAction.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.actions.shared; - -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.content.ObserveContentUI; -import fr.ird.observe.ui.tree.AbstractObserveTreeCellRenderer; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; - -import javax.swing.AbstractButton; -import javax.swing.Action; -import javax.swing.Icon; -import javax.swing.JComponent; -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; -import javax.swing.SwingUtilities; -import java.awt.Color; -import java.awt.event.ActionEvent; -import java.util.Enumeration; - -import static org.nuiton.i18n.I18n.n; - -/** - * Action pour sélectionner un noeud (attaché à l'éditeur) dans l'arbre de - * navigation. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class GoDownUIAction extends AbstractUIAction { - - private static final long serialVersionUID = 1L; - - public static final String ACTION_NAME = "goDown"; - - public GoDownUIAction(ObserveMainUI mainUI) { - super(mainUI, - ACTION_NAME, - n("observe.action.goDown"), - n("observe.action.goDown.tip"), - "go-down" - ); - } - - @Override - public void actionPerformed(final ActionEvent e) { - - SwingUtilities.invokeLater(() -> { - JComponent c = (JComponent) e.getSource(); - JPopupMenu p = (JPopupMenu) - c.getClientProperty("popup"); - if (p == null) { - throw new IllegalStateException( - "could not find client property " + - "popup on component" + c); - } - p.show(c, 2, c.getHeight()); - }); - } - - @Override - public void initAction(ObserveContentUI<?> ui, AbstractButton editor) { - super.initAction(ui, editor); - editor.putClientProperty("popup", getMainUI().getScopeDownPopup()); - } - - @Override - public void updateAction(ObserveContentUI<?> ui, AbstractButton editor) { - ObserveMainUI mainUI = getMainUI(); - - ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); - - AbstractObserveTreeCellRenderer render = treeHelper.getTreeCellRenderer(); - - ObserveNode node; - - super.updateAction(ui, editor); - - JPopupMenu scopePopup = mainUI.getScopeDownPopup(); - Action action = - mainUI.getRootPane().getActionMap().get(SelectNodeUIAction.ACTION_NAME); - node = treeHelper.getSelectedNode(); - ObserveNode nodeOriginal = node; - scopePopup.removeAll(); - Enumeration<?> e = node.children(); - while (e.hasMoreElements()) { - node = (ObserveNode) e.nextElement(); - String text = render.getNodeText(node); - if (text == null) { - continue; - } - Color color = - render.getNavigationTextColor(node); - Icon icon = render.getNavigationIcon(node, "-16"); - JMenuItem mi = new JMenuItem(); - mi.setAction(action); - mi.setText(text.trim()); - mi.setIcon(icon); - mi.setForeground(color); - mi.putClientProperty("node", node); - mi.putClientProperty("ui", ui); - mi.setAction(action); - scopePopup.add(mi); - } - - if (nodeOriginal.getChildCount() == 1 && - !nodeOriginal.getChildAt(0).isLeaf()) { - e = nodeOriginal.getChildAt(0).children(); - while (e.hasMoreElements()) { - node = (ObserveNode) e.nextElement(); - Color color = render.getNavigationTextColor( - node); - Icon icon = render.getNavigationIcon(node, "-16"); - String text = render.getNodeText(node); - JMenuItem mi = new JMenuItem(); - mi.setAction(action); - mi.setText(text.trim()); - mi.setIcon(icon); - mi.setForeground(color); - mi.putClientProperty("node", node); - mi.putClientProperty("ui", ui); - mi.setAction(action); - scopePopup.add(mi); - } - } - - int nbNodes = scopePopup.getComponentCount(); - - editor.setEnabled(nbNodes > 0); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/GoUpUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/GoUpUIAction.java deleted file mode 100644 index 880fde6..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/GoUpUIAction.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.actions.shared; - -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.content.ObserveContentUI; -import fr.ird.observe.ui.tree.AbstractObserveTreeCellRenderer; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; - -import javax.swing.AbstractButton; -import javax.swing.Action; -import javax.swing.Icon; -import javax.swing.JComponent; -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; -import javax.swing.SwingUtilities; -import javax.swing.tree.TreeNode; -import java.awt.Color; -import java.awt.GridLayout; -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.n; - -/** - * Action pour sélectionner un noeud (attaché à l'éditeur) dans l'arbre de - * navigation. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class GoUpUIAction extends AbstractUIAction { - - private static final long serialVersionUID = 1L; - - public static final String ACTION_NAME = "goUp"; - - public GoUpUIAction(ObserveMainUI mainUI) { - super(mainUI, - ACTION_NAME, - n("observe.action.goUp"), - n("observe.action.goUp.tip"), - "go-up" - ); - } - - @Override - public void actionPerformed(final ActionEvent e) { - - SwingUtilities.invokeLater(() -> { - JComponent c = (JComponent) e.getSource(); - JPopupMenu p = (JPopupMenu) c.getClientProperty("popup"); - if (p == null) { - throw new IllegalStateException( - "could not find client property " + - "popup on component" + c); - } - p.show(c, 2, c.getHeight()); - }); - } - - @Override - public void initAction(ObserveContentUI<?> ui, AbstractButton editor) { - super.initAction(ui, editor); - editor.putClientProperty("popup", getMainUI().getScopeUpPopup()); - } - - @Override - public void updateAction(ObserveContentUI<?> ui, AbstractButton editor) { - super.updateAction(ui, editor); - - ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); - - AbstractObserveTreeCellRenderer render = treeHelper.getTreeCellRenderer(); - - ObserveNode node; - - JPopupMenu scopePopup = getMainUI().getScopeUpPopup(); - - Action action = - getMainUI().getRootPane().getActionMap().get(SelectNodeUIAction.ACTION_NAME); - - node = treeHelper.getSelectedNode(); - TreeNode root = node.getRoot(); - scopePopup.removeAll(); - scopePopup.setLayout(new GridLayout(0, 1)); - while (!root.equals(node.getParent())) { - node = node.getParent(); - Color color = - render.getNavigationTextColor(node); - Icon icon = render.getNavigationIcon(node, "-16"); - String text = render.getNodeText(node); - JMenuItem mi = new JMenuItem(); - mi.setAction(action); - mi.setText(text.trim()); - mi.setIcon(icon); - mi.setForeground(color); - mi.setBackground(Color.WHITE); - mi.putClientProperty("node", node); - mi.putClientProperty("ui", ui); - mi.setAction(action); - scopePopup.add(mi); - } - scopePopup.revalidate(); - - int nbNodes = scopePopup.getComponentCount(); - - editor.setEnabled(nbNodes > 0); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/MoveActivityLonglinesUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/MoveActivityLonglinesUIAction.java deleted file mode 100644 index c3b6f34..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/MoveActivityLonglinesUIAction.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.actions.shared; - -import fr.ird.observe.ObserveOpenDataManager; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.application.swing.decoration.decorators.DataReferenceDecorator; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.longline.ActivityLonglineDto; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.service.longline.ActivityLonglineService; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.content.ContentUI; -import fr.ird.observe.ui.content.list.impl.longline.ActivityLonglinesUI; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.ui.tree.TripLonglineNode; -import fr.ird.observe.ui.util.DecoratedNodeEntity; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.SwingUtilities; -import java.awt.event.ActionEvent; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Action pour changer le programme d'une ou plusieurs marée dans la liste. - * - * @author Kevin Morin (Code Lutin) - * @since 5.0 - */ -public class MoveActivityLonglinesUIAction extends AbstractUIAction { - - private static final long serialVersionUID = 1L; - - /** - * Logger. - */ - private static final Log log = LogFactory.getLog(MoveActivityLonglinesUIAction.class); - - public static final String ACTION_NAME = "moveActivityLonglines"; - - public MoveActivityLonglinesUIAction(ObserveMainUI mainUI) { - super(mainUI, - ACTION_NAME, - n("observe.content.action.move.activities.longline"), - n("observe.content.action.move.activities.longline.tip"), - "move-activities" - ); - } - - @Override - public void actionPerformed(final ActionEvent e) { - - SwingUtilities.invokeLater(() -> { - JComponent c = (JComponent) e.getSource(); - ContentUI<?> ui = (ContentUI<?>) - c.getClientProperty("ui"); - if (ui == null) { - throw new IllegalStateException( - "could not find client property " + - "ui on component" + c); - } - - if (!(ui instanceof ActivityLonglinesUI)) { - throw new IllegalStateException("Can not come here!"); - } - ActivityLonglinesUI activityLonglinesUI = (ActivityLonglinesUI) ui; - - - // get current triplongline id - ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); - ObserveNode oldActivitiesNode = treeHelper.getSelectedNode(); - ObserveNode oldTripLonglineNode = oldActivitiesNode.getParent(); - - // choose the new tripLongline - String tripLonglineId = chooseNewTripLongline(ui, oldTripLonglineNode); - - if (tripLonglineId != null) { - - if (log.isInfoEnabled()) { - log.info("Will move activities to trip: " + tripLonglineId); - } - // change the tripLongline of the selected activities - List<DataReference<ActivityLonglineDto>> selectedDatas = activityLonglinesUI.getModel().getSelectedDatas(); - List<String> activityIds = selectedDatas.stream() - .map(DataReference.ID_FUNCTION) - .collect(Collectors.toList()); - ActivityLonglineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivityLonglineService(); -// List<Integer> positions = - service.moveActivityLonglinesToTripLongline(activityIds, tripLonglineId); - - // update the tree - updateTree(oldActivitiesNode, tripLonglineId, activityIds); - } - - }); - - } - - protected String chooseNewTripLongline(ContentUI<?> ui, ObserveNode oldTripLonglineNode) { - ObserveNode programNode = oldTripLonglineNode.getParent(); - String oldTripLonglineId = oldTripLonglineNode.getId(); - int tripLonglineNb = programNode.getChildCount(); - - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - DataReferenceDecorator<TripLonglineDto> decorator = applicationContext.getDecoratorService().getDataReferenceDecorator(TripLonglineDto.class); - - //on crée un tableau avec une marée en moins car on ne propose pas la marée actuelle - DecoratedNodeEntity[] decoratedTripLonglines = new DecoratedNodeEntity[tripLonglineNb - 1]; - - int j = 0; - for (int i = 0; i < tripLonglineNb; i++) { - - TripLonglineNode tripLonglineNode = (TripLonglineNode) programNode.getChildAt(i); - - String tripLonglineId = tripLonglineNode.getId(); - - if (!oldTripLonglineId.equals(tripLonglineId)) { - decoratedTripLonglines[j++] = DecoratedNodeEntity.newDecoratedNodeEntity(tripLonglineNode, decorator); - } - } - - Object decoratedTripLongline = JOptionPane.showInputDialog(ui, - t("observe.action.choose.tripLongline.message"), - t("observe.action.choose.tripLongline.title"), - JOptionPane.QUESTION_MESSAGE, - null, - decoratedTripLonglines, - null); - return decoratedTripLongline != null ? ((DecoratedNodeEntity) decoratedTripLongline).getId() : null; - } - - protected void updateTree(ObserveNode oldActivitiesNode, - String tripLonglineId, - List<String> activityIds) { - - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ObserveOpenDataManager openDataManager = applicationContext.getOpenDataManager(); - ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); - - ObserveNode oldTripLonglineNode = oldActivitiesNode.getParent(); - ObserveNode programNode = oldTripLonglineNode.getParent(); - ObserveNode newTripLonglineNode = treeHelper.getChild(programNode, tripLonglineId); - String activitiesNodeId = DecoratorService.getPropertyLabel(ObserveTreeHelper.TREE_NODE_PREFIX, - TripLonglineDto.PROPERTY_ACTIVITY_LONGLINE); - ObserveNode newActivitiesNode = treeHelper.getChild(newTripLonglineNode, activitiesNodeId); - - // Let's check if we're moving an open activity - Optional<String> openActivity = activityIds - .stream() - .filter(openDataManager::isOpenActivityLongline) - .findFirst(); - - // If so, we close it to avoid ending up with an open activity into a closed trip. - if (openActivity.isPresent()) { - openDataManager.closeActivityLongline(openActivity.get()); - } - - // Let's reload the sub tree of each activities node. - // As the change have already be done in database, we just call the child loaders to regenerate the activities nodes sub trees - treeHelper.reloadNodeSubTree(oldActivitiesNode, true); - treeHelper.reloadNodeSubTree(newActivitiesNode, true); - - // Let's put the focus on the activities node which received the activities - treeHelper.selectNode(newActivitiesNode); - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/MoveActivitySeinesUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/MoveActivitySeinesUIAction.java deleted file mode 100644 index 6eebe06..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/MoveActivitySeinesUIAction.java +++ /dev/null @@ -1,192 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.actions.shared; - -import fr.ird.observe.ObserveOpenDataManager; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.application.swing.decoration.decorators.DataReferenceDecorator; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.services.service.seine.ActivitySeineService; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.content.ContentUI; -import fr.ird.observe.ui.content.list.impl.seine.ActivitySeinesUI; -import fr.ird.observe.ui.content.list.impl.seine.ActivitySeinesUIModel; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.ui.tree.RouteSeineNode; -import fr.ird.observe.ui.util.DecoratedNodeEntity; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.SwingUtilities; -import java.awt.event.ActionEvent; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Action pour changer le programme d'une ou plusieurs marée dans la liste. - * - * @author Kevin Morin (Code Lutin) - * @since 5.0 - */ -public class MoveActivitySeinesUIAction extends AbstractUIAction { - - private static final long serialVersionUID = 1L; - - /** - * Logger. - */ - private static final Log log = LogFactory.getLog(MoveActivitySeinesUIAction.class); - - public static final String ACTION_NAME = "moveActivitySeines"; - - public MoveActivitySeinesUIAction(ObserveMainUI mainUI) { - super(mainUI, - ACTION_NAME, - n("observe.content.action.move.activities.seine"), - n("observe.content.action.move.activities.seine.tip"), - "move-activities" - ); - } - - @Override - public void actionPerformed(final ActionEvent e) { - - SwingUtilities.invokeLater(() -> { - JComponent c = (JComponent) e.getSource(); - ContentUI<?> ui = (ContentUI<?>) - c.getClientProperty("ui"); - if (ui == null) { - throw new IllegalStateException( - "could not find client property " + - "ui on component" + c); - } - - if (!(ui instanceof ActivitySeinesUI)) { - throw new IllegalStateException("Can not come here!"); - } - - // get current route id - ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); - ObserveNode oldActivitiesNode = treeHelper.getSelectedNode(); - ObserveNode oldRouteNode = oldActivitiesNode.getParent(); - - // choose the new route - String routeId = chooseNewRoute(ui, oldRouteNode); - - if (routeId != null) { - // change the route of the selected activities - List<DataReference<ActivitySeineDto>> selectedDatas = ((ActivitySeinesUIModel) ui.getModel()).getSelectedDatas(); - List<String> activityIds = selectedDatas.stream() - .map(DataReference.ID_FUNCTION) - .collect(Collectors.toList()) ; - ActivitySeineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivitySeineService(); - List<Integer> positions = service.moveActivitySeinesToRoute(activityIds, routeId); - - // update the tree - updateTree(oldActivitiesNode, routeId, activityIds); - } - - }); - - } - - protected String chooseNewRoute(ContentUI<?> ui, ObserveNode oldRouteNode) { - ObserveNode routesNode = oldRouteNode.getParent(); - String oldRouteId = oldRouteNode.getId(); - int routeNb = routesNode.getChildCount(); - - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - DataReferenceDecorator<RouteDto> decorator = applicationContext.getDecoratorService().getDataReferenceDecorator(RouteDto.class); - - //on crée un tableau avec une route en moins car on ne propose pas la route actuel - DecoratedNodeEntity[] decoratedRoutes = new DecoratedNodeEntity[routeNb - 1]; - - int j = 0; - for (int i = 0; i < routeNb; i++) { - - RouteSeineNode routeNode = (RouteSeineNode) routesNode.getChildAt(i); - - String routeId = routeNode.getId(); - - if (!oldRouteId.equals(routeId)) { - decoratedRoutes[j++] = DecoratedNodeEntity.newDecoratedNodeEntity(routeNode, decorator); - } - } - - Object decoratedRoute = JOptionPane.showInputDialog(ui, - t("observe.action.choose.route.message"), - t("observe.action.choose.route.title"), - JOptionPane.QUESTION_MESSAGE, - null, - decoratedRoutes, - null); - - return decoratedRoute != null ? ((DecoratedNodeEntity) decoratedRoute).getId() : null; - } - - protected void updateTree(ObserveNode oldActivitiesNode, - String routeId, - List<String> activityIds) { - - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ObserveOpenDataManager openDataManager = applicationContext.getOpenDataManager(); - ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); - - ObserveNode oldRouteNode = oldActivitiesNode.getParent(); - ObserveNode routesNode = oldRouteNode.getParent(); - ObserveNode tripNode = routesNode.getParent(); - ObserveNode newRouteNode = treeHelper.getChild(routesNode, routeId); - String activitiesNodeId = DecoratorService.getPropertyLabel(ObserveTreeHelper.TREE_NODE_PREFIX, - RouteDto.PROPERTY_ACTIVITY_SEINE); - ObserveNode newActivitiesNode = treeHelper.getChild(newRouteNode, activitiesNodeId); - - // Let's check if we're moving an open activity - Optional<String> openActivity = activityIds - .stream() - .filter(openDataManager::isOpenActivitySeine) - .findFirst(); - - // If so, we close it to avoid ending up with an open activity into a closed route. - if (openActivity.isPresent()) { - openDataManager.closeActivitySeine(openActivity.get()); - } - - // Let's reload the sub tree of each activities node. - // As the change have already be done in database, we just call the child loaders to regenerate the activities nodes sub trees - treeHelper.reloadNodeSubTree(oldActivitiesNode, true); - treeHelper.reloadNodeSubTree(newActivitiesNode, true); - - // Let's put the focus on the activities node which received the activities - treeHelper.selectNode(newActivitiesNode); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/MoveRoutesUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/MoveRoutesUIAction.java deleted file mode 100644 index 3205fac..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/MoveRoutesUIAction.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.actions.shared; - -import fr.ird.observe.ObserveOpenDataManager; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.application.swing.decoration.decorators.DataReferenceDecorator; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.services.service.seine.RouteService; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.content.ContentUI; -import fr.ird.observe.ui.content.list.impl.seine.RoutesUI; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.ui.tree.TripSeineNode; -import fr.ird.observe.ui.util.DecoratedNodeEntity; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.SwingUtilities; -import java.awt.event.ActionEvent; -import java.util.List; -import java.util.Optional; -import java.util.stream.Collectors; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Action pour changer le programme d'une ou plusieurs marée dans la liste. - * - * @author Kevin Morin (Code Lutin) - * @since 5.0 - */ -public class MoveRoutesUIAction extends AbstractUIAction { - - private static final long serialVersionUID = 1L; - - /** - * Logger. - */ - private static final Log log = LogFactory.getLog(MoveRoutesUIAction.class); - - public static final String ACTION_NAME = "moveRoutes"; - - public MoveRoutesUIAction(ObserveMainUI mainUI) { - super(mainUI, - ACTION_NAME, - n("observe.content.action.move.routes"), - n("observe.content.action.move.routes.tip"), - "move-routes" - ); - } - - @Override - public void actionPerformed(final ActionEvent e) { - - SwingUtilities.invokeLater(() -> { - JComponent c = (JComponent) e.getSource(); - ContentUI<?> ui = (ContentUI<?>) - c.getClientProperty("ui"); - if (ui == null) { - throw new IllegalStateException( - "could not find client property " + - "ui on component" + c); - } - - if (!(ui instanceof RoutesUI)) { - throw new IllegalStateException("Can not come here!"); - } - - RoutesUI theUi = (RoutesUI) ui; - - // get current tripseine id - ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); - ObserveNode oldRoutesNode = treeHelper.getSelectedNode(); - ObserveNode oldTripSeineNode = oldRoutesNode.getParent(); - - // choose the new tripseine - String tripSeineId = chooseNewTripSeine(theUi, oldTripSeineNode); - - if (tripSeineId != null) { - // change the tripseine of the selected routes - List<DataReference<RouteDto>> selectedDatas = theUi.getModel().getSelectedDatas(); - List<String> routeIds = selectedDatas.stream().map(DataReference.ID_FUNCTION).collect(Collectors.toList()); - RouteService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newRouteService(); - List<Integer> positions = service.moveRoutesToTripSeine(routeIds, tripSeineId); - - // update the tree - updateTree(oldRoutesNode, tripSeineId, routeIds); - } - - }); - - } - - protected String chooseNewTripSeine(ContentUI<?> ui, ObserveNode oldTripSeineNode) { - ObserveNode programNode = oldTripSeineNode.getParent(); - String oldTripSeineId = oldTripSeineNode.getId(); - int tripSeineNb = programNode.getChildCount(); - - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - DataReferenceDecorator<TripSeineDto> decorator = applicationContext.getDecoratorService().getDataReferenceDecorator(TripSeineDto.class); - - //on crée un tableau avec une marée en moins car on ne propose pas la marée actuel - DecoratedNodeEntity[] decoratedTripSeines = new DecoratedNodeEntity[tripSeineNb - 1]; - - int j = 0; - for (int i = 0; i < tripSeineNb; i++) { - - TripSeineNode tripSeineNode = (TripSeineNode) programNode.getChildAt(i); - - String tripSeineId = tripSeineNode.getId(); - - if (!oldTripSeineId.equals(tripSeineId)) { - decoratedTripSeines[j++] = DecoratedNodeEntity.newDecoratedNodeEntity(tripSeineNode, decorator); - } - } - - Object decoratedTripSeine = JOptionPane.showInputDialog(ui, - t("observe.action.choose.tripSeine.message"), - t("observe.action.choose.tripSeine.title"), - JOptionPane.QUESTION_MESSAGE, - null, - decoratedTripSeines, - null); - return decoratedTripSeine != null ? ((DecoratedNodeEntity) decoratedTripSeine).getId() : null; - } - - protected void updateTree(ObserveNode oldRoutesNode, - String tripSeineId, - List<String> routeIds) { - - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ObserveOpenDataManager openDataManager = applicationContext.getOpenDataManager(); - ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); - - ObserveNode oldTripSeineNode = oldRoutesNode.getParent(); - ObserveNode programNode = oldTripSeineNode.getParent(); - ObserveNode newTripSeineNode = treeHelper.getChild(programNode, tripSeineId); - String routesNodeId = DecoratorService.getPropertyLabel(ObserveTreeHelper.TREE_NODE_PREFIX, - TripSeineDto.PROPERTY_ROUTE); - ObserveNode newRoutesNode = treeHelper.getChild(newTripSeineNode, routesNodeId); - - // Let's check if we're moving an open route - Optional<String> openRoute = routeIds - .stream() - .filter(openDataManager::isOpenRoute) - .findFirst(); - - // If so, we close it to avoid ending up with an open route into a closed trip. - if (openRoute.isPresent()) { - openDataManager.closeRoute(openRoute.get()); - } - - // Let's reload the sub tree of each routes node. - // As the change have already be done in database, we just call the child loaders to regenerate the routes nodes sub trees - treeHelper.reloadNodeSubTree(oldRoutesNode, true); - treeHelper.reloadNodeSubTree(newRoutesNode, true); - - // 1. Select the newRoutesNode : - // only a selected node can be reloaded (@see fr.ird.observe.ui.tree.ObserveTreeBridge.canLoadChild). - // (And also it's better for user experience because it puts the focus on the routes node which receive the routes) - // - // However, the node selection has to be done after that the trip has been opened : - // selecting the newRoutesNode opens a list layout which compute a rendering mode associated to the trip state. - // After the mode has been computed, it is injected in the list component which triggers listeners on associated components, such as buttons. - // - // That's why, if we do this before the trip is opened, - // we will end up with an incoherent list view (some buttons will be deactivated while they should be activated for instance) - treeHelper.selectNode(newRoutesNode); - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/MoveTripLonglinesUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/MoveTripLonglinesUIAction.java deleted file mode 100644 index 915decd..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/MoveTripLonglinesUIAction.java +++ /dev/null @@ -1,85 +0,0 @@ -package fr.ird.observe.ui.actions.shared; - -/*- - * #%L - * ObServe :: Application Swing - * %% - * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.constants.GearType; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.service.longline.TripLonglineService; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.content.ContentUI; -import fr.ird.observe.ui.content.list.impl.longline.TripLonglinesUI; -import fr.ird.observe.ui.content.list.impl.longline.TripLonglinesUIModel; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Kevin Morin (Code Lutin) - * @since 5.0 - */ -public class MoveTripLonglinesUIAction extends MoveTripsUIAction<TripLonglineDto> { - - private static final long serialVersionUID = 1L; - - /** - * Logger. - */ - private static final Log log = LogFactory.getLog(MoveTripLonglinesUIAction.class); - - public static final String ACTION_NAME = "moveTripLonglines"; - - public MoveTripLonglinesUIAction(ObserveMainUI mainUI) { - super(mainUI, ACTION_NAME); - } - - @Override - protected void checkUIClass(ContentUI<?> ui) throws IllegalStateException { - if (!(ui instanceof TripLonglinesUI)) { - throw new IllegalStateException("Can not come here!"); - } - } - - @Override - protected GearType getGearType(ContentUI<?> ui) { - return GearType.longline; - } - - @Override - protected List<Integer> getPositions(List<String> tripIds, String programId) { - TripLonglineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripLonglineService(); - return service.moveTripLonglinesToProgram(tripIds, programId); - } - - @Override - protected void updateModelData(ContentUI<?> ui) { - TripLonglinesUI tripLonglinesUI = (TripLonglinesUI) ui; - TripLonglinesUIModel model = tripLonglinesUI.getModel(); - List<DataReference<TripLonglineDto>> data = new ArrayList<>(model.getData()); - data.removeAll(model.getSelectedDatas()); - model.setData(data); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/MoveTripSeinesUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/MoveTripSeinesUIAction.java deleted file mode 100644 index e84e903..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/MoveTripSeinesUIAction.java +++ /dev/null @@ -1,85 +0,0 @@ -package fr.ird.observe.ui.actions.shared; - -/*- - * #%L - * ObServe :: Application Swing - * %% - * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.constants.GearType; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.services.service.seine.TripSeineService; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.content.ContentUI; -import fr.ird.observe.ui.content.list.impl.seine.TripSeinesUI; -import fr.ird.observe.ui.content.list.impl.seine.TripSeinesUIModel; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Kevin Morin (Code Lutin) - * @since 5.0 - */ -public class MoveTripSeinesUIAction extends MoveTripsUIAction<TripSeineDto> { - - private static final long serialVersionUID = 1L; - - /** - * Logger. - */ - private static final Log log = LogFactory.getLog(MoveTripSeinesUIAction.class); - - public static final String ACTION_NAME = "moveTripSeines"; - - public MoveTripSeinesUIAction(ObserveMainUI mainUI) { - super(mainUI, ACTION_NAME); - } - - @Override - protected void checkUIClass(ContentUI<?> ui) throws IllegalStateException { - if (!(ui instanceof TripSeinesUI)) { - throw new IllegalStateException("Can not come here!"); - } - } - - @Override - protected GearType getGearType(ContentUI<?> ui) { - return GearType.seine; - } - - @Override - protected List<Integer> getPositions(List<String> tripIds, String programId) { - TripSeineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripSeineService(); - return service.moveTripSeinesToProgram(tripIds, programId); - } - - @Override - protected void updateModelData(ContentUI<?> ui) { - TripSeinesUI tripSeinesUI = (TripSeinesUI) ui; - TripSeinesUIModel model = tripSeinesUI.getModel(); - List<DataReference<TripSeineDto>> data = new ArrayList<>(model.getData()); - data.removeAll(model.getSelectedDatas()); - model.setData(data); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/MoveTripsUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/MoveTripsUIAction.java deleted file mode 100644 index 739a0c5..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/MoveTripsUIAction.java +++ /dev/null @@ -1,197 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.actions.shared; - -import fr.ird.observe.ObserveOpenDataManager; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.DataDto; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.constants.GearType; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.content.ContentUI; -import fr.ird.observe.ui.content.list.ContentListUIModel; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.ui.tree.menu.MoveTripNodeMenuPopulator; -import fr.ird.observe.ui.util.DecoratedNodeEntity; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.SwingUtilities; -import java.awt.event.ActionEvent; -import java.util.ArrayList; -import java.util.List; -import java.util.stream.Collectors; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Action pour changer le programme d'une ou plusieurs marée dans la liste. - * - * @author Kevin Morin (Code Lutin) - * @since 5.0 - */ -public abstract class MoveTripsUIAction<T extends DataDto> extends AbstractUIAction { - - private static final long serialVersionUID = 1L; - - /** - * Logger. - */ - private static final Log log = LogFactory.getLog(MoveTripsUIAction.class); - - public static final String ACTION_NAME = "moveTrips"; - - public MoveTripsUIAction(ObserveMainUI mainUI, String actionName) { - super(mainUI, - actionName, - n("observe.content.action.move.trips"), - n("observe.content.action.move.trips.tip"), - "move-trips" - ); - } - - @Override - public void actionPerformed(final ActionEvent e) { - - SwingUtilities.invokeLater(() -> { - JComponent c = (JComponent) e.getSource(); - ContentUI<?> ui = (ContentUI<?>) - c.getClientProperty("ui"); - if (ui == null) { - throw new IllegalStateException( - "could not find client property " + - "ui on component" + c); - } - - checkUIClass(ui); - - // get current program id - ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); - ObserveNode oldProgramNode = treeHelper.getSelectedNode(); - String oldProgramId = oldProgramNode.getId(); - - // choose the new program - String programId = chooseNewProgram(ui, oldProgramId); - - if (programId != null) { - - // change the program of the selected trips - List<DataReference<T>> selectedDatas = ((ContentListUIModel) ui.getModel()).getSelectedDatas(); - List<String> tripIds = selectedDatas.stream().map(DataReference.ID_FUNCTION).collect(Collectors.toList()); - List<Integer> positions = getPositions(tripIds, programId); - - // update the tree - updateTree(ui, oldProgramNode, oldProgramId, programId, tripIds, positions); - } - - }); - - } - - protected String chooseNewProgram(ContentUI<?> ui, String oldProgramId) { - - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - - ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); - - GearType geartype = getGearType(ui); - - // racine - ObserveNode rootNode = treeHelper.getRootNode(); - - //on crée un tableau avec un programme en moins car on ne propose pas le programme actuel - List<DecoratedNodeEntity> decoratedProgramList = new ArrayList<>(); - - MoveTripNodeMenuPopulator.createPossibleParents(oldProgramId, decoratedProgramList, geartype, rootNode); - - DecoratedNodeEntity[] decoratedPrograms = - decoratedProgramList.toArray(new DecoratedNodeEntity[decoratedProgramList.size()]); - - DecoratedNodeEntity decoratedProgram = (DecoratedNodeEntity) JOptionPane.showInputDialog(ui, - t("observe.action.choose.program.message"), - t("observe.action.choose.program.title"), - JOptionPane.QUESTION_MESSAGE, - null, - decoratedPrograms, - null); - - return decoratedProgram == null ? null : decoratedProgram.getId(); - } - - protected void updateTree(ContentUI<?> ui, - ObserveNode oldProgramNode, - String oldProgramId, - String programId, - List<String> tripIds, - List<Integer> positions) { - - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ObserveOpenDataManager openDataManager = applicationContext.getOpenDataManager(); - ObserveTreeHelper treeHelper = getMainUI().getTreeHelper(); - - ObserveNode rootNode = treeHelper.getRootNode(); - ObserveNode newProgramNode = treeHelper.getChild(rootNode, programId); - - for (int i = 0, s = positions.size(); i < s; i++) { - - String tripId = tripIds.get(i); - ObserveNode tripNode = treeHelper.getChild(oldProgramNode, tripId); - boolean wasOpen = tripNode.isOpen(); - treeHelper.removeNode(tripNode); - - if (wasOpen) { - openDataManager.closeProgram(oldProgramId); - openDataManager.openProgram(programId); - } - - ObserveNode newTripNode = treeHelper.getChild(newProgramNode, tripId); - - if (newTripNode == null) { - - // create it - if (log.isInfoEnabled()) { - log.info("Insert trip node: "); - } - treeHelper.insertNode(newProgramNode, tripNode, positions.get(i)); - } - } - - updateModelData(ui); - - treeHelper.reloadNode(oldProgramNode, true); - treeHelper.reloadNode(newProgramNode, true); - treeHelper.selectNode(newProgramNode); - } - - protected abstract void checkUIClass(ContentUI<?> ui) throws IllegalStateException; - - protected abstract GearType getGearType(ContentUI<?> ui); - - protected abstract List<Integer> getPositions(List<String> tripIds, String programId); - - protected abstract void updateModelData(ContentUI<?> ui); - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/ReOpenUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/ReOpenUIAction.java deleted file mode 100644 index 01e12e1..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/ReOpenUIAction.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.actions.shared; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.content.ContentUI; -import fr.ird.observe.ui.content.list.ContentListUI; -import fr.ird.observe.ui.content.open.ContentOpenableUI; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; - -import javax.swing.JComponent; -import javax.swing.SwingUtilities; -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.n; - -/** - * Action pour sélectionner un noeud (attaché à l'éditeur) dans l'arbre de - * navigation. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ReOpenUIAction extends AbstractUIAction { - - private static final long serialVersionUID = 1L; - - public static final String ACTION_NAME = "reopen"; - - public ReOpenUIAction(ObserveMainUI mainUI) { - super(mainUI, - ACTION_NAME, - n("observe.content.action.reopen"), - n("observe.content.action.reopen.tip"), - "reopen" - ); - } - - @Override - public void actionPerformed(final ActionEvent e) { - SwingUtilities.invokeLater(() -> { - JComponent c = (JComponent) e.getSource(); - ContentUI<?> ui = (ContentUI<?>) - c.getClientProperty("ui"); - - if (ui == null) { - throw new IllegalStateException( - "could not find client property ui " + - "on component" + c); - } - - ContentOpenableUI<?> openUI; - - if (ui instanceof ContentOpenableUI<?>) { - - openUI = (ContentOpenableUI<?>) ui; - } else if (ui instanceof ContentListUI<?, ?>) { - - DataReference<?> selectedData = ((ContentListUI<?, ?>) ui).getSelectedData(); - - String id = selectedData.getId(); - - ObserveTreeHelper treeHelper = ui.getTreeHelper(); - ObserveNode selectedNode = treeHelper.getSelectedNode(); - ObserveNode node = treeHelper.findNode(selectedNode, id); - - treeHelper.selectNode(node); - - openUI = (ContentOpenableUI<?>) - ObserveSwingApplicationContext.get().getContentUIManager().getSelectedContentUI(); - - } else { - throw new IllegalStateException("The action " + ACTION_NAME + " can not be executed from ui " + ui); - } - - if (openUI != null) { - openUI.openData(); - } - }); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/ResetEditUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/ResetEditUIAction.java deleted file mode 100644 index a2ae98e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/ResetEditUIAction.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.actions.shared; - -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.content.ContentUI; - -import javax.swing.JComponent; -import javax.swing.SwingUtilities; -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.n; - -/** - * Action pour sélectionner un noeud (attaché à l'éditeur) dans l'arbre de - * navigation. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ResetEditUIAction extends AbstractUIAction { - - private static final long serialVersionUID = 1L; - - public static final String ACTION_NAME = "reset"; - - public ResetEditUIAction(ObserveMainUI mainUI) { - super(mainUI, - ACTION_NAME, - n("observe.content.action.reset"), - n("observe.content.action.reset.tip"), - "revert" - ); - } - - @Override - public void actionPerformed(final ActionEvent e) { - SwingUtilities.invokeLater(() -> { - JComponent c = (JComponent) e.getSource(); - ContentUI<?> ui = (ContentUI<?>) - c.getClientProperty("ui"); - if (ui == null) { - throw new IllegalStateException( - "could not find client property " + - "ui on component" + c); - } - ui.resetEdit(); - }); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/SaveEditUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/SaveEditUIAction.java deleted file mode 100644 index f103fb8..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/SaveEditUIAction.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.actions.shared; - -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.content.ContentUI; - -import javax.swing.JComponent; -import javax.swing.SwingUtilities; -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.n; - -/** - * Action pour sélectionner un noeud (attaché à l'éditeur) dans l'arbre de - * navigation. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class SaveEditUIAction extends AbstractUIAction { - - private static final long serialVersionUID = 1L; - - public static final String ACTION_NAME = "save"; - - public SaveEditUIAction(ObserveMainUI mainUI) { - super(mainUI, - ACTION_NAME, - n("observe.action.save"), - n("observe.action.save.tip"), - ACTION_NAME - ); - } - - @Override - public void actionPerformed(final ActionEvent e) { - SwingUtilities.invokeLater(() -> { - JComponent c = (JComponent) e.getSource(); - ContentUI<?> ui = (ContentUI<?>) - c.getClientProperty("ui"); - if (ui == null) { - throw new IllegalStateException( - "could not find client property " + - "ui on component" + c); - } - ui.save(true); - }); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/SelectNodeUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/SelectNodeUIAction.java deleted file mode 100644 index d41674d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/SelectNodeUIAction.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.actions.shared; - -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.tree.ObserveNode; - -import javax.swing.JComponent; -import java.awt.event.ActionEvent; - -import static org.nuiton.i18n.I18n.n; - -/** - * Action pour sélectionner un noeud (attaché à l'éditeur) dans l'arbre de - * navigation. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class SelectNodeUIAction extends AbstractUIAction { - - private static final long serialVersionUID = 1L; - - public static final String ACTION_NAME = "selectNode"; - - public static final String NODE = "node"; - - public SelectNodeUIAction(ObserveMainUI mainUI) { - super(mainUI, - ACTION_NAME, - n("observe.action.selectNode"), - n("observe.action.selectNode.tip"), - "go-jump" - ); - } - - @Override - public void actionPerformed(ActionEvent e) { - JComponent source = (JComponent) e.getSource(); - ObserveNode node = (ObserveNode) source.getClientProperty(NODE); - getMainUI().getTreeHelper().selectNode(node); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/SelectOpenNodeUIAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/SelectOpenNodeUIAction.java deleted file mode 100644 index 2b98f25..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/actions/shared/SelectOpenNodeUIAction.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.actions.shared; - -import fr.ird.observe.ui.ObserveMainUI; - -import javax.swing.JComponent; -import java.awt.event.ActionEvent; - -/** - * Action pour sélectionner un noeud (attaché à l'éditeur) dans l'arbre de - * navigation. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class SelectOpenNodeUIAction extends AbstractUIAction { - - public static final String ACTION_NAME = "selectOpen"; - - private static final long serialVersionUID = 1L; - - public SelectOpenNodeUIAction(ObserveMainUI mainUI) { - super(mainUI, ACTION_NAME, "<NONE>", "<NONE>", "go-down"); - } - - @Override - public void actionPerformed(ActionEvent e) { - - JComponent c = (JComponent) e.getSource(); - Class<?> type = (Class<?>) c.getClientProperty("type"); - if (type == null) { - throw new IllegalStateException( - "could not find client property " + - "type on component" + c); - } - getMainUI().getTreeHelper().selectOpenNode(type); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminActionModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminActionModel.java deleted file mode 100644 index 2730a14..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminActionModel.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin; - -import jaxx.runtime.swing.wizard.ext.WizardExtStepModel; - -/** - * Le modèle de base pour les actions. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public abstract class AdminActionModel extends WizardExtStepModel<AdminStep> { - - protected AdminActionModel(AdminStep objectOperation) { - super(objectOperation); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminActionWorker.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminActionWorker.java deleted file mode 100644 index 67b6af4..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminActionWorker.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin; - -import jaxx.runtime.swing.application.ActionWorker; -import jaxx.runtime.swing.wizard.ext.WizardState; - -import java.util.concurrent.Callable; - -/** - * Un worker pour les opération longues d'administration. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class AdminActionWorker extends ActionWorker<WizardState, String> { - - protected final AdminTabUIHandler handler; - - protected AdminActionWorker(AdminTabUIHandler handler, - String actionLabel) { - super(actionLabel); - this.handler = handler; - } - - public static AdminActionWorker newWorker( - AdminTabUIHandler handler, - String actionLabel, - Callable<WizardState> target) { - AdminActionWorker adminActionWorker = new AdminActionWorker(handler, actionLabel); - adminActionWorker.setTarget(target); - return adminActionWorker; - } - - public AdminTabUIHandler getHandler() { - return handler; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminStep.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminStep.java deleted file mode 100644 index d010960..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminStep.java +++ /dev/null @@ -1,451 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin; - -import fr.ird.observe.db.constants.DbMode; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.admin.config.ConfigUI; -import fr.ird.observe.ui.admin.config.SelectDataUI; -import fr.ird.observe.ui.admin.consolidate.ConsolidateModel; -import fr.ird.observe.ui.admin.consolidate.ConsolidateUI; -import fr.ird.observe.ui.admin.synchronize.data.DataSynchroModel; -import fr.ird.observe.ui.admin.synchronize.data.DataSynchroUI; -import fr.ird.observe.ui.admin.export.ExportModel; -import fr.ird.observe.ui.admin.export.ExportUI; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchroModel; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchroUI; -import fr.ird.observe.ui.admin.report.ReportModel; -import fr.ird.observe.ui.admin.report.ReportUI; -import fr.ird.observe.ui.admin.resume.ShowResumeUI; -import fr.ird.observe.ui.admin.save.SaveLocalModel; -import fr.ird.observe.ui.admin.save.SaveLocalUI; -import fr.ird.observe.ui.admin.synchronize.referential.legacy.SynchronizeModel; -import fr.ird.observe.ui.admin.synchronize.referential.legacy.SynchronizeUI; -import fr.ird.observe.ui.admin.validate.ValidateModel; -import fr.ird.observe.ui.admin.validate.ValidateUI; -import jaxx.runtime.swing.wizard.ext.WizardExtStep; -import jaxx.runtime.swing.wizard.ext.WizardExtUI; - -import javax.swing.ImageIcon; -import java.lang.reflect.Constructor; -import java.util.EnumSet; - -import static org.nuiton.i18n.I18n.n; - -/** - * Pour caractériser les étapes (correspond aux onglets de l'ui). - * - * Chaque constante représente un onglet de l'ui et est responsable de - * l'instanciation des différents objets associés à un onglet, à savoir : - * <ul> - * <li>le model {@link #newModel()}</li> - * <li>l'ui {@link #newUI(WizardExtUI)} </li> - * </ul> - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public enum AdminStep implements WizardExtStep { - - /** pour configurer les actions à réaliser et voir la progression */ - CONFIG( - n("observe.actions.config.step"), - n("observe.actions.config.step.description"), - null, - ConfigUI.class, - true - ), - - /** pour selectionner les donnes */ - SELECT_DATA( - n("observe.actions.selectData.step"), - n("observe.actions.selectData.step.description"), - null, - SelectDataUI.class, - true - ), - - /** pour résoudre les entités obosolètes */ - SYNCHRONIZE( - n("observe.actions.synchro.referential.legacy.step"), - n("observe.actions.synchro.referential.legacy.step.description"), - n("observe.actions.synchro.referential.legacy"), - n("observe.actions.synchro.referential.legacy.tip"), - "synchronizeReferentiel", - n("observe.actions.synchro.referential.legacy"), - n("observe.actions.synchro.referential.legacy.description"), - SynchronizeModel.class, - SynchronizeUI.class, - true, - false, - true, - false, - DbMode.USE_LOCAL, - DbMode.USE_REMOTE - ), - - DATA_SYNCHRONIZE( - n("observe.actions.synchro.data.step"), - n("observe.actions.synchro.data.step.description"), - n("observe.actions.synchro.data.title"), - n("observe.actions.synchro.data.title.tip"), - "dataSynchronize", - n("observe.actions.synchro.data"), - n("observe.actions.synchro.data.description"), - DataSynchroModel.class, - DataSynchroUI.class, - true, - false, - false, - false, - DbMode.USE_LOCAL, - DbMode.USE_REMOTE, - DbMode.USE_SERVER - ), - - REFERENTIAL_SYNCHRONIZE( - n("observe.actions.synchro.referential.step"), - n("observe.actions.synchro.referential.step.description"), - n("observe.actions.synchro.referential.title"), - n("observe.actions.synchro.referential.title.tip"), - "referentialSynchronize", - n("observe.actions.synchro.referential"), - n("observe.actions.synchro.referential.description"), - ReferentialSynchroModel.class, - ReferentialSynchroUI.class, - true, - false, - false, - false, - DbMode.USE_LOCAL, - DbMode.USE_REMOTE, - DbMode.USE_SERVER - ), - - /** pour lancer la validation des donnees */ - VALIDATE( - n("observe.actions.validate.step"), - n("observe.actions.validate.step.description"), - n("observe.actions.validate.title"), - n("observe.actions.validate.title.tip"), - "validate", - n("observe.actions.validate"), - n("observe.actions.validate.description"), - ValidateModel.class, - ValidateUI.class, - false, - true, - false, - false, - DbMode.USE_LOCAL, - DbMode.USE_REMOTE, - DbMode.USE_SERVER - ), - - /** pour lancer la consolidation des données (mesure taille-poids...) */ - CONSOLIDATE( - n("observe.actions.consolidate.step"), - n("observe.actions.consolidate.step.description"), - n("observe.actions.consolidate.title"), - n("observe.actions.consolidate.title.tip"), - "consolidate", - n("observe.actions.consolidate"), - n("observe.actions.consolidate.description"), - ConsolidateModel.class, - ConsolidateUI.class, - false, - true, - false, - false, - DbMode.USE_LOCAL, - DbMode.USE_REMOTE, - DbMode.USE_SERVER - ), - - /** pour lancer la generation des rapports */ - REPORT( - n("observe.actions.report.step"), - n("observe.actions.report.step.description"), - n("observe.actions.report.title"), - n("observe.actions.report.title.tip"), - "report", - n("observe.actions.report"), - n("observe.actions.report.description"), - ReportModel.class, - ReportUI.class, - false, - true, - false, - false, - DbMode.USE_LOCAL, - DbMode.USE_REMOTE, - DbMode.USE_SERVER - ), - - /** pour effectuer les modifications vers la base locale */ - SAVE_LOCAL( - n("observe.actions.saveLocal.step"), - n("observe.actions.saveLocal.step.description"), - null, - null, - "save", - n("observe.actions.saveLocal"), - n("observe.actions.saveLocal.description"), - SaveLocalModel.class, - SaveLocalUI.class, - false, - false, - false, - false - ), - - /** pour effectuer les modifications vers la base distante */ - EXPORT_DATA( - n("observe.actions.exportData.step"), - n("observe.actions.exportData.step.description"), - n("observe.actions.exportData.title"), - n("observe.actions.exportData.title.tip"), - "remote-export", - n("observe.actions.exportData"), - n("observe.actions.exportData.description"), - ExportModel.class, - ExportUI.class, - true, - true, - false, - false, - DbMode.USE_LOCAL, - DbMode.USE_REMOTE, - DbMode.USE_SERVER - ), - - /** pour afficher après les opération un ecran de résumé */ - SHOW_RESUME( - n("observe.actions.showResume.step"), - n("observe.actions.showResume.step.description"), - null, - ShowResumeUI.class, - false - ); - - private final String iconName; - - private final String title; - - private final String titleTip; - - private final String label; - - private final String description; - - private final String operationLabel; - - private final String operationDescription; - - private final Class<? extends AdminActionModel> modelClass; - - private final Class<? extends AdminTabUI> uiClass; - - private final DbMode[] incomingModes; - - private final boolean needReferentiel; - - private final boolean needSave; - - private final boolean needSelect; - - private final boolean config; - - private transient ImageIcon icon; - - AdminStep(String label, - String description, - Class<? extends AdminActionModel> modelClass, - Class<? extends AdminTabUI> uiClass, - boolean config) { - this(label, - description, - null, - null, - null, - null, - null, - modelClass, - uiClass, - false, - false, - false, - config - ); - } - - AdminStep(String label, - String description, - String title, - String titleTip, - String iconName, - String operationLabel, - String operationDescription, - Class<? extends AdminActionModel> modelClass, - Class<? extends AdminTabUI> uiClass, - boolean needReferentiel, - boolean needSelect, - boolean needSave, - boolean config, - DbMode... incomingModes) { - this.label = label; - this.description = description; - this.title = title; - this.titleTip = titleTip; - this.iconName = iconName; - this.operationDescription = operationDescription; - this.operationLabel = operationLabel; - this.needReferentiel = needReferentiel; - this.needSave = needSave; - this.needSelect = needSelect; - this.modelClass = modelClass; - this.uiClass = uiClass; - this.config = config; - this.incomingModes = incomingModes; - } - - public static EnumSet<AdminStep> getOperations() { - EnumSet<AdminStep> operations = EnumSet.noneOf(AdminStep.class); - for (AdminStep step : AdminStep.values()) { - if (step.isOperation()) { - operations.add(step); - } - } - return operations; - } - - public static AdminStep valueOfIgnoreCase(String value) { - for (AdminStep step : AdminStep.values()) { - if (step.name().equalsIgnoreCase(value)) { - return step; - } - } - return null; - } - - public String getTitle() { - return title; - } - - public String getTitleTip() { - return titleTip; - } - - public String getIconName() { - return iconName; - } - - public ImageIcon getIcon() { - if (iconName != null && icon == null) { - icon = (ImageIcon) UIHelper.getUIManagerActionIcon(iconName); - } - return icon; - } - - @Override - public String getLabel() { - return label; - } - - @Override - public String getDescription() { - return description; - } - - @Override - public String getOperationDescription() { - return operationDescription; - } - - @Override - public String getOperationLabel() { - return operationLabel; - } - - @Override - public boolean isOperation() { - return operationLabel != null; - } - - @Override - public boolean isConfig() { - return config; - } - - public boolean isNeedSelect() { - return needSelect; - } - - @Override - public Class<? extends AdminActionModel> getModelClass() { - return modelClass; - } - - @Override - public Class<? extends AdminTabUI> getUiClass() { - return uiClass; - } - - @Override - public AdminActionModel newModel() { - if (!isOperation()) { - throw new IllegalStateException("The current step [" + this + "] is not an operation."); - } - try { - return getModelClass().newInstance(); - } catch (Exception e) { - throw new IllegalStateException("Could not init model : " + getModelClass(), e); - } - } - - @Override - public AdminTabUI newUI(WizardExtUI<?, ?> ui) { - try { - Constructor<?> constructor = uiClass.getConstructor(AdminUI.class); - Object tabPanelUI = constructor.newInstance(ui); - return (AdminTabUI) tabPanelUI; - } catch (Exception e) { - throw new IllegalStateException("Could not init ui " + this, e); - } - } - - public boolean isNeedReferentiel() { - return needReferentiel; - } - - public boolean isNeedSave() { - return needSave; - } - - public DbMode[] getIncomingModes() { - return incomingModes; - } - - public boolean hasIncomingModes() { - return incomingModes.length > 0; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminTabUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminTabUI.jaxx deleted file mode 100644 index 3019162..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminTabUI.jaxx +++ /dev/null @@ -1,208 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<!-- **************************** --> -<!-- La base des contenu d'onglet --> -<!-- **************************** --> - -<JPanel id="mainPanel" abstract='true' - implements='jaxx.runtime.swing.wizard.WizardStepUI<AdminStep, AdminUIModel>, java.beans.PropertyChangeListener'> - - <import> - fr.ird.observe.ObserveSwingApplicationContext - fr.ird.observe.ui.UIHelper - fr.ird.observe.ui.admin.* - fr.ird.observe.ui.storage.StorageUIModel - - jaxx.runtime.swing.wizard.ext.WizardState - jaxx.runtime.swing.CardLayout2 - - java.awt.Color - java.awt.Dimension - java.beans.PropertyChangeEvent - javax.swing.border.LineBorder - </import> - - <AdminUIModel id='model' initializer='getContextValue(AdminUIModel.class)'/> - - <AdminActionModel id='stepModel' initializer='model.getStepModel(getStep())'/> - - <StorageUIModel id='localSourceModel' initializer='getModel().getLocalSourceModel()'/> - - <StorageUIModel id='centralSourceModel' initializer='getModel().getCentralSourceModel()'/> - - <AdminTabUIHandler id='handler' initializer='null'/> - - <AdminStep id='step' initializer='null'/> - - <script><![CDATA[ - -public abstract void initUI(AdminUI ui); - -protected AdminTabUI(AdminStep step, AdminUI parentContext) { - this.step = step; - UIHelper.checkJAXXContextEntry(parentContext, UIHelper.newContextEntryDef(AdminUIModel.class)); - UIHelper.initContext(this, parentContext); - $initialize(); - // pour etre sur que step est positionne (la methode d'init supprime la reference... - this.step = step; -} - -public void destroy() { - description.setText(""); - localSourceModel = null; - centralSourceModel = null; - UIHelper.destroy(this); -} - -@Override -protected void finalize() throws Throwable { - super.finalize(); - destroy(); -} - -@Override -public void propertyChange(PropertyChangeEvent evt) { - //propertyChange.super(evt); -} - -public void addMessage(AdminStep step, String text) { - getHandler().addMessage(step, text); -} - -public void updateState(WizardState newState) { - getHandler().updateState(this, newState); -} - -]]> - </script> - - <CardLayout2 id='contentLayout'/> - - <!-- titre --> - <JPanel layout='{new BorderLayout()}' constraints='BorderLayout.NORTH'> - <JProgressBar id='progress' constraints='BorderLayout.CENTER'/> - </JPanel> - - <!-- content --> - <JPanel id='content' decorator='boxed' constraints='BorderLayout.CENTER'> - - <JPanel id='PENDING_content' - constraints='WizardState.PENDING.name()'/> - - - <Table id="NEED_FIX_panel" fill='both' - constraints='WizardState.NEED_FIX.name()'> - <row> - <cell fill='both'> - <JPanel id="NEED_FIX_labelPanel"> - <JLabel id='NEED_FIX_label'/> - </JPanel> - - </cell> - </row> - <row> - <cell fill='both' weighty='1' weightx='1'> - <JPanel id='NEED_FIX_content'/> - </cell> - </row> - - </Table> - - <Table id="FAILED_panel" fill='both' - constraints='WizardState.FAILED.name()'> - <row> - <cell fill='both'> - <JLabel id='FAILED_label'/> - </cell> - </row> - <row> - <cell fill='both' weighty='1' weightx='1'> - <JScrollPane id='FAILED_progressionPane'/> - </cell> - </row> - - </Table> - - <Table id="RUNNING_panel" fill='both' - constraints='WizardState.RUNNING.name()'> - <row> - <cell fill='both' weighty='0.3'> - <JPanel id="RUNNING_top"> - <JLabel id='RUNNING_label' constraints='BorderLayout.CENTER'/> - </JPanel> - </cell> - </row> - <row> - <cell fill='both' weighty='0.7' weightx='1'> - <JScrollPane id='RUNNING_progressionPane'/> - </cell> - </row> - </Table> - - <Table id="SUCCESSED_panel" fill='both' - constraints='WizardState.SUCCESSED.name()'> - <row> - <cell fill='both' weighty='0.3'> - <JLabel id='SUCCESSED_label'/> - </cell> - </row> - <row> - <cell fill='both' weighty='0.7' weightx='1'> - <JScrollPane id='SUCCESSED_progressionPane'/> - </cell> - </row> - </Table> - - <Table fill='both' constraints='WizardState.CANCELED.name()'> - <row> - <cell fill='both' weighty='0.3'> - <JLabel id='CANCELED_label'/> - </cell> - </row> - <row> - <cell fill='both' weighty='0.7' weightx='1'> - <JScrollPane id='CANCELED_progressionPane'/> - </cell> - </row> - </Table> - - <JTextArea id='progression' constraints='"PROGRESSION"'/> - <JToolBar id='progressionTop' constraints='"PROGRESSION_TOP"'> - <JLabel id='progressionTopLabel'/> - <javax.swing.Box.Filler - constructorParams='UIHelper.newMinDimension(), UIHelper.newMinDimension(), UIHelper.newMaxXDimension()'/> - <JButton id="progressionTopCopyCliptBoard" - onActionPerformed='UIHelper.copyToClipBoard(progression.getText())'/> - </JToolBar> - </JPanel> - - <!-- description --> - <JScrollPane id="descriptionPane" constraints='BorderLayout.SOUTH'> - <JTextArea id='description'/> - </JScrollPane> - - <JPanel id='invisiblePanel' visible="false" constraints='BorderLayout.EAST'> - - </JPanel> - -</JPanel> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminTabUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminTabUIHandler.java deleted file mode 100644 index 1be451a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminTabUIHandler.java +++ /dev/null @@ -1,242 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin; - -import fr.ird.observe.ObserveRunner; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.service.BabModelVersionException; -import fr.ird.observe.services.service.DatabaseConnexionNotAuthorizedException; -import fr.ird.observe.services.service.DatabaseNotFoundException; -import fr.ird.observe.ui.admin.config.SelectDataUI; -import fr.ird.observe.ui.admin.resume.ShowResumeUI; -import fr.ird.observe.ui.storage.tabs.DataSelectionModel; -import fr.ird.observe.ui.tree.DataSelectionTreeSelectionModel; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import jaxx.runtime.swing.wizard.ext.WizardState; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JTree; -import javax.swing.tree.TreeModel; -import java.io.PrintWriter; -import java.io.StringWriter; -import java.util.concurrent.Callable; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Le controleur des onglets. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class AdminTabUIHandler { - - /** Logger */ - private static final Log log = LogFactory.getLog(AdminTabUIHandler.class); - - protected final AdminTabUI ui; - - protected final AdminUIModel model; - - protected AdminUI parentUI; - - /** Service de decoration. */ - private DecoratorService decoratorService; - - public AdminTabUIHandler(AdminTabUI ui) { - this.ui = ui; - model = ui.getModel(); - } - - public AdminTabUI getUi() { - return ui; - } - - public AdminUIModel getModel() { - return model; - } - - public final DecoratorService getDecoratorService() { - if (decoratorService == null) { - decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); - } - return decoratorService; - } - - public final WizardState onCancel(Exception e) { - if (log.isDebugEnabled()) { - log.debug(this, e); - } - sendMessage(t("observe.actions.operation.message.canceled")); - return WizardState.CANCELED; - } - - public final WizardState onError(Exception e) { - model.getStepModel(model.getOperation()).setError(e); - if (log.isErrorEnabled()) { - log.error(e.getMessage(), e); - } - sendMessage(t("observe.actions.operation.message.failed")); - return WizardState.FAILED; - } - - public void initTabUI(AdminUI ui, AdminTabUI tabUI) { - - parentUI = ui; - AdminStep step = tabUI.getStep(); - - tabUI.addPropertyChangeListener(tabUI); - - if (log.isDebugEnabled()) { - log.debug("common for [" + step + "] for main ui " + ui.getClass().getName() + "@" + System.identityHashCode(ui)); - } - - String stepLabel = t(step.getLabel()); - tabUI.getRUNNING_label().setText(t("observe.actions.operation.message.running", stepLabel)); - tabUI.SUCCESSED_label.setText(t("observe.actions.operation.message.successed", stepLabel)); - tabUI.NEED_FIX_label.setText(t("observe.actions.operation.message.needFix", stepLabel)); - tabUI.CANCELED_label.setText(t("observe.actions.operation.message.canceled", stepLabel)); - tabUI.FAILED_label.setText(t("observe.actions.operation.message.failed", stepLabel)); - tabUI.progression.setVisible(true); - tabUI.progressionTop.setVisible(true); - } - - public void updateState(AdminTabUI ui, WizardState newState) { - if (newState == null) { - newState = WizardState.PENDING; - } - ui.getContentLayout().show(ui.content, newState.name()); - switch (newState) { - case PENDING: - ui.description.setText(t(ui.getStep().getDescription())); - return; - case RUNNING: - ui.RUNNING_progressionPane.getViewport().setView(ui.progression); - ui.RUNNING_progressionPane.setColumnHeaderView(ui.progressionTop); - break; - case SUCCESSED: - ui.SUCCESSED_progressionPane.getViewport().setView(ui.progression); - ui.SUCCESSED_progressionPane.setColumnHeaderView(ui.progressionTop); - break; - case FAILED: - Exception e = ui.getStepModel().getError(); - StringWriter w = new StringWriter(); - e.printStackTrace(new PrintWriter(w)); - ui.addMessage(ui.getStep(), w.toString()); - ui.FAILED_progressionPane.getViewport().setView(ui.progression); - ui.FAILED_progressionPane.setColumnHeaderView(ui.progressionTop); - break; - case NEED_FIX: - break; - case CANCELED: - ui.CANCELED_progressionPane.getViewport().setView(ui.progression); - ui.CANCELED_progressionPane.setColumnHeaderView(ui.progressionTop); - break; - } - } - - public void sendMessage(String message) { - - AdminStep step = ui.getStep(); - ui.addMessage(step, message); - ShowResumeUI resumeUI = (ShowResumeUI) parentUI.getStepUI(AdminStep.SHOW_RESUME); - if (resumeUI != null) { - resumeUI.addMessage(step, message); - } - } - - public String getProgressString(int currentStep, int nbStep) { - String txt = ""; - AdminStep step = ui.getStep(); - if (step != null) { - txt = n("observe.storage.step.label"); - txt = t(txt, currentStep + 1, nbStep, t(step.getLabel())); - } - return txt; - } - - public void updateSelectionModel(SelectDataUI tabUI) { - - JTree selectTree = tabUI.getSelectTree(); - DataSelectionModel selectDataModel = tabUI.getSelectDataModel(); - DataSelectionTreeSelectionModel selectionModel = tabUI.getSelectionModel(); - ObserveTreeHelper helper = tabUI.getTreeHelper(); - ObserveSwingDataSource source = tabUI.getModel().getSafeLocalSource(true); - - updateSelectionModel(tabUI, helper, selectTree, source, selectDataModel, selectionModel); - - } - - protected void checkStepIsOperation(AdminTabUI ui) { - if (!ui.getStep().isOperation()) { - throw new IllegalStateException("can not launch objectOperation on none operation step " + ui.getStep()); - } - } - - protected void openSource(ObserveSwingDataSource service) throws DatabaseConnexionNotAuthorizedException, DatabaseNotFoundException, BabModelVersionException { - if (!service.isOpen()) { - service.open(); - } - } - - public void addAdminWorker(String label, Callable<WizardState> callable) { - AdminActionWorker worker = AdminActionWorker.newWorker(this, label, callable); - ObserveRunner.getActionExecutor().addAction(worker); - } - - protected void updateSelectionModel(AdminTabUI tabUI, - ObserveTreeHelper helper, - JTree selectTree, - ObserveSwingDataSource source, - DataSelectionModel selectDataModel, - DataSelectionTreeSelectionModel selectionModel) { - - - if (log.isDebugEnabled()) { - log.debug("reload model " + selectDataModel); - } - - selectionModel.clearSelection(); - - if (log.isDebugEnabled()) { - log.debug("Will treeHelper : " + helper); - log.debug("selection model : " + selectDataModel); - log.debug("use referentiel : " + selectDataModel.isUseReferentiel()); - log.debug("use data : " + selectDataModel.isUseData()); - } - - helper.setUI(selectTree, false); - - TreeModel model = helper.createModel(tabUI, selectDataModel, source); - selectTree.setModel(model); - - selectionModel.initUI(selectTree); - } - - public void addMessage(AdminStep step, String text) { - ui.getProgression().append(text + "\n"); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminUI.jaxx deleted file mode 100644 index 8d24844..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminUI.jaxx +++ /dev/null @@ -1,203 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<JPanel id='synchroPanel' implements='jaxx.runtime.swing.wizard.ext.WizardExtUI<AdminStep, AdminUIModel>'> - - <import> - fr.ird.observe.ui.UIHelper - - jaxx.runtime.JAXXContext - jaxx.runtime.swing.BlockingLayerUI - jaxx.runtime.swing.wizard.ext.WizardExtUI - jaxx.runtime.swing.wizard.ext.WizardExtUtil - jaxx.runtime.swing.wizard.ext.WizardState - - javax.swing.ImageIcon - javax.swing.UIManager - </import> - - <!-- le modèle du wizard --> - <AdminUIModel id='model' initializer='getContextValue(AdminUIModel.class)'/> - - <!-- le controleur d'ui --> - <AdminUIHandler id='handler' - initializer='getContextValue(AdminUIHandler.class)'/> - - <!-- le bloqueur d'ui utilisé par l'assistant --> - <BlockingLayerUI id='tabBusyBlockLayerUI'/> - - <!-- le bloqueur d'ui lorsqu'une action est en cours ou annulée --> - <BlockingLayerUI id='busyBlockLayerUI'/> - - <!-- le bloqueur de changement d'opérations --> - <BlockingLayerUI id='operationBlockLayerUI'/> - - <!-- le bloqueur de changement de configuration --> - <BlockingLayerUI id='configBlockLayerUI'/> - - <script><![CDATA[ - -private boolean contextInitialized; - -public AdminUI(JAXXContext parentContext, String title, String tip, ImageIcon icon) { - putClientProperty("title", title); - putClientProperty("tip", tip); - putClientProperty("imageIcon", icon); - - // verification du context parent - UIHelper.checkJAXXContextEntry(parentContext, UIHelper.newContextEntryDef(AdminUIModel.class)); - UIHelper.checkJAXXContextEntry(parentContext, UIHelper.newContextEntryDef(AdminUIHandler.class)); - UIHelper.initContext(this, parentContext); - - contextInitialized = true; -} - -public void destroy() { - getHandler().destroy(this); -} - -@Override -protected void finalize() throws Throwable { - super.finalize(); - destroy(); -} - -@Override -public void start() { - getHandler().start(this); -} - -public void cancel() { - getHandler().cancel(this); -} - -public void dispose() { - getHandler().dispose(this); -} - -@Override -public AdminStep getSelectedStep() { - return getHandler().getSelectedStep(this); -} - -@Override -public AdminTabUI getStepUI(AdminStep step) { - return getHandler().getStepUI(this, step); -} - -@Override -public AdminTabUI getStepUI(int stepIndex) { - return getHandler().getStepUI(this, stepIndex); -} - -@Override -public AdminTabUI getSelectedStepUI() { - return getHandler().getSelectedStepUI(this); -} - -public void blockOperations() { - getHandler().blockOperations(this); -} - -@Override -public void onWasInit() { - getHandler().onWasInit(this); -} - -@Override -public void onWasStarted() { - getHandler().onWasStarted(this); -} - -@Override -public void onModelStateChanged(WizardState newState) { - getHandler().onModelStateChanged(this, newState); -} - -@Override -public void onOperationStateChanged(AdminStep step, WizardState newState) { - getHandler().onOperationStateChanged(this, step, newState); -} - -@Override -public void onStepChanged(AdminStep oldStep, AdminStep newStep) { - getHandler().onStepChanged(this, oldStep, newStep); -} - -@Override -public void onStepsChanged(AdminStep[] steps) { - getHandler().onStepsChanged(this, steps); -} - -void $afterCompleteSetup() { - if (!allComponentsCreated || !contextInitialized) { - // pour partir quand l'ui n'est pas complementement initialise - // par example dans l'init de la classe parent - return; - } - - // installation du dispatcher de modifications du modele - WizardExtUtil.installWizardUIListeners(this); - WizardExtUtil.addTraceLogListener(log, getModel()); -} -]]> - </script> - - <!-- les onglets --> - <JTabbedPane id='tabs' decorator='boxed' - constraints='BorderLayout.CENTER' - onStateChanged='if (!model.isValueAdjusting()) { model.gotoStep(getSelectedStep()); }'/> - - <!-- les actions --> - <Table id='actions' constraints='BorderLayout.SOUTH'> - <row> - <cell weightx='0.5' fill="both"> - - <!-- pour annuler --> - <JButton id='cancelAction' onActionPerformed='getModel().cancel()'/> - </cell> - <cell weightx='0.5' fill="both"> - - <!-- quitter apres une annulation ou une erreur --> - <JButton id='closeOnCanceledOrFailedAction' - onActionPerformed='getHandler().cancel(this)'/> - </cell> - <cell weightx='0.5' fill="both"> - - <!-- pour aller sur l'onglet précédent --> - <JButton id="previousAction" - onActionPerformed='model.gotoPreviousStep()'/> - </cell> - <cell weightx='0.5' fill="both"> - - <!-- pour aller sur l'onglet suivant --> - <JButton id="nextAction" onActionPerformed='model.gotoNextStep()'/> - </cell> - <cell weightx='0.5' fill="both"> - - <!-- quitter quand les opérations sont exécutées correctement --> - <JButton id="closeAction" onActionPerformed='getHandler().close(this)'/> - </cell> - </row> - </Table> - -</JPanel> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminUIHandler.java deleted file mode 100644 index 723dc5e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminUIHandler.java +++ /dev/null @@ -1,381 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin; - -import fr.ird.observe.ObserveActionExecutor; -import fr.ird.observe.ObserveRunner; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.admin.config.ConfigUI; -import fr.ird.observe.ui.admin.resume.ShowResumeUI; -import fr.ird.observe.ui.admin.save.SaveLocalUI; -import jaxx.runtime.swing.wizard.WizardUILancher; -import jaxx.runtime.swing.wizard.ext.WizardExtUtil; -import jaxx.runtime.swing.wizard.ext.WizardState; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.Icon; -import javax.swing.JCheckBox; -import javax.swing.JComponent; -import javax.swing.border.TitledBorder; -import java.awt.Component; -import java.util.Arrays; -import java.util.Date; - -import static org.nuiton.i18n.I18n.t; - -/** - * Le controleur de l'ui des actions d'administration. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class AdminUIHandler { - - /** Logger */ - private static final Log log = LogFactory.getLog(AdminUIHandler.class); - - public AdminStep getSelectedStep(AdminUI ui) { - int index = ui.getTabs().getSelectedIndex(); - AdminTabUI c = null; - if (index > -1) { - c = (AdminTabUI) ui.getTabs().getComponentAt(index); - } - AdminStep result = c == null ? null : c.getStep(); - return result; - } - - public AdminTabUI getStepUI(AdminUI ui, AdminStep step) { - if (step != null) { - return (AdminTabUI) ui.getObjectById(step.name()); - } - return null; - } - - public AdminTabUI getStepUI(AdminUI ui, int stepIndex) { - if (stepIndex > ui.getTabs().getTabCount()) { - return null; - } - return (AdminTabUI) ui.getTabs().getComponentAt(stepIndex); - } - - public AdminTabUI getSelectedStepUI(AdminUI ui) { - AdminStep step = getSelectedStep(ui); - AdminTabUI tabUI = getStepUI(ui, step); - return tabUI; - } - - public void blockOperations(AdminUI ui) { - - ui.getModel().setValueAdjusting(true); - for (AdminStep op : AdminStep.values()) { - ConfigUI configUI = (ConfigUI) - ui.getStepUI(AdminStep.CONFIG); - JCheckBox comp = (JCheckBox) configUI.getObjectById(op.name()); - if (comp == null) { - continue; - } - if (!ui.getModel().getOperations().contains(op)) { - comp.setVisible(false); - } - } - ui.operationBlockLayerUI.setBlock(true); - ui.getModel().setValueAdjusting(false); - } - - public void onWasInit(AdminUI ui) { - if (log.isDebugEnabled()) { - log.debug(ui.getName() + " model was init at " + new Date()); - } - } - - public void onWasStarted(AdminUI ui) { - if (log.isDebugEnabled()) { - log.debug(ui.getName() + " model was started at " + new Date()); - } - } - - public void onStepsChanged(AdminUI ui, AdminStep[] steps) { - - if (log.isDebugEnabled()) { - log.debug("Will use these steps : " + Arrays.toString(steps)); - } - - ui.getModel().setValueAdjusting(true); - - - // on supprime tous les onglets - while (ui.tabs.getTabCount() > 1) { - - int index = ui.tabs.getTabCount() - 1; - if (log.isDebugEnabled()) { - log.debug("remove step : " + index); - } - - ui.tabs.remove(index); - } - - // on recree les onglets - for (int i = 0, max = steps.length; i < max; i++) { - AdminStep step = steps[i]; - AdminTabUI c = ui.getStepUI(step); - if (log.isDebugEnabled()) { - log.debug("StepUI [" + step + "] : " + c); - } - if (c == null) { - - if (log.isDebugEnabled()) { - log.debug("Will init step [" + step + "]"); - } - - c = step.newUI(ui); - - if (log.isDebugEnabled()) { - log.debug("Created tabUI [" + c.getName() + "]"); - } - - ui.get$objectMap().put(step.name(), c); - - if (log.isDebugEnabled()) { - log.debug("Will init tabUI [" + c.getName() + "]"); - } - c.initUI(ui); - - JComponent content = c.getContent(); - UIHelper.setLayerUI(content, ui.getBusyBlockLayerUI()); - } - - String title = t(step.getLabel()); - String tip = t(step.getDescription()); - ui.tabs.addTab(title, null, c, tip); - c.setEnabled(i == 0); - } - - ui.getModel().setValueAdjusting(false); - } - - public void onStepChanged(AdminUI ui, AdminStep oldStep, AdminStep newStep) { - if (log.isTraceEnabled()) { - log.trace(newStep); - } - AdminTabUI c = ui.getStepUI(newStep); - - AdminUIModel model = ui.getModel(); - - if (oldStep == null - && newStep == AdminStep.CONFIG - && (model.containsOperation(AdminStep.REFERENTIAL_SYNCHRONIZE) || model.containsOperation(AdminStep.DATA_SYNCHRONIZE))) { - - ConfigUI configUI = (ConfigUI) ui.getStepUI(AdminStep.CONFIG); - - model.setLocalSourceLabel(t("observe.storage.config.left.storage")); - model.setCentralSourceLabel(t("observe.storage.config.right.storage")); - - configUI.getLocalSourceConfig().setBorder(new TitledBorder(model.getLocalSourceLabel())); - configUI.getCentralSourceConfig().setBorder(new TitledBorder(model.getCentralSourceLabel())); - - } - - if (c != null && c.getStep() == AdminStep.SAVE_LOCAL) { - - // on met a jour le descriptif - SaveLocalUI saveUI = (SaveLocalUI) ui.getStepUI(AdminStep.SAVE_LOCAL); - saveUI.getHandler().updateText(); - } - if (c != null && c.getStep() == AdminStep.SHOW_RESUME) { - - // on met a jour le resumé des opérations - ShowResumeUI showResumeUI = (ShowResumeUI) ui.getStepUI(AdminStep.SHOW_RESUME); - showResumeUI.getHandler().updateText(); - } - - // selection du nouvel onglet - int index = ui.tabs.indexOfComponent(c); - if (index > -1 && ui.tabs.getSelectedIndex() != index) { - ui.tabs.setSelectedIndex(index); - } - } - - /** - * Call back lorsque l'état du modèle a changé. - * - * Ici, on va rendre accessible (ou pas) les onglets selon l'état du modèle. - * - * @param ui l'ui concernée - * @param newState le nouvel état. - */ - public void onModelStateChanged(AdminUI ui, WizardState newState) { - if (log.isDebugEnabled()) { - log.debug(newState); - } - - AdminTabUI selected = ui.getSelectedStepUI(); - boolean busy = WizardExtUtil.acceptStates(newState, WizardState.RUNNING); - UIHelper.TabbedPaneIterator<Component> itr = UIHelper.newTabbedPaneIterator(ui.getTabs()); - if (busy) { - if (log.isDebugEnabled()) { - log.debug("Busy state, can only access selected step : " + selected); - } - // seul l'onglet courant est accessible - for (; itr.hasNext(); ) { - Component tab = itr.next(); - ui.tabs.setEnabledAt(itr.getIndex() - 1, tab.equals(selected)); - } - return; - } - - if (selected != null && selected.getStep().isConfig()) { - - if (log.isDebugEnabled()) { - log.debug("Selected step is config : " + selected.getStep()); - } - for (; itr.hasNext(); ) { - int index = itr.getIndex(); - Component tab = itr.next(); - AdminTabUI tabUI = (AdminTabUI) tab; - AdminStep synchroStep = tabUI.getStep(); - if (synchroStep.isConfig()) { - if (log.isDebugEnabled()) { - log.debug("Test config panel : " + synchroStep); - } - boolean valid = ui.getModel().validate(synchroStep); - if (valid) { - if (log.isDebugEnabled()) { - log.debug("step " + synchroStep + " is valid"); - } - ui.tabs.setIconAt(index, getTabIcon(WizardState.SUCCESSED)); - } else { - if (log.isDebugEnabled()) { - log.debug("step " + synchroStep + " is not valid!"); - } - ui.tabs.setIconAt(index, getTabIcon(WizardState.FAILED)); - } - } - } - itr = UIHelper.newTabbedPaneIterator(ui.getTabs()); - } - - if (selected != null && selected.getStep() == AdminStep.SHOW_RESUME) { - - // rien a faire sur le dernier onglet - if (log.isDebugEnabled()) { - log.debug("We are on last step (resume), nothing to do."); - } - return; - } - boolean[] accessibleSteps = ui.getModel().getAccessibleSteps(); - if (log.isDebugEnabled()) { - log.debug("Accessibles step : " + Arrays.toString(accessibleSteps)); - } - for (; itr.hasNext(); itr.next()) { - int index = itr.getIndex(); - ui.tabs.setEnabledAt(index, accessibleSteps[index]); - } - if (!ui.getModel().containsOperation(AdminStep.REPORT)) { - - // le dernier onglet est accessible uniquement si c'est un resume - // actuellement seul l'action de report n'a pas de resume - //TODO chemit 20190 09 29 Il faudrait avoir la propriete needResume pour faire ça de manière générique - ui.tabs.setEnabledAt(accessibleSteps.length - 1, true); - } - } - - public void onOperationStateChanged(AdminUI ui, AdminStep step, WizardState newState) { - if (log.isDebugEnabled()) { - log.debug(step + " - " + newState); - } - - // mettre a jour l'onglet - AdminTabUI selected = ui.getStepUI(step); - int index = ui.tabs.indexOfComponent(selected); - if (index > -1 && !selected.getStep().isConfig()) { - ui.tabs.setIconAt(index, getTabIcon(newState)); - } - if (selected != null && step == selected.getStep()) { - selected.updateState(newState); - } - } - - public void start(AdminUI ui) { - - try { - // on demarre le modele - ui.getModel().start(ui); - - // affichage ui - ui.setVisible(true); - - } finally { - - ui.getModel().setBusy(false); - } - } - - public void close(AdminUI ui) { - - Runnable action = WizardUILancher.APPLY_DEF.getContextValue(ui); - - ObserveActionExecutor executor = ObserveRunner.getActionExecutor(); - - executor.addAction(t("observe.action.admin.close"), action); - } - - public void cancel(AdminUI ui) { - - Runnable action = WizardUILancher.CANCEL_DEF.getContextValue(ui); - - ObserveActionExecutor executor = ObserveRunner.getActionExecutor(); - - executor.addAction(t("observe.action.admin.cancel"), action); - } - - public void destroy(AdminUI ui) { - ui.getModel().destroy(); - if (log.isDebugEnabled()) { - log.debug("destroy ui " + ui.getName()); - } - UIHelper.TabbedPaneIterator<Component> itr = UIHelper.newTabbedPaneIterator(ui.getTabs()); - for (; itr.hasNext(); ) { - AdminTabUI tab = (AdminTabUI) itr.next(); - if (log.isDebugEnabled()) { - log.debug("destroy ui " + tab.getName()); - } - tab.destroy(); - } - UIHelper.destroy(ui); - } - - public void dispose(AdminUI ui) { - destroy(ui); - } - - public Icon getTabIcon(WizardState state) { - Icon i = null; - if (state != null) { - String key = "wizard-state-" + state.name().toLowerCase(); - i = UIHelper.getUIManagerActionIcon(key); - } - return i; - } - - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminUILauncher.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminUILauncher.java deleted file mode 100644 index 437053f..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminUILauncher.java +++ /dev/null @@ -1,275 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.ObserveUIMode; -import fr.ird.observe.ui.UIHelper; -import jaxx.runtime.JAXXContext; -import jaxx.runtime.swing.wizard.BusyChangeListener; -import jaxx.runtime.swing.wizard.WizardUILancher; -import jaxx.runtime.swing.wizard.ext.WizardState; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.jdesktop.swingx.JXTitledPanel; - -import javax.swing.ImageIcon; -import javax.swing.JDialog; -import javax.swing.SwingUtilities; -import java.awt.Component; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; - -import static org.nuiton.i18n.I18n.t; - -/** - * Le wizard de base pour les opérations complexes. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class AdminUILauncher extends WizardUILancher<AdminStep, AdminUIModel, AdminUI> { - - /** Logger */ - private static final Log log = LogFactory.getLog(AdminUILauncher.class); - - protected final AdminStep uniqueAction; - - protected Component parent; - - protected AdminUILauncher(JAXXContext context, AdminStep uniqueAction) { - super(context, - AdminUI.class, - AdminUIModel.class, - t(uniqueAction.getTitle()), - t(uniqueAction.getTitleTip()), - uniqueAction.getIcon() - ); - this.uniqueAction = uniqueAction; - } - - public static AdminUILauncher newLauncher(JAXXContext context, AdminStep action) { - - AdminUIHandler handler = context.getContextValue(AdminUIHandler.class); - if (handler == null) { - - handler = new AdminUIHandler(); - context.setContextValue(handler); - - if (log.isDebugEnabled()) { - log.debug("Register in context an admin handler : " + handler); - } - } - return new AdminUILauncher(context, action); - } - - @Override - protected void init(AdminUI ui) { - - parent = getParent(ui); - - AdminUIModel model = ui.getModel(); - - model.addOperation(uniqueAction); - - model.updateUniverse(); - - if (uniqueAction != null) { - // on a juste besoin de faire une action - - ui.blockOperations(); - } - - BusyChangeListener listener = new BusyChangeListener(parent) { - - @Override - protected void setBusy(Component ui) { - if (log.isDebugEnabled()) { - log.debug("Busy for component " + ui); - } - if (parent instanceof ObserveMainUI) { - ((ObserveMainUI) parent).setBusy(true); - super.setBusy(parent); - } - super.setBusy(ui); - } - - @Override - protected void setUnBusy(Component ui) { - if (log.isDebugEnabled()) { - log.debug("UnBusy for component " + ui); - } - if (parent instanceof ObserveMainUI) { - ((ObserveMainUI) parent).setBusy(false); - super.setUnBusy(parent); - } - super.setUnBusy(ui); - } - }; - UIHelper.setLayerUI(ui.getTabs(), ui.getTabBusyBlockLayerUI()); - listener.setBlockingUI(ui.getTabBusyBlockLayerUI()); - model.addPropertyChangeListener(AdminUIModel.BUSY_PROPERTY_NAME, listener); - } - - - protected Component getParent(AdminUI ui) { - ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); - ImageIcon icon = (ImageIcon) ui.getClientProperty("icon"); - if (mainUI == null) { - // pas de fenetre detectee - // on encapsule l'ui dans un dialog - - JDialog dialog = new JDialog(); - dialog.setSize(1024, 780); - - if (icon != null) { - dialog.setIconImage(icon.getImage()); - } - dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE); - dialog.setAlwaysOnTop(true); - dialog.setModal(true); - dialog.addWindowListener(new WindowAdapter() { - - @Override - public void windowClosed(WindowEvent e) { - if (log.isInfoEnabled()) { - log.info("closing dialog " + e.getWindow().getName()); - } - if (AdminUILauncher.this.ui.getModel().getModelState() - != WizardState.CANCELED) { - if (log.isInfoEnabled()) { - log.info("cancel panel from dialog !" + - e.getWindow().getName()); - } - AdminUILauncher.this.ui.cancel(); - } - } - }); - return dialog; - } else { - return mainUI; - } - } - - @Override - protected void start(final AdminUI ui) { - super.start(ui); - - ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); - - String title = (String) ui.getClientProperty("title"); - - if (mainUI == null) { - - // pas de fenetre detectee - // on encapsule l'ui dans un dialog - - JDialog dialog = (JDialog) parent; - dialog.setTitle(t(title)); - dialog.setContentPane(ui); -// dialog.pack(); - dialog.setVisible(true); - if (log.isDebugEnabled()) { - log.debug("After dispay dialog"); - } - } else { - - // on attache dans la fenetre principale - String tip = (String) ui.getClientProperty("tip"); - - JXTitledPanel panel = mainUI.getSynchroWizard(); - panel.setTitle(t(title)); - panel.setToolTipText(t(tip)); - panel.setContentContainer(ui); - mainUI.setContextValue(ui.getModel()); - mainUI.setMode(ObserveUIMode.SYNCHRO); - - // refresh selected tab (otherwise it does NOT display (white screen...) - SwingUtilities.invokeLater(() -> ui.getTabs().getSelectedComponent().validate()); - } - } - - @Override - protected void doClose(AdminUI ui, boolean wasCanceled) { - if (log.isInfoEnabled()) { - log.info(this + ", was canceled ? " + wasCanceled); - } - - ObserveMainUI mainUI = null; - - AdminUIModel model = ui.getModel(); - - try { - - - model.doCloseSource(model.getCentralSource(), false); - model.doCloseSource(model.getLocalSource(), false); - - if (!(parent instanceof ObserveMainUI)) { - JDialog dialog = (JDialog) parent; - if (log.isInfoEnabled()) { - log.info("dispose ui!"); - } - ui.dispose(); - dialog.setVisible(false); - dialog.dispose(); - if (log.isInfoEnabled()) { - log.info("After dispose."); - } - ObserveSwingApplicationContext.get().releaseLock(); - return; - } - - mainUI = (ObserveMainUI) parent; - mainUI.getSynchroWizard().remove(ui); - mainUI.removeContextValue(model.getClass()); - - - ObserveSwingDataSource source = model.getPreviousSource(); - - if (source == null) { - - // pas de service auparavant - mainUI.setMode(ObserveUIMode.NO_DB); - return; - } - - model.doCloseSource(source, false); - - // on attache la source a l'ui - ObserveSwingApplicationContext.get().prepareMainStorage(source, false); - - source.open(); - - } catch (Exception e) { - - // on a pas reussit a reouvrir la base precedente - UIHelper.handlingError("Could not close", e); - - if (mainUI != null) { - mainUI.setMode(ObserveUIMode.NO_DB); - } - } - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminUIModel.java deleted file mode 100644 index 7aa0014..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/AdminUIModel.java +++ /dev/null @@ -1,1493 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin; - -import com.google.common.collect.Lists; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.db.constants.DbMode; -import fr.ird.observe.services.configuration.ObserveDataSourceConfiguration; -import fr.ird.observe.services.configuration.ObserveDataSourceInformation; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.DataReferenceSet; -import fr.ird.observe.services.dto.IdDtos; -import fr.ird.observe.services.dto.actions.report.Report; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.services.service.BabModelVersionException; -import fr.ird.observe.services.service.DatabaseConnexionNotAuthorizedException; -import fr.ird.observe.services.service.DatabaseDestroyNotAuthorizedException; -import fr.ird.observe.services.service.DatabaseNotFoundException; -import fr.ird.observe.services.service.actions.synchro.referential.ReferentialSynchronizeMode; -import fr.ird.observe.services.service.actions.validate.ValidateService; -import fr.ird.observe.services.service.longline.TripLonglineService; -import fr.ird.observe.services.service.seine.TripSeineService; -import fr.ird.observe.ui.admin.config.ConfigUI; -import fr.ird.observe.ui.admin.consolidate.ConsolidateModel; -import fr.ird.observe.ui.admin.export.ExportModel; -import fr.ird.observe.ui.admin.report.ReportModel; -import fr.ird.observe.ui.admin.save.SaveLocalModel; -import fr.ird.observe.ui.admin.synchronize.data.DataSynchroModel; -import fr.ird.observe.ui.admin.synchronize.referential.legacy.SynchronizeModel; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchroModel; -import fr.ird.observe.ui.admin.validate.ValidateModel; -import fr.ird.observe.ui.storage.StorageUIHandler; -import fr.ird.observe.ui.storage.StorageUIModel; -import fr.ird.observe.ui.storage.tabs.DataSelectionModel; -import fr.ird.observe.validation.ValidationModelMode; -import jaxx.runtime.swing.wizard.ext.WizardExtModel; -import jaxx.runtime.swing.wizard.ext.WizardState; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.border.TitledBorder; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.EnumSet; -import java.util.List; -import java.util.Set; - -import static fr.ird.observe.ObserveResourceManager.Resource; -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Le modele de l'ui pour effectuer des opérations de synchro et validation. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class AdminUIModel extends WizardExtModel<AdminStep> { - - public static final String SELECTION_MODEL_CHANGED_PROPERTY_NAME = "selectionModelChanged"; - - public static final String SELECTED_TRIP_PROPERTY_NAME = "selectedTrip"; - - /** Logger */ - private static final Log log = LogFactory.getLog(AdminUIModel.class); - - public static final PropertyChangeListener LOG_PROPERTY_CHANGE_LISTENER = new LogPropertyChanged(); - - public static final String PROPERTY_LOCAL_SOURCE_LABEL = "localSourceLabel"; - public static final String PROPERTY_CENTRAL_SOURCE_LABEL = "centralSourceLabel"; - - /** la source de données en cours d'utilisation par l'application */ - protected ObserveSwingDataSource previousSource; - - /** la source de données sur laquel on veut travailler */ - protected ObserveSwingDataSource localSource; - - /** la source de données sur laquel on veut travailler */ - protected ObserveDataSourceInformation localSourceInformation; - - /** la source de données dite central (contenant le référentiel valide) */ - protected ObserveSwingDataSource centralSource; - - /** la configuration de la base source */ - protected final StorageUIModel localSourceModel; - - /** la configuration de la base central */ - protected final StorageUIModel centralSourceModel; - - /** le controleur pour configurer les sources */ - protected StorageUIHandler storageHandler; - - /** selection des donnees a valider */ - protected final DataSelectionModel selectionDataModel; - - /** la liste des modes disponibles en entrée */ - protected final EnumSet<DbMode> availableIncomingModes; - - private final PropertyChangeListener listenStepChanged; - - private final PropertyChangeListener listenSelectModified; - - private final PropertyChangeListener listenValidationModified; - - private final PropertyChangeListener listenReportModified; - - private final PropertyChangeListener listenerSelectedDataForReport; - - private final PropertyChangeListener listenConsolidateModified; - - private final PropertyChangeListener listenSaveLocalChanged; - private final PropertyChangeListener listenReferentialConfigChanged; - - private String localSourceLabel = t("observe.storage.config.source.storage"); - private String centralSourceLabel = t("observe.storage.config.referentiel.storage"); - - public String getLocalSourceLabel() { - return localSourceLabel; - } - - public void setLocalSourceLabel(String localSourceLabel) { - Object oldValue = getLocalSourceLabel(); - this.localSourceLabel = localSourceLabel; - firePropertyChange(PROPERTY_LOCAL_SOURCE_LABEL, oldValue, localSourceLabel); - } - - public String getCentralSourceLabel() { - return centralSourceLabel; - } - - public void setCentralSourceLabel(String centralSourceLabel) { - Object oldValue = getCentralSourceLabel(); - this.centralSourceLabel = centralSourceLabel; - firePropertyChange(PROPERTY_CENTRAL_SOURCE_LABEL, oldValue, centralSourceLabel); - } - - public AdminUIModel() { - super(AdminStep.class); - - localSourceModel = new StorageUIModel() { - - @Override - public String getLabel() { - String txt; - if (containsOperation(AdminStep.REFERENTIAL_SYNCHRONIZE) || containsOperation(AdminStep.DATA_SYNCHRONIZE)) { - txt = n("observe.storage.label.synchro.leftSource"); - } else { - txt = n("observe.storage.label.synchro.incoming"); - } - String params; - - if (getDbMode() == DbMode.USE_SERVER) { - params = t("observe.storage.server.db") + " " + getRemoteUrl(); - } else if (getDbMode() == DbMode.USE_REMOTE) { - params = t("observe.storage.remote.db") + " " + getRemoteUrl(); - } else { - params = t("observe.storage.locale.db") + " " + getH2Config().getDirectory().getAbsolutePath(); - } - txt = t(txt, params); - return txt; - } - - @Override - public void validate() { - super.validate(); - - // on declanche la revalidation du modèle - firePropertyChange(VALID_PROPERTY_NAME, isValid()); - } - - }; - - centralSourceModel = new StorageUIModel() { - - @Override - public String getLabel() { - String txt; - if (containsOperation(AdminStep.REFERENTIAL_SYNCHRONIZE) || containsOperation(AdminStep.DATA_SYNCHRONIZE)) { - txt = n("observe.storage.label.synchro.rightSource"); - } else { - txt = n("observe.storage.label.synchro.referentiel"); - } - String params; - - if (getDbMode() == DbMode.USE_SERVER) { - params = t("observe.storage.server.db") + " " + getRemoteUrl(); - } else if (getDbMode() == DbMode.USE_REMOTE) { - params = t("observe.storage.remote.db") + " " + getRemoteUrl(); - } else { - params = t("observe.storage.locale.db") + " " + getH2Config().getDirectory().getAbsolutePath(); - } - txt = t(txt, params); - return txt; - } - - @Override - public void validate() { - super.validate(); - - // on declanche la revalidation du modèle - firePropertyChange(VALID_PROPERTY_NAME, isValid()); - } - }; - - selectionDataModel = new DataSelectionModel(); - - availableIncomingModes = EnumSet.noneOf(DbMode.class); - - if (log.isDebugEnabled()) { - log.debug("model [" + this + "] is instanciate."); - } - - listenReferentialConfigChanged = evt -> { - - - if (isWasStarted()) { - - // on ne propage plus rien (il n'y a plus de configuration possible...) - if (log.isDebugEnabled()) { - log.debug("Stop propagation, was started... " + evt.getPropertyName()); - } - return; - } - - if (ReferentialSynchroModel.SYNCHRONIZE_MODE_PROPERTY_NAME.equals(evt.getPropertyName())) { - - validate(); - - } - - }; - - listenStepChanged = evt -> { - - if (isWasStarted()) { - - // on ne propage plus rien (il n'y a plus de configuration possible...) - if (log.isDebugEnabled()) { - log.debug("Stop propagation, was started... " + evt.getPropertyName()); - } - return; - } - - AdminStep oldStep = (AdminStep) evt.getOldValue(); - AdminStep newStep = (AdminStep) evt.getNewValue(); - - if (AdminStep.REPORT == newStep) { - - if (oldStep != null && oldStep.ordinal() < newStep.ordinal()) { - - int oldIndex = getStepIndex(oldStep); - int newIndex = getStepIndex(newStep); - - if (oldIndex < newIndex) { - - // on reinitialise le report sélectionné - getReportModel().setSelectedReport(null); - } - } - } - - if (AdminStep.CONFIG == newStep) { - - // on repasse sur l'écran de configuration - - if (containsOperation(AdminStep.REFERENTIAL_SYNCHRONIZE) || containsOperation(AdminStep.DATA_SYNCHRONIZE)) { - - setLocalSourceLabel(t("observe.storage.config.left.storage")); - setCentralSourceLabel(t("observe.storage.config.right.storage")); - - } - - return; - } - - if (oldStep != null && oldStep != AdminStep.CONFIG) { - - // on fait rien si on ne vient pas de la configuration - return; - } - - // on était sur l'écran de configuration - - // mise à jour des modèles de sélection si on arrive sur une étape - // qui le requière - - boolean needSelect = needSelect(); - - if (!needSelect) { - - // pas besoin d'agir sur le model de sélection de données - return; - } - - DataSelectionModel selectModel = getSelectionDataModel(); - - if (containsOperation(AdminStep.EXPORT_DATA)) { - - // on doit aussi calculer les ids des marées distantes - computeExistingTrips(getSafeCentralSource(true)); - - } - - // on remplit le modèle de sélection - if (log.isDebugEnabled()) { - log.debug("Will refill selectionModel [" + newStep + "] : " + selectModel); - } - ObserveSwingDataSource dataSource = getSafeLocalSource(true); - populateSelectionModel(dataSource); - }; - listenSelectModified = evt -> { - DataSelectionModel source = (DataSelectionModel) evt.getSource(); - if (log.isDebugEnabled()) { - log.debug("selection data model [" + source + "] changed on " + - evt.getPropertyName() + ", new value = " + - evt.getNewValue()); - } - validate(); - if (log.isDebugEnabled()) { - log.debug("nb selected export datas = " + - source.getSelectedData().size()); - } - - // on declanche la revalidation du modèle - firePropertyChange(VALID_STEP_PROPERTY_NAME, validStep); - }; - listenValidationModified = evt -> { - ValidateModel source = (ValidateModel) evt.getSource(); - if (log.isDebugEnabled()) { - log.debug("validation model [" + source + "] changed on " + - evt.getPropertyName() + ", new value = " + - evt.getNewValue()); - } - validate(); - if (log.isDebugEnabled()) { - log.debug("nb validators = " + - source.getValidators().size() - ); - } - firePropertyChange(VALID_STEP_PROPERTY_NAME, validStep); - }; - listenReportModified = evt -> { - ReportModel source = (ReportModel) evt.getSource(); - if (log.isDebugEnabled()) { - log.debug("report model [" + source + "] changed on " + - evt.getPropertyName() + ", new value = " + - evt.getNewValue()); - } - validate(); - firePropertyChange(VALID_STEP_PROPERTY_NAME, validStep); - }; - listenerSelectedDataForReport = evt -> { - - // la modification de la sélection entraine la suppression d'un report sélectionné - getReportModel().setSelectedReport(null); - - // cela entraine aussi la modification de la marée sélectionnée - firePropertyChange(SELECTED_TRIP_PROPERTY_NAME, getSelectedTrip()); - - }; - listenConsolidateModified = evt -> { - ConsolidateModel source = (ConsolidateModel) evt.getSource(); - if (log.isDebugEnabled()) { - log.debug("consolidate model [" + source + "] changed on " + - evt.getPropertyName() + ", new value = " + - evt.getNewValue()); - } - validate(); - firePropertyChange(VALID_STEP_PROPERTY_NAME, validStep); - }; - listenSaveLocalChanged = evt -> { - - String propertyName = evt.getPropertyName(); - - if (SaveLocalModel.BACKUP_FILE_PROPERTY_NAME.equals(propertyName)) { - - validate(); - return; - } - - if (SaveLocalModel.LOCAL_SOURCE_NEED_SAVE_PROPERTY_NAME.equals(propertyName)) { - boolean localSourceNeedSave = (Boolean) evt.getNewValue(); - if (localSourceNeedSave) { - // l'opération de sauvegarde est obligatoire - setStepState(AdminStep.SAVE_LOCAL, WizardState.PENDING); - } - validate(); - return; - } - - if (log.isDebugEnabled()) { - log.debug("Skip property " + propertyName); - } - }; - } - - public DataSelectionModel getSelectionDataModel() { - return selectionDataModel; - } - - public boolean needSelect() { - if (WizardState.CANCELED == getModelState()) { - return false; - } - Set<AdminStep> operations = getOperations(); - for (AdminStep operation : operations) { - if (operation.isNeedSelect()) { - return true; - } - } - return false; - } - - public DataReference getSelectedTrip() { - Set<DataReference> data = getSelectionDataModel().getSelectedData(); - if (data.isEmpty()) { - - // pas de Trip selectionne - return null; - } - DataReference dto = data.iterator().next(); - if (IdDtos.isTrip(dto)) { - return dto; - } - - // la donnée n'est pas une marée - return null; - } - - @Override - public AdminActionModel getStepModel(AdminStep operation) { - return (AdminActionModel) super.getStepModel(operation); - } - - /** - * Pour savoir si on a besoin d'une base source pour l'opération. - * - * Actuellement, seul l'opération d'import acces n'a pas besoin d'une telle - * base. - * - * @return {@code true} si au moins une des opérations a besoin d'une source - * d'entrée, {@code false} autrement. - * @since 2.0 - */ - public boolean isNeedIncomingDataSource() { - for (AdminStep op : getOperations()) { - if (op.hasIncomingModes()) { - - // l'operation requiere une base en entree - return true; - } - } - - // aucune operation ne requiere pas de base en entree - return false; - } - - /** - * Pour savoir si on a besoin d'une base de référence pour l'opération. - * - * @return {@code true} si au moins une des opérations a besoin d'une source - * de référence, {@code false} autrement. - * @since 2.0 - */ - public boolean isNeedReferentielDataSource() { - for (AdminStep op : getOperations()) { - if (op.isNeedReferentiel()) { - - // l'operation requiere une base de référence - return true; - } - } - - // aucune operation ne requiere pas de base de référence - return false; - } - - /** - * Construit l'ensemble des modes disponibles pour la base en entrée. - * - * @return l'ensemble des modes disponibles. - */ - public EnumSet<DbMode> getIncomingDataSourceMode() { - - EnumSet<DbMode> result = EnumSet.noneOf(DbMode.class); - getOperations().stream().filter(AdminStep::hasIncomingModes).forEach(op -> result.addAll(Arrays.asList(op.getIncomingModes()))); - return result; - } - - public void start(AdminUI ui) { - - availableIncomingModes.clear(); - - storageHandler = ui.getContextValue(StorageUIHandler.class); - - ObserveSwingApplicationConfig config = ObserveSwingApplicationContext.get().getConfig(); - - // demarrage du modèle : on fixe ici une fois pour toute les liste - // des onglets visibles - start(); - - // preparation de l'ui (création des onglets visibles) - ui.blockOperations(); - - if (log.isInfoEnabled()) { - log.info("enables steps = " + steps); - log.info("enables operations = " + operations); - } - - // on positionne la source courante de l'application comme service - // entrant (on se sert de la configuration de ce service s'il existe - // pour la source locale). - ObserveSwingDataSource previousSource = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); - setPreviousSource(previousSource); - - startIncomingSourceModel(ui); - - startCentralSourceModel(ui); - - startSelectModel(); - - // avant le demarrage du wizard, on ferme toujours la source - // en cours d'utilisation - - if (previousSource != null && previousSource.isOpen()) { - - if (log.isDebugEnabled()) { - log.debug("Close previous source " + - previousSource.getLabel()); - } - doCloseSource(previousSource, false); - } - - if (containsOperation(AdminStep.SAVE_LOCAL)) { - - File backupfile = new File(config.getBackupDirectory(), storageHandler.getDefaultBackupFilename()); - - getSaveLocalModel().setBackupFile(backupfile); - getSaveLocalModel().setDoBackup(true); - getSaveLocalModel().removePropertyChangeListener(listenSaveLocalChanged); - getSaveLocalModel().addPropertyChangeListener(listenSaveLocalChanged); - } - - if (containsOperation(AdminStep.VALIDATE)) { - - getValidateModel().removePropertyChangeListener(listenValidationModified); - getValidateModel().addPropertyChangeListener(listenValidationModified); - getValidateModel().addScope(NuitonValidatorScope.ERROR); - getValidateModel().setModelMode(ValidationModelMode.DATA); - getValidateModel().setContextName(ValidateService.SERVICE_VALIDATION_CONTEXT); - getValidateModel().setGenerateReport(true); - if (!config.getValidationReportDirectory().exists()) { - boolean b = config.getValidationReportDirectory().mkdirs(); - if (!b) { - throw new RuntimeException("Could not create directory " + config.getValidationReportDirectory()); - } - } - File reportFile = new File(config.getValidationReportDirectory(), - getValidateModel().getDefaultReportFilename()); - getValidateModel().setReportFile(reportFile); - } - - if (containsOperation(AdminStep.REPORT)) { - - File reportFile = Resource.report.getFile(config.getReportDirectory()); - - if (reportFile.exists()) { - if (log.isInfoEnabled()) { - log.info("Will use report file : " + reportFile); - } - - getReportModel().setReportFile(reportFile); - } else { - if (log.isWarnEnabled()) - log.warn("Default report file " + reportFile + " does not exists."); - } - // on charge la liste des reports disponilbes - List<Report> reports = getReportModel().getReports(); - - // on ecoute la modification du modèle - getReportModel().removePropertyChangeListener(listenReportModified); - getReportModel().addPropertyChangeListener(listenReportModified); - - // on ecoute la modification de la sélection - getSelectionDataModel().removePropertyChangeListener(DataSelectionModel.PROPERTY_SELECTED_DATA, listenerSelectedDataForReport); - getSelectionDataModel().addPropertyChangeListener(DataSelectionModel.PROPERTY_SELECTED_DATA, listenerSelectedDataForReport); - - if (log.isInfoEnabled()) { - log.info("Detects " + reports.size() + " report(s)."); - } - } - - if (containsOperation(AdminStep.CONSOLIDATE)) { - - // Anything to init ? - getConsolidateModel().removePropertyChangeListener(listenConsolidateModified); - getConsolidateModel().addPropertyChangeListener(listenConsolidateModified); - } - - if (containsOperation(AdminStep.DATA_SYNCHRONIZE)) { - - ConfigUI configUI = (ConfigUI) ui.getStepUI(AdminStep.CONFIG); - - configUI.getLocalSourceConfig().setBorder(new TitledBorder(getLocalSourceLabel())); - configUI.getCentralSourceConfig().setBorder(new TitledBorder(getCentralSourceLabel())); - - } - if (containsOperation(AdminStep.REFERENTIAL_SYNCHRONIZE)) { - - getReferentialSynchroModel().removePropertyChangeListener(listenReferentialConfigChanged); - getReferentialSynchroModel().addPropertyChangeListener(listenReferentialConfigChanged); - - getReferentialSynchroModel().addPropertyChangeListener(ReferentialSynchroModel.SYNCHRONIZE_MODE_PROPERTY_NAME, evt -> { - - ReferentialSynchronizeMode newValue = (ReferentialSynchronizeMode) evt.getNewValue(); - - if (ui.getTabs().getComponentCount() > 1 && newValue != null) { - ui.getTabs().setTitleAt(1, t("observe.actions.synchro.referential.withMode", newValue.getLabel())); - } - - }); - - getReferentialSynchroModel().setSynchronizeMode(ReferentialSynchronizeMode.FROM_LEFT_TO_RIGHT); - - } - - // on ecoute les modifications d'étapes pour remplir les modèles de sélection - // si nécessaire - - removePropertyChangeListener(STEP_PROPERTY_NAME, listenStepChanged); - addPropertyChangeListener(STEP_PROPERTY_NAME, listenStepChanged); - - if (log.isInfoEnabled()) { - log.info("End of start..."); - } - - // on revalide le modèle (tout est prêt) - validate(); - } - - protected void startCentralSourceModel(AdminUI ui) { - - if (!isNeedReferentielDataSource()) { - - // pas besoin de la base distante - return; - } - - // par default, on tente d'utiliser la base distance - centralSourceModel.init(ui, null); - centralSourceModel.setCanCreateLocalService(false); - boolean canUseLocalSource = getOperations().contains(AdminStep.DATA_SYNCHRONIZE) || getOperations().contains(AdminStep.REFERENTIAL_SYNCHRONIZE); - centralSourceModel.setCanUseLocalService(canUseLocalSource); - centralSourceModel.setCanUseRemoteService(true); - centralSourceModel.setCanUseServerService(true); - centralSourceModel.start(DbMode.USE_REMOTE); - - if (log.isDebugEnabled()) { - centralSourceModel.removePropertyChangeListener(LOG_PROPERTY_CHANGE_LISTENER); - centralSourceModel.addPropertyChangeListener(LOG_PROPERTY_CHANGE_LISTENER); - } - - // on teste si la connexion distante existe - if (centralSourceModel.isValid()) { - centralSourceModel.testRemote(); - } - } - - protected void startIncomingSourceModel(AdminUI ui) { - - if (!isNeedIncomingDataSource()) { - - // pas besoin de la base locale - return; - } - - ObserveSwingDataSource previousSource = getPreviousSource(); - - ObserveDataSourceConfiguration previousSourceConfig = null; - ObserveDataSourceInformation previousSourceInfo = null; - - EnumSet<DbMode> authorizedModes = getIncomingDataSourceMode(); - EnumSet<DbMode> modes = EnumSet.noneOf(DbMode.class); - - if (authorizedModes.contains(DbMode.USE_LOCAL)) { - - // ce mode est disponible uniquement si une base locale existe - if (ObserveSwingApplicationContext.get().getConfig().isLocalStorageExist()) { - modes.add(DbMode.USE_LOCAL); - } - } - - if (authorizedModes.contains(DbMode.USE_REMOTE)) { - - modes.add(DbMode.USE_REMOTE); - } - - if (authorizedModes.contains(DbMode.USE_SERVER)) { - - modes.add(DbMode.USE_SERVER); - } - - if (authorizedModes.contains(DbMode.CREATE_LOCAL)) { - - modes.add(DbMode.CREATE_LOCAL); - } - - if (previousSource != null) { - - try { - previousSourceConfig = previousSource.getConfiguration().clone(); - previousSourceInfo = previousSource.getInformation(); - } catch (CloneNotSupportedException e) { - if (log.isErrorEnabled()) { - log.error("con not clone previous data configuration", e); - } - } - - if (previousSource.isRemote()) { - - if (!modes.contains(DbMode.USE_REMOTE)) { - - // pas autorise a utiliser cette source en entree - previousSource = null; - } - } - - if (previousSource != null && previousSource.isServer()) { - - if (!modes.contains(DbMode.USE_SERVER)) { - - // pas autorise a utiliser cette source en entree - previousSource = null; - } - } - - if (previousSource != null && previousSource.isLocal()) { - - if (!modes.contains(DbMode.USE_LOCAL)) { - - // pas autorise a utiliser cette source en entree - previousSource = null; - } - } - } - - availableIncomingModes.addAll(modes); - - localSourceModel.setCanCreateLocalService(modes.contains(DbMode.CREATE_LOCAL)); - localSourceModel.setCanUseLocalService(modes.contains(DbMode.USE_LOCAL)); - localSourceModel.setCanUseRemoteService(modes.contains(DbMode.USE_REMOTE)); - localSourceModel.setCanUseServerService(modes.contains(DbMode.USE_SERVER)); - - if (previousSource == null) { - - // on intialize le modèle de la source locale à partir du service entrant (s'il existe) - localSourceModel.init(ui, null); - - } else { - - // on intialize le modèle de la source locale à partir du service entrant (s'il existe) - localSourceModel.initFromPreviousConfig(ui, previousSourceConfig, previousSourceInfo); - } - - DbMode dbMode = localSourceModel.getDbMode(); - localSourceModel.start(dbMode); - - if (log.isDebugEnabled()) { - localSourceModel.removePropertyChangeListener(LOG_PROPERTY_CHANGE_LISTENER); - localSourceModel.addPropertyChangeListener(LOG_PROPERTY_CHANGE_LISTENER); - } - } - - protected void startSelectModel() { - - if (!needSelect()) { - - // pas d'opération avec une sélection de données, rien a faire ici - return; - } - - DataSelectionModel selectionModel = getSelectionDataModel(); - - if (containsOperation(AdminStep.EXPORT_DATA)) { - - selectionModel.setUseData(true); - selectionModel.setUseOpenData(false); - selectionModel.setUseReferentiel(false); - } - - if (containsOperation(AdminStep.REPORT)) { - - selectionModel.setUseData(true); - selectionModel.setUseOpenData(true); - selectionModel.setUseReferentiel(false); - } - - if (containsOperation(AdminStep.VALIDATE)) { - - selectionModel.setUseOpenData(true); - } - - if (containsOperation(AdminStep.CONSOLIDATE)) { - - selectionModel.setUseOpenData(true); - selectionModel.setUseData(true); - selectionModel.setUseReferentiel(false); - } - - selectionModel.addPropertyChangeListener(listenSelectModified); - } - - @Override - public void destroy() { - localSourceModel.destroy(); - centralSourceModel.destroy(); - selectionDataModel.destroy(); - super.destroy(); - } - - public ObserveSwingDataSource getPreviousSource() { - return previousSource; - } - - public void setPreviousSource(ObserveSwingDataSource previousSource) { - this.previousSource = previousSource; - } - - public ObserveSwingDataSource getLocalSource() { - return localSource; - } - - public ObserveDataSourceInformation getLocalSourceInformation() { - if (localSourceInformation == null) { - - ObserveSwingDataSource localSource = getSafeLocalSource(false); - - try { - - localSourceInformation = localSource.checkCanConnect(); - - } catch (Exception e) { - //FIXME ! il faut faire quelque chose dans ce cas précis, au moins avertir l'utilisateur - if (log.isErrorEnabled()) { - log.error("unable to find local source information", e); - } - } - - } - - return localSourceInformation; - } - - public ObserveSwingDataSource getCentralSource() { - return centralSource; - } - - public ObserveSwingDataSource getSafeLocalSource(boolean open) { - if (localSource == null || open && !localSource.isOpen()) { - - localSource = createDataSource(getLocalSourceModel()); - } - if (open) { - - doOpenSource(localSource); - } - return localSource; - } - - public ObserveSwingDataSource getSafeCentralSource(boolean open) { - if (centralSource == null || open && !centralSource.isOpen()) { - - centralSource = createDataSource(getCentralSourceModel()); - } - if (open) { - doOpenSource(centralSource); - } - return centralSource; - } - - public StorageUIModel getLocalSourceModel() { - return localSourceModel; - } - - public StorageUIModel getCentralSourceModel() { - return centralSourceModel; - } - - public ValidateModel getValidateModel() { - return (ValidateModel) getStepModel(AdminStep.VALIDATE); - } - - public SynchronizeModel getSynchronizeReferentielModel() { - return (SynchronizeModel) getStepModel(AdminStep.SYNCHRONIZE); - } - - public ExportModel getExportModel() { - return (ExportModel) getStepModel(AdminStep.EXPORT_DATA); - } - - public ReportModel getReportModel() { - return (ReportModel) getStepModel(AdminStep.REPORT); - } - - public ConsolidateModel getConsolidateModel() { - return (ConsolidateModel) getStepModel(AdminStep.CONSOLIDATE); - } - - public SaveLocalModel getSaveLocalModel() { - return (SaveLocalModel) getStepModel(AdminStep.SAVE_LOCAL); - } - - public DataSynchroModel getDataSynchroModel() { - return (DataSynchroModel) getStepModel(AdminStep.DATA_SYNCHRONIZE); - } - - public ReferentialSynchroModel getReferentialSynchroModel() { - return (ReferentialSynchroModel) getStepModel(AdminStep.REFERENTIAL_SYNCHRONIZE); - } - - @Override - public void cancel() { - super.cancel(); - // on affiche l'onglet de resume si requis - AdminStep newStep = getSteps().get(getSteps().size() - 1); - if (log.isDebugEnabled()) { - log.debug("Operation canceled, will go to final step " + newStep); - } - gotoStep(newStep); - } - - @Override - public AdminUIModel addOperation(AdminStep step) { - if (AdminStep.EXPORT_DATA == step) { - - // pour exporter les données utilisateurs - // l'opération de synchronisation de référentiel est nécessaire - getOperations().add(AdminStep.SYNCHRONIZE); - - // l'opération de calcul des données est aussi obligatoire - getOperations().add(AdminStep.CONSOLIDATE); - } - - if (AdminStep.REPORT == step) { - - // l'opération de calcul des données est obligatoire - getOperations().add(AdminStep.CONSOLIDATE); - } - return (AdminUIModel) super.addOperation(step); - } - - @Override - public void removeOperation(AdminStep step) { - if (AdminStep.SYNCHRONIZE == step) { - - // pour exporter les données utilisateurs - // l'objectOperation de synchronisation de référentiel est nécessaire - getOperations().remove(AdminStep.EXPORT_DATA); - } - - if (AdminStep.CONSOLIDATE == step) { - - // pour exporter les données utilisateurs ou effectuer des reports - // l'objectOperation de calcul des données est nécessaire - getOperations().remove(AdminStep.EXPORT_DATA); - getOperations().remove(AdminStep.REPORT); - } - - super.removeOperation(step); - } - - @Override - public boolean validate(AdminStep step) { - - boolean validate = super.validate(step) && !getOperations().isEmpty(); - if (!validate) { - if (log.isDebugEnabled()) { - log.debug("not valid from generic states..."); - } - return false; - } - - DataSelectionModel selectionModel = getSelectionDataModel(); - - switch (step) { - case CONFIG: - if (isNeedIncomingDataSource()) { - if (!localSourceModel.isValid()) { - if (log.isDebugEnabled()) { - log.debug("incoming service is not valid"); - } - validate = false; - } - } - if (isNeedReferentielDataSource()) { - if (!centralSourceModel.isValid()) { - if (log.isDebugEnabled()) { - log.debug("referentiel service is not valid"); - } - validate = false; - } - } - - if (containsOperation(AdminStep.VALIDATE)) { - - // il faut avoir selectionner un context - // il faut avoir au moins selectionner un scope - if (StringUtils.isEmpty(getValidateModel().getContextName())) { - if (log.isDebugEnabled()) { - log.debug("no validation context name"); - } - return false; - } - if (getValidateModel().getScopes().isEmpty()) { - if (log.isDebugEnabled()) { - log.debug("no validation scopes"); - } - return false; - } - if (getValidateModel().getModelMode() == null) { - if (log.isDebugEnabled()) { - log.debug("no validation model mode"); - } - return false; - } - if (getValidateModel().isGenerateReport()) { - - // le fichier de rapport ne doit pas exister - File file = getValidateModel().getReportFile(); - - if (file.exists()) { - if (log.isDebugEnabled()) { - log.debug("report file already exists"); - } - return false; - } - - // le repertoire du rapport doit exister - File parentFile = file.getParentFile(); - if (parentFile == null || !parentFile.exists()) { - return false; - } - } - if (getValidateModel().getValidators().isEmpty()) { - if (log.isDebugEnabled()) { - log.debug("no validators detected"); - } - return false; - } - - // la base precedente doit etre ouverte - ObserveDataSourceInformation dataSourceInformation = getLocalSourceInformation(); - - // si le test de connection a echoue - if (dataSourceInformation == null) { - if (log.isDebugEnabled()) { - log.debug("can not connect to data source "); - } - return false; - } - - - // pour valider une base il faut les droits - if (selectionModel.isUseData()) { - - // il faut les droits en Lecture sur les donnes - if (!(dataSourceInformation.canReadData() && dataSourceInformation.canWriteData())) { - if (log.isDebugEnabled()) { - log.debug("can not read and write data"); - } - return false; - } - } - if (selectionModel.isUseReferentiel()) { - - // il faut les droits en L/E sur le referentiel - if (!(dataSourceInformation.canReadReferential() && dataSourceInformation.canWriteReferential())) { - if (log.isDebugEnabled()) { - log.debug("can not read and write referentiel"); - } - return false; - } - } - } - if (validate && containsOperation(AdminStep.DATA_SYNCHRONIZE)) { - - // les deux bases (source et referentiel) doivent etre different - DbMode dbMode = localSourceModel.getDbMode(); - if (dbMode == centralSourceModel.getDbMode()) { - switch (dbMode) { - case USE_LOCAL: - validate = false; - break; - case USE_REMOTE: - validate = !localSourceModel.getPgConfig().getJdbcUrl().equals(centralSourceModel.getPgConfig().getJdbcUrl()); - break; - case USE_SERVER: - validate = !localSourceModel.getRestConfig().getServerUrl().equals(centralSourceModel.getRestConfig().getServerUrl()); - break; - } - } - - ObserveDataSourceInformation leftDataSourceInformation = getLocalSourceInformation(); - if (!(leftDataSourceInformation.canReadData() && leftDataSourceInformation.canWriteData())) { - if (log.isDebugEnabled()) { - log.debug("can not read and write data on left data source"); - } - return false; - } - - if (centralSourceModel.getDataSourceInformation() != null) { - - ObserveDataSourceInformation rightDataSourceInformation = centralSourceModel.getDataSourceInformation(); - if (!(rightDataSourceInformation.canReadData() && rightDataSourceInformation.canWriteData())) { - if (log.isDebugEnabled()) { - log.debug("can not read and write data on right data source"); - } - return false; - } - - } - - } - - if (validate && containsOperation(AdminStep.REFERENTIAL_SYNCHRONIZE)) { - - // les deux bases (source et referentiel) doivent etre different - DbMode dbMode = localSourceModel.getDbMode(); - if (dbMode == centralSourceModel.getDbMode()) { - switch (dbMode) { - case USE_LOCAL: - validate = false; - break; - case USE_REMOTE: - validate = !localSourceModel.getPgConfig().getJdbcUrl().equals(centralSourceModel.getPgConfig().getJdbcUrl()); - break; - case USE_SERVER: - validate = !localSourceModel.getRestConfig().getServerUrl().equals(centralSourceModel.getRestConfig().getServerUrl()); - break; - } - } - - ObserveDataSourceInformation leftDataSourceInformation = getLocalSourceInformation(); - if (!(leftDataSourceInformation.canReadReferential())) { - if (log.isDebugEnabled()) { - log.debug("can not read and write referential on left data source"); - } - return false; - } - - if (centralSourceModel.getDataSourceInformation() != null) { - - ObserveDataSourceInformation rightDataSourceInformation = centralSourceModel.getDataSourceInformation(); - if (!(rightDataSourceInformation.canReadReferential())) { - if (log.isDebugEnabled()) { - log.debug("can not read and write referential on right data source"); - } - return false; - } - - } - - if (getReferentialSynchroModel().getSynchronizeMode() == null) { - return false; - } - - } - - if (containsOperation(AdminStep.SYNCHRONIZE)) { - - // les deux bases (source et referentiel) doivent etre different - DbMode dbMode = localSourceModel.getDbMode(); - if (dbMode == centralSourceModel.getDbMode()) { - if (dbMode == DbMode.USE_REMOTE) { - validate &= !localSourceModel.getPgConfig().getJdbcUrl().equals(centralSourceModel.getPgConfig().getJdbcUrl()); - } - } -// validate &= centralSourceModel.isValid(); - } - if (containsOperation(AdminStep.EXPORT_DATA)) { - - // il faut une base locale et une connexion distante - // avec des droits d'écriture de données - validate &= centralSourceModel.getDataSourceInformation() != null - && centralSourceModel.getDataSourceInformation().canWriteData(); - - } - - if (containsOperation(AdminStep.REPORT)) { - - // il faut le fichier di'mport existe - File reportFile = getReportModel().getReportFile(); - validate &= reportFile != null && - reportFile.exists(); - } - break; - case SELECT_DATA: - - if (containsOperation(AdminStep.VALIDATE)) { - - // la config doit etre ok - validate = validate(AdminStep.CONFIG); - if (validate) { - - // il faut au moins une donnee de selectionnee - boolean empty = selectionModel.isEmpty(); - validate = !empty; - } - } - if (containsOperation(AdminStep.EXPORT_DATA)) { - - // la config doit etre ok - validate &= validate(AdminStep.CONFIG); - if (validate) { - - // il faut au moins une donnee de selectionnee - boolean empty = selectionModel.isDataEmpty(); - validate = !empty; - } - } - if (containsOperation(AdminStep.CONSOLIDATE)) { - - // la config doit etre ok - validate &= validate(AdminStep.CONFIG); - if (validate) { - - // il faut au moins une donnee de selectionnee - boolean empty = selectionModel.isDataEmpty(); - validate = !empty; - } - } - if (containsOperation(AdminStep.REPORT)) { - - // la config doit etre ok - validate &= validate(AdminStep.CONFIG); - if (validate) { - - // il faut exactement une Trip de selectionnee - boolean empty = selectionModel.isDataEmpty(); - validate = !empty && - selectionModel.getSelectedData().size() == 1; - } - } - break; - case VALIDATE: - validate = validate(AdminStep.SELECT_DATA) && - getStepState(step) == WizardState.SUCCESSED; - break; - case EXPORT_DATA: - validate = validate(AdminStep.SELECT_DATA) && - getStepState(step) == WizardState.SUCCESSED; - break; - case CONSOLIDATE: - validate = validate(AdminStep.SELECT_DATA) && - getStepState(step) == WizardState.SUCCESSED; - break; - case REPORT: - - // pour acceder a l'onglet des report, il faut que - // l'onglet de sélection des données soit ok - validate = validate(AdminStep.SELECT_DATA); - break; - case SYNCHRONIZE: - validate = getStepState(step) == WizardState.SUCCESSED; - break; - case SAVE_LOCAL: - // valide si l'action a ete executee avec success - validate = !getSaveLocalModel().isDoBackup() || - getStepState(step) == WizardState.SUCCESSED; - break; - case SHOW_RESUME: - validate = true; - } - return validate; - } - - @Override - protected AdminStep[] updateStepUniverse() { - - List<AdminStep> universe = new ArrayList<>(); - - // toujours l'onglet de configuration des opérations - universe.add(AdminStep.CONFIG); - - // pour savoir si on doit ajouter l'onglet de résumé (cas par défaut) - boolean needResume = true; - if (!operations.isEmpty()) { - - if (needSelect()) { - - // ajout de l'onglet de selection des donnees - universe.add(AdminStep.SELECT_DATA); - } - - if (containsOperation(AdminStep.DATA_SYNCHRONIZE)) { - - universe.add(AdminStep.DATA_SYNCHRONIZE); - } - - if (containsOperation(AdminStep.REFERENTIAL_SYNCHRONIZE)) { - - universe.add(AdminStep.REFERENTIAL_SYNCHRONIZE); - } - - if (containsOperation(AdminStep.SYNCHRONIZE)) { - - // ajout de l'onglet de resolution des entites obsoletes - universe.add(AdminStep.SYNCHRONIZE); - } - - if (containsOperation(AdminStep.VALIDATE)) { - - // ajout de l'onglet de validation - universe.add(AdminStep.VALIDATE); - } - - if (containsOperation(AdminStep.CONSOLIDATE)) { - - // ajout de l'onglet de consolidation - universe.add(AdminStep.CONSOLIDATE); - } - - if (containsOperation(AdminStep.REPORT)) { - - universe.add(AdminStep.REPORT); - - // pas de page de resume - needResume = false; - } - - updateSaveLocalOperation(); - - if (containsOperation(AdminStep.SAVE_LOCAL)) { - - // ajout de l'onglet de sauvegarde de la base locale - universe.add(AdminStep.SAVE_LOCAL); - } - - if (containsOperation(AdminStep.EXPORT_DATA)) { - - // ajout de l'onglet de sauvegarde de la base distante - universe.add(AdminStep.EXPORT_DATA); - } - - if (needResume) { - - // ajout d'un onglet de resume - universe.add(AdminStep.SHOW_RESUME); - } - } - return universe.toArray(new AdminStep[universe.size()]); - } - - public void removeLocalSource() { - if (localSource != null) { - doCloseSource(localSource, false); - localSource = null; - localSourceInformation = null; - } - } - - public void removeCentralSource() { - if (centralSource != null) { - doCloseSource(centralSource, false); - centralSource = null; - } - } - - public void populateSelectionModel(ObserveSwingDataSource source) { - try { - DataSelectionModel.populate(getSelectionDataModel(), source); - - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error("could not populate selected model", e); - } - } finally { - - // on notifie que le modèle de sélection a changé - // (il faut donc recalculé l'arbre de sélection) - firePropertyChange(SELECTION_MODEL_CHANGED_PROPERTY_NAME, getSelectionDataModel()); - } - } - - protected void computeExistingTrips(ObserveSwingDataSource source) { - - List<DataReference<?>> existingTrip = Lists.newArrayList(); - - TripSeineService tripSeineService = source.newTripSeineService(); - DataReferenceSet<TripSeineDto> tripSeineSet = tripSeineService.getAllTripSeine(); - existingTrip.addAll(tripSeineSet.getReferences()); - - TripLonglineService tripLonglineService = source.newTripLonglineService(); - DataReferenceSet<TripLonglineDto> tripLonglineSet = tripLonglineService.getAllTripLongline(); - existingTrip.addAll(tripLonglineSet.getReferences()); - - - getExportModel().setExistingTripIds(existingTrip); - - } - - protected void updateSaveLocalOperation() { - boolean shouldAdd = false; - for (AdminStep s : operations) { - if (s.isNeedSave()) { - shouldAdd = true; - } - } - if (shouldAdd) { - - // ajout de l'operations - operations.add(AdminStep.SAVE_LOCAL); - } else { - - // on doit supprimer l'operations - operations.remove(AdminStep.SAVE_LOCAL); - } - } - - protected ObserveSwingDataSource createDataSource(StorageUIModel model) { - - ObserveSwingDataSource dataSource = storageHandler.newDataSourceFromModel(model); - return dataSource; - } - - protected void doOpenSource(ObserveSwingDataSource source) { - - if (source != null && !source.isOpen()) { - try { - source.open(); - } catch (DatabaseConnexionNotAuthorizedException | DatabaseNotFoundException | BabModelVersionException e) { - throw new IllegalStateException("Could not open " + source, e); - } - } - - } - - protected void doCloseSource(ObserveSwingDataSource source, boolean destroy) { - - if (source != null && source.isOpen()) { - if (destroy) { - try { - source.destroy(); - } catch (DatabaseDestroyNotAuthorizedException e) { - throw new IllegalStateException("Could not destroy " + source, e); - } - } else { - source.close(); - } - } - - } - - private static class LogPropertyChanged implements PropertyChangeListener { - @Override - public void propertyChange(PropertyChangeEvent evt) { - String name = evt.getPropertyName(); - Object oldValue = evt.getOldValue(); - Object newValue = evt.getNewValue(); - if (log.isDebugEnabled()) { - log.debug(evt.getSource() + " - Property [" + name + "] has changed from " + oldValue + " to " + newValue); - } - - } - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/config/ConfigUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/config/ConfigUI.jaxx deleted file mode 100644 index 56e20f7..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/config/ConfigUI.jaxx +++ /dev/null @@ -1,199 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<!-- ************************************************************* --> -<!-- L'écran de configuration des opérations de syncro a realiser --> -<!-- ************************************************************* --> - -<fr.ird.observe.ui.admin.AdminTabUI _successIcon='SwingUtil.getUIManagerActionIcon("connect_ok")' - _failedIcon='SwingUtil.getUIManagerActionIcon("connect_no")' - > - - <import> - fr.ird.observe.ui.admin.AdminUI - fr.ird.observe.ui.admin.AdminStep - fr.ird.observe.ui.admin.AdminTabUI - - jaxx.runtime.SwingUtil - java.awt.Color - - javax.swing.Icon - static org.nuiton.i18n.I18n.n - </import> - - - <fr.ird.observe.ui.admin.AdminActionModel id='stepModel' initializer='null'/> - - <fr.ird.observe.ui.storage.StorageUIModel id='localSourceModel'/> - - <fr.ird.observe.ui.storage.StorageUIModel id='centralSourceModel'/> - - <ConfigUIHandler id='handler' constructorParams='this'/> - - <script><![CDATA[ - -public ConfigUI(AdminUI parentContext) { - super(AdminStep.CONFIG, parentContext); -} - -@Override -public void initUI(AdminUI ui) { - getHandler().initTabUI(ui, this); -} - -@Override -public void addMessage(AdminStep step, String text) { - // on enregistre pas les messages pour cette étape -} -]]> - </script> - - <JPanel id='PENDING_content'> - <JPanel id='config' constraints='BorderLayout.CENTER' decorator='boxed'> - <JPanel id="configLabelPanel" constraints='BorderLayout.NORTH'> - <JLabel id="configLabel"/> - </JPanel> - <Table fill='both' - weightx='1' - insets='0' - constraints='BorderLayout.CENTER'> - <row> - <cell> - <Table id='operations' decorator='boxed' fill='both' weightx='1'> - <row> - <cell> - <JCheckBox id='SYNCHRONIZE' - onItemStateChanged='getHandler().updateOperationState((JCheckBox)event.getSource())'/> - </cell> - </row> - <row> - <cell> - <JCheckBox id='DATA_SYNCHRONIZE' - onItemStateChanged='getHandler().updateOperationState((JCheckBox)event.getSource())'/> - </cell> - </row> - <row> - <cell> - <JCheckBox id='REFERENTIAL_SYNCHRONIZE' - onItemStateChanged='getHandler().updateOperationState((JCheckBox)event.getSource())'/> - </cell> - </row> - <row> - <cell> - <JCheckBox id='VALIDATE' - onItemStateChanged='getHandler().updateOperationState((JCheckBox)event.getSource())'/> - </cell> - </row> - <row> - <cell> - <JCheckBox id='EXPORT_DATA' - onItemStateChanged='getHandler().updateOperationState((JCheckBox)event.getSource())'/> - </cell> - </row> - <row> - <cell> - <JCheckBox id='CONSOLIDATE' - onItemStateChanged='getHandler().updateOperationState((JCheckBox)event.getSource())'/> - </cell> - </row> - <row> - <cell> - <JCheckBox id='REPORT' - onItemStateChanged='getHandler().updateOperationState((JCheckBox)event.getSource())'/> - </cell> - </row> - </Table> - </cell> - </row> - - <!-- configuration de la source en entree --> - <row> - <cell fill='both'> - <Table id="localSourceConfig" insets="1"> - <row> - <cell weightx='1' fill='both'> - <JLabel id='localSourceLabel'/> - </cell> - <cell> - <JButton id='configureLocalSource' - onActionPerformed='getHandler().obtainIncomingConnexion()'/> - </cell> - <cell anchor='east'> - <JLabel id='localSourceStatus'/> - </cell> - </row> - <row> - <cell fill='both' columns="2"> - <JLabel id='localSourcePolicy'/> - </cell> - </row> - <!--row> - <cell fill='both' columns="2"> - <JLabel id='localSourceInfoLabel'/> - </cell> - </row--> - </Table> - </cell> - </row> - - <!-- configuration de la source de référence --> - <row> - <cell fill='both'> - <Table id="centralSourceConfig" insets="1"> - <row> - <cell weightx='1' fill='both'> - <JLabel id='centralSourceLabel'/> - </cell> - <cell> - <JButton id='configureCentralSource' - onActionPerformed='getHandler().obtainRemoteConnexion()'/> - </cell> - <cell anchor='east'> - <JLabel id='centralSourceStatus'/> - </cell> - </row> - <row> - <cell fill='both' columns="2"> - <JLabel id='centralSourcePolicy'/> - </cell> - </row> - <row> - <cell fill='both' columns="2"> - <JLabel id='centralSourceInfoLabel'/> - </cell> - </row> - </Table> - </cell> - </row> - - <!-- configuration supplémentaire (fournit par les opérations) --> - <row> - <cell fill='both' weightx='1' weighty='1'> - <JPanel id="extraConfig"/> - </cell> - - </row> - </Table> - </JPanel> - </JPanel> - -</fr.ird.observe.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/config/ConfigUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/config/ConfigUIHandler.java deleted file mode 100644 index 41499aa..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/config/ConfigUIHandler.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin.config; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.ObserveTextGenerator; -import fr.ird.observe.services.configuration.ObserveDataSourceInformation; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.admin.AdminStep; -import fr.ird.observe.ui.admin.AdminTabUI; -import fr.ird.observe.ui.admin.AdminTabUIHandler; -import fr.ird.observe.ui.admin.AdminUI; -import fr.ird.observe.ui.storage.StorageStep; -import fr.ird.observe.ui.storage.StorageUIHandler; -import fr.ird.observe.ui.storage.StorageUILauncher; -import fr.ird.observe.ui.storage.StorageUIModel; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JCheckBox; -import javax.swing.JLabel; -import javax.swing.JTree; -import java.awt.Window; -import java.util.Set; - -import static org.nuiton.i18n.I18n.t; - -/** - * Le controleur des onglets. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ConfigUIHandler extends AdminTabUIHandler { - - /** Logger */ - private static final Log log = LogFactory.getLog(ConfigUIHandler.class); - - public ConfigUIHandler(AdminTabUI ui) { - super(ui); - } - - public void initTabUI(AdminUI ui, ConfigUI tabUI) { - - super.initTabUI(ui, tabUI); - - if (log.isDebugEnabled()) { - log.debug("specialized for [" + tabUI.getStep() + "] for main ui " + ui.getClass().getName() + "@" + System.identityHashCode(ui)); - } - - UIHelper.setLayerUI(tabUI.getOperations(), ui.getOperationBlockLayerUI()); - UIHelper.setLayerUI(tabUI.getConfig(), ui.getConfigBlockLayerUI()); - UIHelper.setLayerUI(tabUI.getContent(), null); - } - - - public void initTabUI(AdminUI ui, SelectDataUI tabUI) { - - super.initTabUI(ui, tabUI); - - if (log.isDebugEnabled()) { - log.debug(" specialized for [" + tabUI.getStep() + "] for main ui " + ui.getClass().getName() + "@" + System.identityHashCode(ui)); - } - - UIHelper.setLayerUI(tabUI.getContent(), null); - UIHelper.setLayerUI(tabUI.getSelectTreePane(), ui.getConfigBlockLayerUI()); - - JTree tree = tabUI.getSelectTree(); - tabUI.getTreeHelper().setUI(tree, false, null); - - // customize tree selection colors - UIHelper.initUI(tabUI.getSelectTreePane(), tree); - } - - public void updateOperationState(JCheckBox checkBox) { - AdminStep op = getOperation(checkBox); - if (log.isDebugEnabled()) { - log.debug("Operation " + op + " selection has changed : selected:" + checkBox.isSelected()); - } - if (checkBox.isSelected()) { - // ajout de l'operation - getModel().addOperation(op); - } else { - // supprime cette opération - getModel().removeOperation(op); - } - } - - public String updateStorageLabel(StorageUIModel service, - boolean serviceValid, - JLabel label) { - String text; - if (serviceValid) { - - // on recupere le label du service - text = service.getLabel(); - } else { - - // aucun service configuré - text = t((String) label.getClientProperty("no")); - } - return text; - } - - public AdminStep getOperation(JCheckBox checkBox) { - return AdminStep.valueOf(checkBox.getName()); - } - - public boolean isOperationSelected(Set<AdminStep> operations, - JCheckBox checkBox) { - AdminStep scope = getOperation(checkBox); - return operations.contains(scope); - } - - public StorageUIHandler getStorageHandler() { - return ui.getContextValue(StorageUIHandler.class); - } - - public void obtainIncomingConnexion() { - StorageUIModel sourceModel = ui.getLocalSourceModel(); - StorageUILauncher.obtainConnexion(ui, ui.getParentContainer(Window.class), sourceModel); - if (log.isDebugEnabled()) { - log.debug("After modifiy source model isValid : " + sourceModel.isValid() + " / " + sourceModel.isValidStep()); - } - model.removeLocalSource(); - model.getLocalSourceModel().validate(); - model.validate(); - } - - public void obtainRemoteConnexion() { - if (log.isInfoEnabled()) { - log.info("start obtain remote connexion"); - } - StorageUIModel sourceModel = ui.getCentralSourceModel(); - StorageUILauncher.obtainConnexion(ui, ui.getParentContainer(Window.class), sourceModel); - model.removeCentralSource(); - model.getCentralSourceModel().validate(StorageStep.CONFIG); - model.validate(); - } - - protected String updateDataSourcePolicy(StorageUIModel sourceModel, boolean valid) { - String text = null; - if (valid) { - ObserveDataSourceInformation dataSourceInformation = sourceModel.getDataSourceInformation(); - - if (dataSourceInformation != null) { - - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ObserveTextGenerator textGenerator = applicationContext.getTextGenerator(); - text = textGenerator.getDataSourcePolicy(dataSourceInformation); - } - - } else { - - text = t("observe.common.storage.not.valid"); - - } - - return text; - } - - protected boolean canShowLocalStorage(Set<AdminStep> operations, - boolean needLocalStorage) { - return !operations.isEmpty() && needLocalStorage; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/config/SelectDataUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/config/SelectDataUI.jaxx deleted file mode 100644 index d6e5b71..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/config/SelectDataUI.jaxx +++ /dev/null @@ -1,87 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<!-- ************************************************************* --> -<!-- L'écran de configuration des opérations de syncro a realiser --> -<!-- ************************************************************* --> - -<fr.ird.observe.ui.admin.AdminTabUI> - - <import> - fr.ird.observe.ui.UIHelper - fr.ird.observe.ui.admin.AdminUI - fr.ird.observe.ui.admin.AdminStep - fr.ird.observe.ui.tree.ObserveTreeHelper - fr.ird.observe.ui.tree.DataSelectionTreeCellRenderer - fr.ird.observe.ui.tree.DataSelectionTreeSelectionModel - fr.ird.observe.ui.storage.tabs.DataSelectionModel - - jaxx.runtime.SwingUtil - - javax.swing.tree.TreeSelectionModel - - </import> - - <ObserveTreeHelper id='treeHelper'/> - - <ConfigUIHandler id='handler' constructorParams='this'/> - - <fr.ird.observe.ui.admin.AdminActionModel id='stepModel' initializer='null'/> - - <DataSelectionModel id='selectDataModel' - initializer='getModel().getSelectionDataModel()'/> - - <DataSelectionTreeSelectionModel id='selectionModel'/> - - <DataSelectionTreeCellRenderer id='selectionRenderer' - constraints='BorderLayout.EAST'/> - - <script><![CDATA[ -public SelectDataUI(AdminUI parentContext) { - super(AdminStep.SELECT_DATA, parentContext); -} - -public void initUI(AdminUI ui) { - getHandler().initTabUI(ui, this); -} - -@Override -public void destroy() { - selectionModel.clearSelection(); - //selectDataModel = null; - super.destroy(); -} -]]> - </script> - - <JPanel id='PENDING_content'> - - <JScrollPane id='selectTreePane' constraints='BorderLayout.CENTER' - decorator='boxed'> - - <!-- arbre de selection des exports --> - <JTree id='selectTree'/> - </JScrollPane> - </JPanel> - - -</fr.ird.observe.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/consolidate/ConsolidateModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/consolidate/ConsolidateModel.java deleted file mode 100644 index 8629c23..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/consolidate/ConsolidateModel.java +++ /dev/null @@ -1,56 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin.consolidate; - -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.ui.admin.AdminActionModel; -import fr.ird.observe.ui.admin.AdminStep; - -/** - * Modele pour preparer une validation de donnees d'une base. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.5 - */ -public class ConsolidateModel extends AdminActionModel { - - /** la source de données où effectuer la consolidation des données */ - private ObserveSwingDataSource source; - - public ConsolidateModel() { - super(AdminStep.CONSOLIDATE); - } - - public ObserveSwingDataSource getSource() { - return source; - } - - public void setSource(ObserveSwingDataSource source) { - this.source = source; - } - - @Override - public void destroy() { - super.destroy(); - source = null; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/consolidate/ConsolidateUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/consolidate/ConsolidateUI.jaxx deleted file mode 100644 index 1413c8b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/consolidate/ConsolidateUI.jaxx +++ /dev/null @@ -1,65 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<!-- ********************************************** --> -<!-- L'écran de validation des données observers --> -<!-- ********************************************** --> - -<fr.ird.observe.ui.admin.AdminTabUI> - - <import> - fr.ird.observe.ui.admin.AdminStep - fr.ird.observe.ui.admin.AdminTabUI - fr.ird.observe.ui.admin.AdminUI - </import> - - <ConsolidateUIHandler id='handler' constructorParams='this'/> - - <ConsolidateModel id='stepModel' - initializer='getModel().getConsolidateModel()'/> - - <script><![CDATA[ -public ConsolidateUI(AdminUI parentContext) { - super(AdminStep.CONSOLIDATE, parentContext); -} - -@Override -public void initUI(AdminUI ui) { - log.info("for [" + getStep() + "]"); - getHandler().initTabUI(ui, this); -} - -]]> - </script> - - <JPanel id='PENDING_content'> - <Table constraints='BorderLayout.CENTER' fill='both' weightx='1' - weighty='1'> - <row> - <cell> - <JButton id='startButton' - onActionPerformed="getHandler().startAction()"/> - </cell> - </row> - </Table> - </JPanel> -</fr.ird.observe.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/consolidate/ConsolidateUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/consolidate/ConsolidateUIHandler.java deleted file mode 100644 index c0bc1fb..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/consolidate/ConsolidateUIHandler.java +++ /dev/null @@ -1,186 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin.consolidate; - -import com.google.common.collect.ImmutableSet; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.service.actions.consolidate.ConsolidateActivitySeineDataResult; -import fr.ird.observe.services.service.actions.consolidate.ConsolidateDataService; -import fr.ird.observe.services.service.actions.consolidate.ConsolidateTripSeineDataRequest; -import fr.ird.observe.services.service.actions.consolidate.ConsolidateTripSeineDataResult; -import fr.ird.observe.ui.admin.AdminStep; -import fr.ird.observe.ui.admin.AdminTabUI; -import fr.ird.observe.ui.admin.AdminTabUIHandler; -import fr.ird.observe.ui.admin.AdminUI; -import fr.ird.observe.ui.admin.AdminUIModel; -import fr.ird.observe.ui.admin.config.SelectDataUI; -import fr.ird.observe.ui.storage.tabs.DataSelectionModel; -import jaxx.runtime.swing.wizard.ext.WizardState; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.beans.PropertyChangeListener; -import java.util.Date; -import java.util.Set; -import java.util.stream.Collectors; - -import static org.nuiton.i18n.I18n.t; - -/** - * Le controleur des onglets. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.5 - */ -public class ConsolidateUIHandler extends AdminTabUIHandler { - - /** Logger */ - private static final Log log = LogFactory.getLog(ConsolidateUIHandler.class); - - public ConsolidateUIHandler(AdminTabUI ui) { - super(ui); - } - - public ConsolidateModel getStepModel() { - return model.getConsolidateModel(); - } - - public void initTabUI(AdminUI ui, ConsolidateUI tabUI) { - - super.initTabUI(ui, tabUI); - - if (log.isDebugEnabled()) { - log.debug(" specialized for [" + tabUI.getStep() + - "] for main ui " + ui.getClass().getName() + "@" + - System.identityHashCode(ui)); - } - - tabUI.getStartButton().setText( - t("observe.actions.synchro.launch.operation", - t(tabUI.getStep().getOperationLabel()))); - - final SelectDataUI selectTabUI = (SelectDataUI) - ui.getStepUI(AdminStep.SELECT_DATA); - - PropertyChangeListener listener = evt -> { - AdminUIModel model1 = (AdminUIModel) evt.getSource(); - if (!model1.containsStep(selectTabUI.getStep())) { - // avoid multi-cast - return; - } - DataSelectionModel value = (DataSelectionModel) evt.getNewValue(); - if (log.isDebugEnabled()) { - log.debug("selection model changed to " + value); - } - updateSelectionModel(selectTabUI); - }; - tabUI.getModel().addPropertyChangeListener( - AdminUIModel.SELECTION_MODEL_CHANGED_PROPERTY_NAME, - listener - ); - } - - public void startAction() { - - addAdminWorker(((ConsolidateUI) ui).getStartButton().getToolTipText(), this::doAction); - } - - public WizardState doAction() throws Exception { - if (log.isDebugEnabled()) { - log.debug(this); - } - - WizardState init = initDB(); - - if (init != null) { - - // une erreur ou une annulation - return init; - } - Set<DataReference> trips = model.getSelectionDataModel().getSelectedData(); - ImmutableSet<String> tripIds = ImmutableSet.copyOf(trips.stream() - .filter(DataReference.newTripSeinePredicate()) - .map(DataReference.ID_FUNCTION) - .collect(Collectors.toSet())); - - ObserveSwingDataSource dataSource = getStepModel().getSource(); - - try { - - ConsolidateDataService consolidateDataService = dataSource.newConsolidateDataService(); - - ConsolidateTripSeineDataRequest request = new ConsolidateTripSeineDataRequest(); - request.setTripSeineIds(tripIds); - request.setFailIfLenghtWeightParameterNotFound(false); - - ImmutableSet<ConsolidateTripSeineDataResult> results = consolidateDataService.consolidateTripSeines(request); - - if (results.isEmpty()) { - - sendMessage(t("observe.actions.consolidate.message.noChanges")); - - } else { - - for (ConsolidateTripSeineDataResult tripSeineDataResult : results) { - - String tripSeineLabel = tripSeineDataResult.getTripSeineLabel(); - - sendMessage(t("observe.actions.consolidate.message.trip", tripSeineLabel)); - - for (ConsolidateActivitySeineDataResult activitySeineDataResult : tripSeineDataResult.getConsolidateActivitySeineDataResults()) { - - sendMessage(t("observe.actions.consolidate.message.activity", activitySeineDataResult.getActivitySeineLabel())); - - } - - } - - sendMessage(t("observe.actions.consolidate.message.save.changes", results.size())); - } - - sendMessage(t("observe.actions.consolidate.message.operation.done", - new Date())); - - } finally { - - dataSource.close(); - - } - - - return WizardState.SUCCESSED; - } - - - protected WizardState initDB() throws Exception { - - // on recupere la source de données - ObserveSwingDataSource source = model.getSafeLocalSource(false); - getStepModel().setSource(source); - - openSource(source); - - return null; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/export/ExportModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/export/ExportModel.java deleted file mode 100644 index 7023bac..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/export/ExportModel.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin.export; - -import com.google.common.collect.ImmutableList; -import com.google.common.collect.Lists; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.AbstractReference; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.ui.admin.AdminActionModel; -import fr.ird.observe.ui.admin.AdminStep; -import fr.ird.observe.ui.storage.tabs.DataSelectionModel; -import fr.ird.observe.application.swing.decoration.decorators.DataReferenceDecorator; -import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * Le modèle d'une opération d'export de données observers. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ExportModel extends AdminActionModel { - - /** les index des marées à exporter. */ - protected int[] exportDataSelectedIndex; - - /** les ids des marées déjà existante sur la base distante lors d'un export */ - protected List<DataReference<?>> existingTrips; - - /** les données exportables */ - protected List<TripEntry> data; - - protected ReferentialReferenceDecorator<ProgramDto> programDecorator; - - protected DataReferenceDecorator<TripSeineDto> tripSeineDecorator; - - protected DataReferenceDecorator<TripLonglineDto> tripLonglineDecorator; - - protected ObserveSwingDataSource source; - - protected ObserveSwingDataSource centralSource; - - public ExportModel() { - super(AdminStep.EXPORT_DATA); - } - - public void setExportDataSelectedIndex(int... exportDataSelectedIndex) { - this.exportDataSelectedIndex = exportDataSelectedIndex; - } - - public List<DataReference<?>> getExistingTrips() { - return existingTrips; - } - - public void setExistingTripIds(List<DataReference<?>> existingTrips) { - this.existingTrips = existingTrips; - } - - @Override - public void destroy() { - super.destroy(); - if (existingTrips != null) { - existingTrips.clear(); - existingTrips = null; - } - exportDataSelectedIndex = null; - tripSeineDecorator = null; - data = null; - centralSource = null; - source = null; - } - - public List<TripEntry> getData() { - return data; - } - - public void setData(DataSelectionModel selectionModel) { - - List<TripEntry> tripEntries = Lists.newArrayList(); - - for (Map.Entry<ReferentialReference<ProgramDto>, List<DataReference>> entry : selectionModel.getSelectedDataByProgram().entrySet()) { - - ReferentialReference<ProgramDto> program = entry.getKey(); - - for (DataReference trip : entry.getValue()) { - - boolean exists = existingTrips.contains(trip); - - TripEntry tripEntry = new TripEntry(program, trip, exists); - - tripEntries.add(tripEntry); - } - } - - this.data = ImmutableList.copyOf(tripEntries); - - } - - public ObserveSwingDataSource getSource() { - return source; - } - - public void setSource(ObserveSwingDataSource source) { - this.source = source; - } - - public ObserveSwingDataSource getCentralSource() { - return centralSource; - } - - public void setCentralSource(ObserveSwingDataSource centralSource) { - this.centralSource = centralSource; - } - - public void setProgramDecorator(ReferentialReferenceDecorator<ProgramDto> programDecorator) { - this.programDecorator = programDecorator; - } - - public void setTripSeineDecorator(DataReferenceDecorator<TripSeineDto> mareeDecorator) { - this.tripSeineDecorator = mareeDecorator; - } - - public void setTripLonglineDecorator(DataReferenceDecorator<TripLonglineDto> tripLonglineDecorator) { - this.tripLonglineDecorator = tripLonglineDecorator; - } - - public String decorate(AbstractReference referenceDto) { - String decor = null; - - if (ProgramDto.class.isAssignableFrom(referenceDto.getType())) { - decor = programDecorator.toString(referenceDto); - } else if (TripSeineDto.class.isAssignableFrom(referenceDto.getType())) { - decor = tripSeineDecorator.toString(referenceDto); - } else if (TripLonglineDto.class.isAssignableFrom(referenceDto.getType())) { - decor = tripLonglineDecorator.toString(referenceDto); - } - - return decor; - } - - public List<TripEntry> getSelectedTrips() { - - List<TripEntry> entries = new ArrayList<>(); - - for (int index : exportDataSelectedIndex) { - entries.add(data.get(index)); - } - return entries; - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/export/ExportUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/export/ExportUI.jaxx deleted file mode 100644 index 7b4b0a8..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/export/ExportUI.jaxx +++ /dev/null @@ -1,89 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<!-- ***************************************** --> -<!-- L'écran d'export des données observers --> -<!-- ***************************************** --> - -<fr.ird.observe.ui.admin.AdminTabUI> - <import> - fr.ird.observe.ui.admin.AdminUI - fr.ird.observe.ui.admin.AdminStep - - jaxx.runtime.swing.wizard.ext.WizardState - </import> - - - <ExportModel id='stepModel' initializer='getModel().getExportModel()'/> - - <ExportUIHandler id='handler' constructorParams='this'/> - - <!-- le modèles des activités dont on a pu calculé un point gps --> - <TripToExportTableModel id='tripsModel' onTableChanged='startAction.setEnabled(tripsModel.hasSelection())'/> - - <script><![CDATA[ -public ExportUI(AdminUI parentContext) { - super(AdminStep.EXPORT_DATA, parentContext); -} - -@Override -public void initUI(AdminUI ui) { - log.info("for [" + getStep() + "]"); - getHandler().initTabUI(ui, this); -} - -@Override -public void destroy() { - super.destroy(); - tripsModel.clear(); -} - -@Override -public void updateState(WizardState newState) { - getHandler().updateState(this, newState); -} -]]> - </script> - - <JPanel id='PENDING_content'> - <Table constraints='BorderLayout.CENTER' fill='both' weightx='1' weighty='1'> - <row> - <cell> - <JButton id="prepareAction" onActionPerformed="getHandler().doPrepareAction()"/> - </cell> - </row> - </Table> - </JPanel> - - <JPanel id='NEED_FIX_content'> - - <!-- la liste des trips --> - <JScrollPane id='tripPane' constraints='BorderLayout.CENTER'> - <JTable id='trips'/> - </JScrollPane> - - <JPanel constraints='BorderLayout.SOUTH' layout='{new BorderLayout()}'> - <JButton id='startAction' constraints='BorderLayout.CENTER' onActionPerformed="getHandler().doStartAction()"/> - </JPanel> - </JPanel> - -</fr.ird.observe.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/export/ExportUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/export/ExportUIHandler.java deleted file mode 100644 index e6df440..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/export/ExportUIHandler.java +++ /dev/null @@ -1,334 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin.export; - -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Maps; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.services.service.BabModelVersionException; -import fr.ird.observe.services.service.DatabaseConnexionNotAuthorizedException; -import fr.ird.observe.services.service.DatabaseNotFoundException; -import fr.ird.observe.services.service.actions.export.ReplicateTripService; -import fr.ird.observe.services.service.actions.export.ReplicateTripsExportRequest; -import fr.ird.observe.services.service.actions.export.ReplicateTripsExportResult; -import fr.ird.observe.services.service.actions.export.ReplicateTripsImportResult; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.admin.AdminStep; -import fr.ird.observe.ui.admin.AdminTabUI; -import fr.ird.observe.ui.admin.AdminTabUIHandler; -import fr.ird.observe.ui.admin.AdminUI; -import fr.ird.observe.ui.admin.AdminUIModel; -import fr.ird.observe.ui.admin.config.SelectDataUI; -import fr.ird.observe.ui.storage.tabs.DataSelectionModel; -import fr.ird.observe.application.swing.decoration.decorators.DataReferenceDecorator; -import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; -import jaxx.runtime.swing.editor.MyDefaultCellEditor; -import jaxx.runtime.swing.wizard.ext.WizardState; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.Date; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Le controleur des onglets. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ExportUIHandler extends AdminTabUIHandler { - - /** Logger */ - private static final Log log = LogFactory.getLog(ExportUIHandler.class); - - public ExportUIHandler(AdminTabUI ui) { - super(ui); - } - - public void initTabUI(AdminUI ui, ExportUI tabUI) { - - super.initTabUI(ui, tabUI); - - if (log.isDebugEnabled()) { - log.debug(" specialized for [" + tabUI.getStep() + "] for main ui " + ui.getClass().getName() + "@" + System.identityHashCode(ui)); - } - - tabUI.getPrepareAction().setText(t("observe.actions.synchro.prepare.operation", t(tabUI.getStep().getOperationLabel()))); - tabUI.getStartAction().setText(t("observe.actions.synchro.launch.operation", t(tabUI.getStep().getOperationLabel()))); - - final SelectDataUI selectTabUI = (SelectDataUI) ui.getStepUI(AdminStep.SELECT_DATA); - - tabUI.getModel().addPropertyChangeListener(AdminUIModel.SELECTION_MODEL_CHANGED_PROPERTY_NAME, evt -> { - AdminUIModel model1 = (AdminUIModel) evt.getSource(); -// if (!getModel().containsStep(tabUI.getStep())) { -// // avoid multi-cast -// return; -// } - - DataSelectionModel value = (DataSelectionModel) evt.getNewValue(); - if (log.isInfoEnabled()) { - log.info("selection model changed to " + value); - } - - selectTabUI.getSelectionModel().clearSelection(); - selectTabUI.getSelectionRenderer().setExistingTrips(model1.getExportModel().getExistingTrips()); - updateSelectionModel(selectTabUI); - }); - - // tableau de l'export de données - - final JTable table4 = tabUI.getTrips(); - table4.setRowHeight(24); - - UIHelper.fixTableColumnWidth(table4, 0, 20); - UIHelper.fixTableColumnWidth(table4, 3, 20); - - DefaultTableCellRenderer renderer5 = new DefaultTableCellRenderer(); - - UIHelper.setI18nTableHeaderRenderer( - table4, - n("observe.actions.exportData.table.selected"), - n("observe.actions.exportData.table.selected.tip"), - n("observe.actions.exportData.table.program.label"), - n("observe.actions.exportData.table.program.label.tip"), - n("observe.actions.exportData.table.trip.label"), - n("observe.actions.exportData.table.trip.label.tip"), - n("observe.actions.exportData.table.exist.label"), - n("observe.actions.exportData.table.exist.label.tip")); - - UIHelper.setTableColumnRenderer(table4, 0, UIHelper.newBooleanTableCellRenderer(renderer5)); - UIHelper.setTableColumnRenderer(table4, 1, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer5, ProgramDto.class)); - UIHelper.setTableColumnRenderer(table4, 2, UIHelper.newDecorateTableCellRenderer(renderer5, DataReference.class, DecoratorService.TRIP_CONTEXT)); - UIHelper.setTableColumnRenderer(table4, 3, UIHelper.newBooleanTableCellRenderer(renderer5)); - UIHelper.setTableColumnEditor(table4, 0, MyDefaultCellEditor.newBooleanEditor(false)); - - // pour tout selectionner - deselectionner dans l'entete du tableau - table4.getTableHeader().addMouseListener(new MouseAdapter() { - - @Override - public void mouseClicked(MouseEvent e) { - - int colIndex = table4.getTableHeader().columnAtPoint(e.getPoint()); - colIndex = table4.convertColumnIndexToModel(colIndex); - if (colIndex == 0) { - TripToExportTableModel model = (TripToExportTableModel) table4.getModel(); - boolean oldValue = model.isSelectAll(); - // toggle selectAll - model.setSelectAll(!oldValue); - } - } - }); - } - - public void updateState(ExportUI tabUI, WizardState newState) { - super.updateState(tabUI, newState); - if (newState == WizardState.NEED_FIX) { - // met a jour la liste des marées - tabUI.tripsModel.init(tabUI.getStepModel().getData()); - return; - } - if (newState == WizardState.RUNNING) { - - } - } - - public void doPrepareAction() { - - addAdminWorker( - ((ExportUI) ui).getPrepareAction().getToolTipText(), - this::prepareAction - ); - } - - public void doStartAction() { - - ExportUI tabUI = (ExportUI) ui; - - int[] rows = tabUI.getTripsModel().getSelected(); - tabUI.getModel().getExportModel().setExportDataSelectedIndex(rows); - - addAdminWorker( - tabUI.getStartAction().getToolTipText(), - this::doAction - ); - - } - - public WizardState prepareAction() throws Exception { - - DecoratorService decoratorProvider = getDecoratorService(); - ExportModel stepModel = model.getExportModel(); - - ReferentialReferenceDecorator<ProgramDto> pDecorator = decoratorProvider.getReferentialReferenceDecorator(ProgramDto.class); - DataReferenceDecorator<TripLonglineDto> tripLonglineDecorator = decoratorProvider.getDataReferenceDecorator(TripLonglineDto.class); - DataReferenceDecorator<TripSeineDto> tripSeineDecorator = decoratorProvider.getDataReferenceDecorator(TripSeineDto.class); - stepModel.setProgramDecorator(pDecorator); - stepModel.setTripSeineDecorator(tripSeineDecorator); - stepModel.setTripLonglineDecorator(tripLonglineDecorator); - - ObserveSwingDataSource centralSource = model.getSafeCentralSource(false); - - stepModel.setCentralSource(centralSource); - - if (!centralSource.canWriteData()) { - // l'utilisateur n'a pas le droit d'écrire sur la base distante - sendMessage(t("observe.message.can.not.write.data")); - return WizardState.FAILED; - } - - ObserveSwingDataSource source = model.getSafeLocalSource(false); - - stepModel.setSource(source); - - // ouverture de la base distante - openSource(centralSource); - - // ouverture base source - openSource(source); - - // il s'agit de la première passe : préparation des données - - sendMessage(t("observe.actions.exportData.message.prepare.data")); - - // récupération des couples (program, marees) sur la base temporaire - DataSelectionModel selectionModel = model.getSelectionDataModel(); - stepModel.setData(selectionModel); - - List<TripEntry> entries = stepModel.getData(); - - if (entries.isEmpty()) { - // pas de données possible à exporter - sendMessage(t("observe.actions.exportData.message.not.possible")); - sendMessage(t("observe.actions.operation.message.done", new Date())); - return WizardState.CANCELED; - } - - sendMessage(t("observe.actions.exportData.message.operation.needFix", new Date())); - - // on rend la main à l'ui pour que l'utilisateur selectionne les marees a exporter - return WizardState.NEED_FIX; - } - - public WizardState doAction() throws Exception { - - ExportModel stepModel = model.getExportModel(); - - // on filtre les marées sélectionnées pour export - List<TripEntry> selectedTripEntries = stepModel.getSelectedTrips(); - - ReplicateTripsImportResult results = replicateData(stepModel.getSource(), stepModel.getCentralSource(), selectedTripEntries); - - ImmutableMap<String, TripEntry> tripEntriesById = Maps.uniqueIndex(selectedTripEntries, tripEntry -> tripEntry.getTrip().getId()); - - for (ReplicateTripsImportResult.ReplicateTripImportResult result : results) { - - String tripId = result.getTripId(); - - TripEntry tripEntry = tripEntriesById.get(tripId); - - String tripDecorated = stepModel.decorate(tripEntry.getTrip()); - String programDecorated = stepModel.decorate(tripEntry.getProgram()); - - if (result.isDeleted()) { - - if (log.isInfoEnabled()) { - log.info(tripId + " → " + t("observe.actions.exportData.message.delete.remote.maree", tripDecorated, programDecorated)); - } - sendMessage(t("observe.actions.exportData.message.delete.remote.maree", tripDecorated, programDecorated)); - } - - if (log.isInfoEnabled()) { - log.info(tripId + " → " + t("observe.actions.exportData.message.replicate.maree", tripDecorated, programDecorated)); - } - sendMessage(t("observe.actions.exportData.message.replicate.maree", tripDecorated, programDecorated)); - - } - - sendMessage(t("observe.actions.operation.message.done", new Date())); - - return WizardState.SUCCESSED; - } - - private ReplicateTripsImportResult replicateData(ObserveSwingDataSource source, - ObserveSwingDataSource target, - List<TripEntry> tripEntries) throws DatabaseNotFoundException, BabModelVersionException, DatabaseConnexionNotAuthorizedException { - - Preconditions.checkState(CollectionUtils.isNotEmpty(tripEntries)); - - ReplicateTripsExportRequest.ExportTripsRequestBuilder requestBuilder = ReplicateTripsExportRequest.builder(); - - for (TripEntry tripEntry : tripEntries) { - - requestBuilder.addTripToReplicate(tripEntry.getTrip().getId(), tripEntry.isExist()); - - } - - ReplicateTripsExportRequest request = requestBuilder.build(); - - ReplicateTripsExportResult tripExportResults; - - try { - - openSource(source); - ReplicateTripService sourceReplicateService = source.newReplicateTripService(); - tripExportResults = sourceReplicateService.exportTrips(request); - - } finally { - - source.close(); - - } - - ReplicateTripsImportResult result; - - try { - - openSource(target); - ReplicateTripService targetReplicateService = target.newReplicateTripService(); - result = targetReplicateService.importTrips(tripExportResults); - - } finally { - - target.close(); - - } - - return result; - - } - - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/export/TripEntry.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/export/TripEntry.java deleted file mode 100644 index 27f2e32..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/export/TripEntry.java +++ /dev/null @@ -1,59 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin.export; - -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; - -import java.io.Serializable; - -/** Une classe qui représente une entrée dans le modèle (sans la sélection) */ -public class TripEntry implements Serializable { - - private static final long serialVersionUID = 1L; - - protected final ReferentialReference<ProgramDto> program; - - protected final DataReference trip; - - protected final boolean exist; - - public TripEntry(ReferentialReference<ProgramDto> program, DataReference trip, boolean exist) { - this.program = program; - this.trip = trip; - this.exist = exist; - } - - public ReferentialReference<ProgramDto> getProgram() { - return program; - } - - public DataReference getTrip() { - return trip; - } - - public boolean isExist() { - return exist; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/export/TripToExportTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/export/TripToExportTableModel.java deleted file mode 100644 index 7b39e6b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/export/TripToExportTableModel.java +++ /dev/null @@ -1,170 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin.export; - -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.referential.ReferentialReference; - -import javax.swing.table.AbstractTableModel; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * Le modèle pour la tableau dans l'export GPS qui contient les activités et les - * points gps calculés via le fichier gps importé. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class TripToExportTableModel extends AbstractTableModel { - - protected static final Class<?>[] COLUMN_CLASSES = { - Boolean.class, - ReferentialReference.class, //program - DataReference.class, // trip - Boolean.class - }; - - private static final long serialVersionUID = 1L; - - protected TripEntry[] data; - - protected final Set<Integer> selected; - - protected boolean selectAll; - - public TripToExportTableModel() { - selected = new HashSet<>(); - } - - @Override - public boolean isCellEditable(int rowIndex, int columnIndex) { - // seule la première colonne est éditable (selection des marées à - // exporter) - return columnIndex == 0; - } - - public int[] getSelected() { - int[] result = new int[selected.size()]; - int i = 0; - for (Integer index : selected) { - result[i++] = index; - } - return result; - } - - public boolean hasSelection() { - return !selected.isEmpty(); - } - - /** - * Initialise le modèle. - * - * @param data les entrées du modèles (program-maree-existe à distance) - */ - public void init(List<TripEntry> data) { - - this.data = data.toArray(new TripEntry[data.size()]); - - selected.clear(); - // par defaut, on selectionne toutes les references - setSelectAll(true); - } - - public void clear() { - data = null; - } - - @Override - public int getRowCount() { - return data == null ? 0 : data.length; - } - - @Override - public int getColumnCount() { - return COLUMN_CLASSES.length; - } - - @Override - public Object getValueAt(int rowIndex, int columnIndex) { - Object value = null; - TripEntry tripEntry = data == null ? null : data[rowIndex]; - if (tripEntry != null) { - switch (columnIndex) { - case 0: - value = selected.contains(rowIndex); - break; - case 1: - value = tripEntry.getProgram(); - break; - case 2: - value = tripEntry.getTrip(); - break; - case 3: - value = tripEntry.isExist(); - break; - default: - throw new IllegalStateException("can not get value for row " + rowIndex + ", col " + columnIndex); - } - } - return value; - } - - public boolean isSelectAll() { - return selectAll; - } - - public void setSelectAll(boolean selectAll) { - this.selectAll = selectAll; - if (selectAll) { - for (int i = 0, max = getRowCount(); i < max; i++) { - selected.add(i); - } - } else { - selected.clear(); - } - fireTableDataChanged(); - } - - @Override - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - if (columnIndex == 0) { - Boolean value = (Boolean) aValue; - if (value) { - selected.add(rowIndex); - if (selected.size() == getRowCount()) { - selectAll = true; - } - } else { - selected.remove(rowIndex); - if (selected.isEmpty()) { - selectAll = false; - } - } - fireTableCellUpdated(rowIndex, columnIndex); - } - - // no edit for others columns - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/report/ReportConfigUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/report/ReportConfigUI.jaxx deleted file mode 100644 index c9fe72b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/report/ReportConfigUI.jaxx +++ /dev/null @@ -1,70 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<!-- ************************************************************* --> -<!-- La configuration de l'import GPS --> -<!-- ************************************************************* --> - -<Table id="reportConfig"> - - <import> - fr.ird.observe.ui.admin.AdminUIModel - - java.io.File - - static fr.ird.observe.ui.UIHelper.getStringValue - </import> - - <ReportUIHandler id='handler' - initializer='getContextValue(ReportUIHandler.class)'/> - - <AdminUIModel id='model' initializer='getContextValue(AdminUIModel.class)'/> - - <ReportModel id='stepModel' initializer='model.getReportModel()'/> - - <script><![CDATA[ -public void destroy() { - model = null; - stepModel = null; -} - -@Override -protected void finalize() throws Throwable { - super.finalize(); - destroy(); -} -]]> - </script> - - <row> - <cell anchor="west"> - <JLabel id='reportFileLabel'/> - </cell> - <cell weightx='1' fill="horizontal"> - <JTextField id="reportFile" - onKeyReleased='stepModel.setReportFile(new File(((JTextField)event.getSource()).getText()))'/> - </cell> - <cell anchor="east"> - <JButton id="reportFileChooserAction" - onActionPerformed="getHandler().chooseReportFile()"/> - </cell> - </row> -</Table> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/report/ReportModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/report/ReportModel.java deleted file mode 100644 index 7e3b30b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/report/ReportModel.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin.report; - -import fr.ird.observe.services.dto.actions.report.Report; -import fr.ird.observe.services.service.actions.report.ReportBuilder; -import fr.ird.observe.ui.admin.AdminActionModel; -import fr.ird.observe.ui.admin.AdminStep; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.File; -import java.io.IOException; -import java.net.URL; -import java.util.List; -import java.util.Map; -import java.util.TreeMap; -import java.util.regex.Pattern; - -/** - * Le modèle utilisé pour la fonctionnalité de génération de rapport. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.3 - */ -public class ReportModel extends AdminActionModel { - - public static final String SELECTED_MAREE_PROPERTY_NAME = "selectedTrip"; - - public static final String SELECTED_REPORT_PROPERTY_NAME = "selectedReport"; - - public static final String REPORTS_PROPERTY_NAME = "reports"; - - public static final String REPORT_FILE_PROPERTY_NAME = "reportFile"; - - public static final String COPY_ROW_HEADERS_PROPERTY_NAME = "copyRowHeaders"; - - public static final String COPY_COLUMN_HEADERS_PROPERTY_NAME = "copyColumnHeaders"; - - public static final String AUTO_COPY_TO_CLIPBOARD_PROPERTY_NAME = "autoCopyToClipboard"; - - public static final String VARIABLES_PROPERTY_NAME = "variables"; - - public static final String VALID_PROPERTY_NAME = "valid"; - - public static final Pattern REPORT_DEFINITION_PATTERN = Pattern.compile("report.(\\w+).name"); - - /** Logger. */ - private static final Log log = LogFactory.getLog(ReportModel.class); - - /** la fichier contenant la définition des reports. */ - protected File reportFile; - - /** la liste des reports connus. */ - protected List<Report> reports; - - /** le report actuellement sélectionné. */ - protected Report selectedReport; - - /** les variables utilisées pour le report. */ - protected final Map<String, Object> variables; - - /** le résultat du report actuellement sélectionné */ - protected ResultTableModel resultModel; - - /** - * Un drapeau pour automatiquement copier dans le presse papier le - * tableau des résultats. - */ - protected boolean autoCopyToClipboard; - - /** Un drapeau pour savoir si la requete est executable. */ - protected Boolean valid; - - /** Pour copier les entêtes de lignes */ - protected boolean copyRowHeaders = true; - - /** Pour copier les entêtes de colonnes */ - protected boolean copyColumnHeaders = true; - - public ReportModel() { - super(AdminStep.REPORT); - variables = new TreeMap<>(); - } - - public List<Report> loadReports(URL resource) throws IOException { - - ReportBuilder builder = new ReportBuilder(); - try { - - List<Report> result = builder.load(resource); - return result; - } finally { - builder.clear(); - } - } - - public File getReportFile() { - return reportFile; - } - - public void setReportFile(File reportFile) { - Object old = this.reportFile; - this.reportFile = reportFile; - firePropertyChange(REPORT_FILE_PROPERTY_NAME, old, reportFile); - reports = null; - getReports(); - } - - public boolean isAutoCopyToClipboard() { - return autoCopyToClipboard; - } - - public void setAutoCopyToClipboard(boolean autoCopyToClipboard) { - boolean oldValue = this.autoCopyToClipboard; - this.autoCopyToClipboard = autoCopyToClipboard; - firePropertyChange(AUTO_COPY_TO_CLIPBOARD_PROPERTY_NAME, - oldValue, - autoCopyToClipboard - ); - } - - public boolean isCopyRowHeaders() { - return copyRowHeaders; - } - - public void setCopyRowHeaders(boolean copyRowHeaders) { - boolean oldValue = this.copyRowHeaders; - this.copyRowHeaders = copyRowHeaders; - firePropertyChange(COPY_ROW_HEADERS_PROPERTY_NAME, - oldValue, - copyRowHeaders - ); - } - - public boolean isCopyColumnHeaders() { - return copyColumnHeaders; - } - - public void setCopyColumnHeaders(boolean copyColumnHeaders) { - boolean oldValue = this.copyColumnHeaders; - this.copyColumnHeaders = copyColumnHeaders; - firePropertyChange(COPY_COLUMN_HEADERS_PROPERTY_NAME, - oldValue, - copyColumnHeaders - ); - } - - public ResultTableModel getResultModel() { - if (resultModel == null) { - resultModel = new ResultTableModel(); - } - return resultModel; - } - - public boolean isInit() { - return reports != null; - } - - public List<Report> getReports() { - if (reports == null && reportFile.exists()) { - - - try { - URL resource = reportFile.toURI().toURL(); - List<Report> reports = loadReports(resource); - if (log.isDebugEnabled()) { - log.debug("Add loaded " + reports.size() + " report(s)."); - } - setReports(reports); - } catch (IOException e) { - throw new IllegalStateException( - "Could not load reports definition file (" + reportFile + ").", e); - } - } - return reports; - } - - public void setReports(List<Report> reports) { - this.reports = reports; - firePropertyChange(REPORTS_PROPERTY_NAME, reports); - } - - public Report getSelectedReport() { - return selectedReport; - } - - public void setSelectedReport(Report selectedReport) { - - // suppression des variables - variables.clear(); - - // invalidation du modèle (sans déclanchement d'évènement) - valid = null; - - // changement de report - Object old = this.selectedReport; - this.selectedReport = selectedReport; - firePropertyChange(SELECTED_REPORT_PROPERTY_NAME, old, selectedReport); - } - - public Map<String, Object> getVariables() { - return variables; - } - - public boolean isValid() { - return valid != null && valid; - } - - public void setValid(boolean valid) { - Boolean old = this.valid; - this.valid = valid; - firePropertyChange(VALID_PROPERTY_NAME, old, valid); - } - - public void addVariable(String name, Object value) { - variables.put(name, value); - - // invalidation du modèle (sans déclanchement d'évènement) - valid = null; - - firePropertyChange(VARIABLES_PROPERTY_NAME, null, variables); - } - - public void resetVariables() { - variables.clear(); - firePropertyChange(VARIABLES_PROPERTY_NAME, null, variables); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/report/ReportUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/report/ReportUI.jaxx deleted file mode 100644 index af5382a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/report/ReportUI.jaxx +++ /dev/null @@ -1,122 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<!-- ********************************************** --> -<!-- L'écran d'import GPS --> -<!-- ********************************************** --> - -<fr.ird.observe.ui.admin.AdminTabUI> - <import> - fr.ird.observe.ui.UIHelper - fr.ird.observe.ui.admin.AdminStep - fr.ird.observe.ui.admin.AdminTabUI - fr.ird.observe.ui.admin.AdminUI - fr.ird.observe.services.dto.actions.report.Report - - java.awt.Dimension - - javax.swing.DefaultComboBoxModel - javax.swing.JComboBox - </import> - - <ReportUIHandler id='handler' constructorParams='this'/> - - <ReportModel id='stepModel' javaBean='getModel().getReportModel()'/> - - <ResultTableModel id='resultModel' - javaBean='getStepModel().getResultModel()'/> - - <script><![CDATA[ -public ReportUI(AdminUI parentContext) { - super(AdminStep.REPORT, parentContext); -} - -@Override -public void initUI(AdminUI ui) { - getHandler().initTabUI(ui, this); -} - -public void destroy() { - getHandler().destroy(); -} -]]> - </script> - - <JPanel id='PENDING_content'> - - <!-- le paneau du haut qui contient le sélecteur et les actions --> - <JPanel id='northPanel' constraints='BorderLayout.NORTH'> - - <JPanel id='requestSelectorPane' constraints='BorderLayout.NORTH'> - - <JToolBar id='toolbar' constraints='BorderLayout.WEST'> - - <!-- suppression de la sélection du report --> - <JButton id="resetSelectedReport" - onActionPerformed="getHandler().updateSelectedReport(null)"/> - - </JToolBar> - - <!-- selecteur de report --> - <JComboBox id='reportSelector' constraints='BorderLayout.CENTER' - onItemStateChanged='getHandler().updateSelectedReportFromEvent(event)'/> - <!--onItemStateChanged='if (event.getStateChange() == ItemEvent.SELECTED) getHandler().updateSelectedReport((Report) ((JComboBox)event.getSource()).getSelectedItem());'/>--> - - <JScrollPane id='reportDescriptionPane' - constraints='BorderLayout.SOUTH'> - <JTextArea id='reportDescription'/> - </JScrollPane> - - </JPanel> - - <!-- selecteur de variables --> - <JScrollPane id='reportVariableSelectorPane' - constraints='BorderLayout.CENTER'> - <JPanel id='reportVariableSelectorPanel'> - </JPanel> - </JScrollPane> - </JPanel> - - <!-- le tableau des résultats --> - <JScrollPane id='resultPane' constraints='BorderLayout.CENTER'> - <JTable id='resultTable'/> - </JScrollPane> - - <JPanel id="copyPane" constraints='BorderLayout.SOUTH'> - <JPanel id='copyOptions' constraints='BorderLayout.NORTH'> - <JCheckBox id='autoCopyToClipboard' - onStateChanged='getStepModel().setAutoCopyToClipboard(((JCheckBox)event.getSource()).isSelected())'/> - <JCheckBox id='copyRowHeaders' - onStateChanged='getStepModel().setCopyRowHeaders(((JCheckBox)event.getSource()).isSelected())'/> - <JCheckBox id='copyColumnHeaders' - onStateChanged='getStepModel().setCopyColumnHeaders(((JCheckBox)event.getSource()).isSelected())'/> - </JPanel> - <JButton id="copy" constraints='BorderLayout.CENTER' - onActionPerformed='getHandler().copyReportToClipBoard(getStepModel().getSelectedReport(), getResultModel(), getStepModel().isCopyRowHeaders(), - getStepModel().isCopyColumnHeaders())'/> - - </JPanel> - - </JPanel> - - -</fr.ird.observe.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/report/ReportUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/report/ReportUIHandler.java deleted file mode 100644 index f42720d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/report/ReportUIHandler.java +++ /dev/null @@ -1,504 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin.report; - -import com.google.common.collect.Lists; -import fr.ird.observe.ObserveSwingTechnicalException; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.DataDto; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.actions.report.DataMatrix; -import fr.ird.observe.services.dto.actions.report.Report; -import fr.ird.observe.services.dto.actions.report.ReportVariable; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.service.actions.report.ReportService; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.admin.AdminStep; -import fr.ird.observe.ui.admin.AdminTabUI; -import fr.ird.observe.ui.admin.AdminTabUIHandler; -import fr.ird.observe.ui.admin.AdminUI; -import fr.ird.observe.ui.admin.AdminUIModel; -import fr.ird.observe.ui.admin.config.ConfigUI; -import fr.ird.observe.ui.admin.config.SelectDataUI; -import fr.ird.observe.ui.storage.tabs.DataSelectionModel; -import jaxx.runtime.context.JAXXInitialContext; -import jaxx.runtime.swing.editor.bean.BeanComboBox; -import jaxx.runtime.swing.wizard.ext.WizardState; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.decorator.Decorator; -import org.nuiton.decorator.JXPathDecorator; -import org.nuiton.util.TimeLog; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.JComboBox; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JTable; -import javax.swing.SwingUtilities; -import javax.swing.table.DefaultTableCellRenderer; -import java.awt.Component; -import java.awt.Font; -import java.awt.event.ItemEvent; -import java.io.File; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import static org.nuiton.i18n.I18n.t; - -/** - * Le controleur des onglets. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ReportUIHandler extends AdminTabUIHandler { - - public static final String VARIABLE_NAME = "variableName"; - - /** Logger */ - private static final Log log = LogFactory.getLog(ReportUIHandler.class); - - private static final TimeLog timeLog = new TimeLog(ReportUIHandler.class, 0, 1000); - - private final Runnable revalidateTabUI; - - public ReportUIHandler(AdminTabUI ui) { - super(ui); - revalidateTabUI = () -> getUi().revalidate(); - } - - public void initTabUI(AdminUI ui, final ReportUI tabUI) { - - super.initTabUI(ui, tabUI); - - if (log.isDebugEnabled()) { - log.debug(" specialized for [" + tabUI.getStep() + - "] for main ui " + ui.getClass().getName() + - "@" + System.identityHashCode(ui)); - } - - UIHelper.setLayerUI(tabUI.getContent(), ui.getConfigBlockLayerUI()); - - ReportModel stepModel = getStepModel(); - stepModel.addPropertyChangeListener(evt -> { - - if (getModel().getModelState() == WizardState.CANCELED) { - - // action annulée, on ne declanche plus rien - return; - } - String propertyName = evt.getPropertyName(); - Object newValue = evt.getNewValue(); - - ReportModel source = (ReportModel) evt.getSource(); - - if (ReportModel.REPORTS_PROPERTY_NAME.equals(propertyName)) { - List<?> reports = (List<?>) newValue; - onReportsChanged(tabUI, reports); - } else if (ReportModel.SELECTED_REPORT_PROPERTY_NAME.equals(propertyName)) { - Report report = (Report) newValue; - onSelectedReportChanged(tabUI, source, report); - } else if (ReportModel.VARIABLES_PROPERTY_NAME.equals(propertyName)) { - Map<String, Object> variables = (Map<String, Object>) newValue; - onVariablesChanges(source, variables); - } else if (ReportModel.VALID_PROPERTY_NAME.equals(propertyName)) { - final Boolean valid = (Boolean) newValue; - SwingUtilities.invokeLater(() -> onValidChanged(source, valid != null && valid)); - - - } - }); - - tabUI.getReportSelector().setRenderer(new DefaultListCellRenderer() { - private static final long serialVersionUID = 1L; - - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - if (value == null) { - - // on affiche une message de sélection de report - value = t("observe.message.select.report"); - } - return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - } - } - - ); - // ajout du renderer sur le tableau - - DefaultTableCellRenderer renderer = new DefaultTableCellRenderer() { - private static final long serialVersionUID = 1L; - Font defaultFont; - - Font headerFont; - - public Font getDefaultFont(JTable table) { - if (defaultFont == null) { - defaultFont = table.getFont(); - } - return defaultFont; - } - - public Font getHeaderFont(JTable table) { - if (headerFont == null) { - headerFont = getDefaultFont(table).deriveFont(Font.BOLD); - } - return headerFont; - } - - @Override - public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { - Font font; - if (row == 0 || column == 0) { - - // on est sur une bordure - font = getHeaderFont(table); - } else { - font = getDefaultFont(table); - } - Component comp = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - comp.setFont(font); - return comp; - } - }; - tabUI.getResultTable().setDefaultRenderer(Object.class, renderer); - tabUI.getResultTable().setDefaultRenderer(String.class, renderer); - - // initialisation de l'ui de configuration - if (log.isInfoEnabled()) { - log.info("Init extra configuration for " + tabUI.getName()); - } - - ConfigUI configUI = (ConfigUI) ui.getStepUI(AdminStep.CONFIG); - JAXXInitialContext tx = new JAXXInitialContext().add(configUI).add(this); - - ReportConfigUI extraConfig = new ReportConfigUI(tx); - - configUI.getExtraConfig().add(extraConfig); - - final SelectDataUI selectTabUI = (SelectDataUI) ui.getStepUI(AdminStep.SELECT_DATA); - ui.getModel().addPropertyChangeListener(AdminUIModel.SELECTION_MODEL_CHANGED_PROPERTY_NAME, evt -> { - AdminUIModel model1 = (AdminUIModel) evt.getSource(); - if (!model1.containsStep(selectTabUI.getStep())) { - - // avoid multi-cast - return; - } - - DataSelectionModel value = (DataSelectionModel) evt.getNewValue(); - if (log.isDebugEnabled()) { - log.debug("selection model changed to " + value.getDatas()); - log.debug("IS USE DATA ? : " + value.isUseData()); - } - updateSelectionModel(selectTabUI); - }); - } - - public void updateSelectedReportFromEvent(ItemEvent event) { - - if (event.getStateChange() == ItemEvent.SELECTED) { - if (log.isInfoEnabled()) { - log.info("Item selected!"); - } - JComboBox<Report> source = (JComboBox<Report>) event.getSource(); - updateSelectedReport((Report) source.getSelectedItem()); - } else if (getStepModel().getSelectedReport() != null) { - - Object item = event.getItem(); - if (log.isInfoEnabled()) { - log.info("Item not selected: " + item); - } - updateSelectedReport(null); - } - } - - public void updateSelectedReport(Report report) { - getModel().setBusy(true); - try { - if (log.isInfoEnabled()) { - log.info("New selected report : " + report); - } - getStepModel().setSelectedReport(report); - - } finally { - getModel().setBusy(false); - } - } - - public String updateSelectedReportDescrption(Report report) { - if (report == null) { - return t("observe.message.no.report.selected"); - } - return t(report.getDescription()); - } - - public void updateVariable(JComboBox combo, Object value) { - String variableName = (String) combo.getClientProperty(VARIABLE_NAME); - if (variableName == null) { - throw new IllegalStateException( - "No 'variableName' clientProperty on " + combo); - } - if (log.isInfoEnabled()) { - log.info("Set variable [" + variableName + "] to value " + value); - } - getStepModel().addVariable(variableName, value); - } - - public void chooseReportFile() { - ReportModel model = getModel().getReportModel(); - File f = UIHelper.chooseFile( - ui, - t("observe.title.choose.reportFile"), - t("observe.action.choose.reportFile"), - model.getReportFile(), - "^.+\\.properties$", - t("observe.action.choose.reportFile.description")); - model.setReportFile(f); - } - - public void copyReportToClipBoard(Report report, - ResultTableModel model, - boolean copyRowHeaders, - boolean copyColumnHeaders) { - if (report == null) { - - // pas de report sélectionné, rien à faire - return; - } - - if (log.isDebugEnabled()) { - log.debug("Will copy result of report " + report.getName()); - log.debug("Result dimension : [" + model.getRowCount() + "," + - model.getColumnCount() + "]"); - } - String content = model.getClipbordContent(copyRowHeaders, copyColumnHeaders); - UIHelper.copyToClipBoard(content); - } - - protected void onReportsChanged(ReportUI tabUI, List<?> newValue) { - - if (log.isDebugEnabled()) { - log.debug("New reports : " + newValue); - } - - // on ajoute toujours une premiere valeur null (pour ne rien selectionne) - newValue.add(0, null); - - // on charge le nouveau modèle dans la liste déroulante - UIHelper.fillComboBox(tabUI.getReportSelector(), newValue, null); - } - - @SuppressWarnings({"unchecked"}) - protected void onSelectedReportChanged(ReportUI tabUI, - ReportModel model, - Report report) { - - if (log.isInfoEnabled()) { - log.info("New selected report [" + report + "]"); - } - - getModel().setBusy(true); - - try { - // on regénère l'ui de configuration des variables - JPanel variablesPanel = tabUI.getReportVariableSelectorPanel(); - variablesPanel.removeAll(); - - // on utilise les variables uniquement si nécessaire - boolean useVariables = report != null && report.isVariableRequired(); - tabUI.getReportVariableSelectorPane().setVisible(useVariables); - - // calcul des données et contruction du tableau - model.getResultModel().clear(); - - if (report != null) { - - try { - - ObserveSwingDataSource dataSource = getModel().getSafeLocalSource(true); - - ReportService reportService = dataSource.newReportService(); - - report = reportService.populateVariables(report, getModel().getSelectedTrip().getId()); - - } catch (Exception e) { - throw new ObserveSwingTechnicalException("unable to populate report : " + report.getName(), e); - } - - if (useVariables) { - - // on construit les ui pour chaqsue variable - for (ReportVariable variable : report.getVariables()) { - String variableName = variable.getName(); - // String value = variables.get(variableName); - Set values = variable.getValues(); - List<Object> universe = Lists.newArrayList(values); - BeanComboBox<Object> combo = new BeanComboBox<>(); - - combo.setShowReset(true); - variablesPanel.add(combo); - Decorator decorator; - if (ReferentialDto.class.isAssignableFrom(variable.getType()) && !universe.isEmpty()) { - decorator = getDecoratorService().getReferentialReferenceDecorator(variable.getType()); - } else if (DataDto.class.isAssignableFrom(variable.getType()) && !universe.isEmpty()) { - decorator = getDecoratorService().getDataReferenceDecorator(variable.getType()); - } else { - decorator = getDecoratorService().getDecoratorByType(variable.getType()); - } - combo.init((JXPathDecorator<Object>) decorator, universe); - JComboBox jComboBox = combo.getCombobox(); - jComboBox.putClientProperty(VARIABLE_NAME, variableName); - jComboBox.addItemListener(e -> { - - JComboBox comboBox = (JComboBox) e.getSource(); - - if (e.getStateChange() == ItemEvent.DESELECTED) { - - // ne rien faire de l'évènement de déselection - // sauf si le modèle devient vide - - if (comboBox.getSelectedItem() == null) { - updateVariable(comboBox, null); - } - return; - } - - Object o = e.getItem(); - updateVariable(comboBox, o); - }); - } - } - - // on revalide la disposition de l'onglet - SwingUtilities.invokeLater(revalidateTabUI); - - Map<String, Object> variables = model.getVariables(); - updateValidState(report, variables); - } - } finally { - - getModel().setBusy(false); - - } - } - - protected void onVariablesChanges(ReportModel model, Map<String, Object> variables) { - - Report report = model.getSelectedReport(); - if (report != null) { - - updateValidState(report, variables); - } - } - - protected void onValidChanged(ReportModel model, boolean valid) { - - if (log.isInfoEnabled()) { - log.info("valid state changed to " + valid); - } - - if (!valid) { - // calcul des données et contruction du tableau - model.getResultModel().clear(); - return; - } - - getModel().setBusy(true); - - try { - - Report report = model.getSelectedReport(); - - DataReference trip = getModel().getSelectedTrip(); - - if (log.isDebugEnabled()) { - log.debug("Build result for report [" + report.getName() + "] on " + trip); - } - - Map<String, Object> variables = model.getVariables(); - - for (ReportVariable variable : report.getVariables()) { - Object value = variables.get(variable.getName()); - variable.setSelectedValue(value); - } - - long startTime = TimeLog.getTime(); - - ObserveSwingDataSource dataSource = getModel().getSafeLocalSource(true); - if (!dataSource.isOpen()) { - dataSource.open(); - } - - ReportService reportService = dataSource.newReportService(); - - DataMatrix data = reportService.executeReport(report, trip.getId()); - - timeLog.log(startTime, "execute", report.getName()); - - if (log.isInfoEnabled()) { - log.info("Result to dispaly:\n" + data.getClipbordContent(true, true)); - } - - // calcul des données et contruction du tableau - model.getResultModel().populate(report, data); - - // mise a jour du clipboard automatique si requis - if (model.isAutoCopyToClipboard()) { - copyReportToClipBoard(report, - model.getResultModel(), - model.isCopyRowHeaders(), - model.isCopyColumnHeaders()); - } - - } catch (Exception e) { - - UIHelper.handlingError("Could not obtain report data", e); - - model.getResultModel().clear(); - - } finally { - - getModel().setBusy(false); - - } - } - - protected ReportModel getStepModel() { - return model.getReportModel(); - } - - protected void updateValidState(Report report, Map<String, Object> variables) { - - boolean canExecute = report != null && report.canExecute(variables); - getStepModel().setValid(canExecute); - } - - public void destroy() { - ObserveSwingDataSource dataSource = model.getSafeLocalSource(false); - - if (dataSource.isOpen()) { - dataSource.close(); - } - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/report/ResultTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/report/ResultTableModel.java deleted file mode 100644 index d3ffaf2..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/report/ResultTableModel.java +++ /dev/null @@ -1,199 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin.report; - -import fr.ird.observe.services.dto.actions.report.DataMatrix; -import fr.ird.observe.services.dto.actions.report.Report; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.table.AbstractTableModel; -import java.io.Serializable; - -/** - * Le modèle de tableau de résultats d'un report. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ResultTableModel extends AbstractTableModel { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(ResultTableModel.class); - - /** les données du tableaux. */ - protected transient DataMatrix data; - - public void populate(Report report, DataMatrix data) { - - if (report == null) { - - // suppression du report - clear(); - return; - } - - if (log.isInfoEnabled()) { - log.info("from report : " + report); - } - - DataMatrix allData = new DataMatrix(); - - DataMatrix rowData = null; - DataMatrix columnData = null; - int nbRows = data.getHeight(); - int nbCols = data.getWidth(); - - String[] columnNames = report.getColumnHeaders(); - String[] rowNames = report.getRowHeaders(); - - boolean withColumnHeader = columnNames != null && columnNames.length > 0; - boolean withRowHeader = rowNames != null && rowNames.length > 0; - - if (withColumnHeader) { - - // on ajoute une première ligne aux données - - nbRows += 1; - nbCols = columnNames.length; - - // les données commencent à la ligne 1 - data.setY(1); - rowData = new DataMatrix(); - rowData.setWidth(nbCols); - rowData.setHeight(1); - rowData.createData(); - for (int i = 0; i < nbCols; i++) { - String columnName = columnNames[i]; - rowData.setValue(i, 0, columnName); - } - if (withRowHeader) { - rowData.setX(1); - } - } - - if (withRowHeader) { - - // on ajoute une première colonne aux données - nbCols += 1; - nbRows = rowNames.length; - - // les données commencent à la colonne 1 - data.setX(1); - - // la matrice colonne 0 - columnData = new DataMatrix(); - columnData.setWidth(1); - columnData.setHeight(nbRows); - - columnData.createData(); - for (int i = 0; i < nbRows; i++) { - String rowName = rowNames[i]; - columnData.setValue(0, i, rowName); - } - if (withColumnHeader) { - columnData.setY(1); - nbRows += 1; - } - } - - allData.setHeight(nbRows); - allData.setWidth(nbCols); - - if (log.isInfoEnabled()) { - log.info("final data dimension : " + - allData.getDimension() + " vs " + - data.getDimension() - ); - } - - // creation de la matrice finale - allData.createData(); - - if (withRowHeader) { - - // ajout de la colonne 0 - allData.copyData(columnData); - } - - if (withColumnHeader) { - - // ajout de la ligne 0 - allData.copyData(rowData); - } - - // ajout des données réelles - allData.copyData(data); - this.data = allData; - fireTableStructureChanged(); - } - - public void clear() { - data = null; - fireTableStructureChanged(); - } - - @Override - protected void finalize() throws Throwable { - super.finalize(); - clear(); - } - - @Override - public int getRowCount() { - return data == null ? 0 : data.getHeight(); - } - - @Override - public int getColumnCount() { - return data == null ? 0 : data.getWidth(); - } - - @Override - public String getColumnName(int columnIndex) { - - // on utilise pas les colonnes du modèle de tableau (on utilise - // directement les données du tableaux que l'on va distinguer en gras) - return null; - } - - @Override - public Object getValueAt(int rowIndex, int columnIndex) { - Serializable data = this.data == null ? null : this.data.getValue(columnIndex, rowIndex); - return data; - } - - @Override - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - // les données du tableau n'est pas modifiable - } - - public String getClipbordContent(boolean copyRowHeaders, - boolean copyColumnHeaders) { - - return data == null ? "" : data.getClipbordContent(copyRowHeaders, - copyColumnHeaders - ); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/resume/ShowResumeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/resume/ShowResumeUI.jaxx deleted file mode 100644 index 67668c5..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/resume/ShowResumeUI.jaxx +++ /dev/null @@ -1,94 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<!-- **************************************** --> -<!-- L'écran de résumé des opérations passées --> -<!-- **************************************** --> - -<fr.ird.observe.ui.admin.AdminTabUI> - - <import> - fr.ird.observe.ui.UIHelper - fr.ird.observe.ui.admin.AdminUI - fr.ird.observe.ui.admin.AdminStep - fr.ird.observe.ui.admin.AdminTabUI - - java.awt.Dimension - </import> - - <ShowResumeUIHandler id='handler' constructorParams='this'/> - - <fr.ird.observe.ui.admin.AdminActionModel id='stepModel' initializer='null'/> - - <script><![CDATA[ -public ShowResumeUI(AdminUI parentContext) { - super(AdminStep.SHOW_RESUME, parentContext); -} - -@Override -public void initUI(AdminUI ui) { - getHandler().initTabUI(ui, this); -} - -@Override -public void destroy() { - super.destroy(); - globalProgression.setText(""); - resume.setText(""); -} - -@Override -public void addMessage(AdminStep step, String text) { - getHandler().addMessage(step, text); -} -]]> - </script> - - <JPanel id='PENDING_content'> - <Table constraints='BorderLayout.CENTER' fill='both' weightx='1' - weighty='1'> - <row> - <cell> - <JScrollPane id='resumePane'> - <JTextArea id='resume'/> - </JScrollPane> - </cell> - </row> - <row> - <cell> - <JScrollPane id='globalProgressionPane' - columnHeaderView='{globalProgressionTop}'> - <JTextArea id='globalProgression'/> - <JToolBar id='globalProgressionTop'> - <JLabel id='globalProgressionTopLabel'/> - <javax.swing.Box.Filler - constructorParams='UIHelper.newMinDimension(), UIHelper.newMinDimension(), UIHelper.newMaxXDimension()'/> - <JButton id="globalProgressionCopyToClipBoard" - onActionPerformed='UIHelper.copyToClipBoard(globalProgression.getText())'/> - </JToolBar> - </JScrollPane> - </cell> - </row> - </Table> - </JPanel> - -</fr.ird.observe.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/resume/ShowResumeUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/resume/ShowResumeUIHandler.java deleted file mode 100644 index b3da9b8..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/resume/ShowResumeUIHandler.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin.resume; - -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.admin.AdminStep; -import fr.ird.observe.ui.admin.AdminTabUIHandler; -import fr.ird.observe.ui.admin.AdminUI; -import jaxx.runtime.swing.wizard.ext.WizardState; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import static org.nuiton.i18n.I18n.t; - -/** - * Le controleur des onglets. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ShowResumeUIHandler extends AdminTabUIHandler { - - /** Logger */ - private static final Log log = LogFactory.getLog(ShowResumeUIHandler.class); - - public ShowResumeUIHandler(ShowResumeUI ui) { - super(ui); - } - - @Override - public ShowResumeUI getUi() { - return (ShowResumeUI) super.getUi(); - } - - public void initTabUI(AdminUI ui, ShowResumeUI tabUI) { - - super.initTabUI(ui, tabUI); - - if (log.isDebugEnabled()) { - log.debug(" specialized for [" + tabUI.getStep() + "] for main ui " + ui.getClass().getName() + "@" + System.identityHashCode(ui)); - } - - UIHelper.setLayerUI(tabUI.getContent(), null); - } - - - public void updateText() { - StringBuilder buffer = new StringBuilder(); - if (!model.isWasStarted()) { - buffer.append(t("observe.admin.resume.no.operation.done")); - } else { - for (AdminStep s : model.getOperations()) { - WizardState state = model.getStepState(s); - String stateStr = ""; - switch (state) { - case CANCELED: - stateStr = t("observe.admin.resume.operation.canceled"); - break; - case FAILED: - stateStr = t("observe.admin.resume.operation.failed"); - break; - case NEED_FIX: - stateStr = t("observe.admin.resume.operation.need.fix"); - break; - case PENDING: - stateStr = t("observe.admin.resume.operation.not.started"); - break; - case RUNNING: - stateStr = t("observe.admin.resume.operation.running"); - break; - case SUCCESSED: - stateStr = t("observe.admin.resume.operation.done"); - break; - } - buffer.append("\n\n"); - buffer.append(t(s.getLabel())); - buffer.append(" : "); - buffer.append(stateStr); - buffer.append("."); - } - buffer.append("\n\n"); - } - getUi().getResume().setText(buffer.toString()); - } - - public void addMessage(AdminStep step, String text) { - getUi().getGlobalProgression().append(t(step.getLabel()) + " - " + text + "\n"); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/save/SaveLocalModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/save/SaveLocalModel.java deleted file mode 100644 index 9b5172e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/save/SaveLocalModel.java +++ /dev/null @@ -1,140 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin.save; - -import fr.ird.observe.ui.admin.AdminActionModel; -import fr.ird.observe.ui.admin.AdminStep; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.File; -import java.util.HashSet; -import java.util.Set; - -/** - * Le modèle d'une opération d'export de données observers. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class SaveLocalModel extends AdminActionModel { - - public static final String BACKUP_FILE_PROPERTY_NAME = "backupFile"; - - public static final String DO_BACKUP_PROPERTY_NAME = "doBackup"; - - public static final String CAN_SAVE_LOCAL_PROPERTY_NAME = "canSaveLocal"; - - public static final String LOCAL_SOURCE_NEED_SAVE_PROPERTY_NAME = "localSourceNeedSave"; - - /** Logger */ - private static final Log log = LogFactory.getLog(SaveLocalModel.class); - - /** le fichier de sauvegarde de la base locale */ - protected File backupFile = new File(""); - - /** - * un drapeau pour savoir si on doit effectuer une sauvegarde de la base - * locale - */ - protected boolean doBackup; - - /** un drapeau pour savoir si la source locale doit être sauvée */ - protected boolean localSourceNeedSave; - - /** la liste des etapes qui ont demande une sauvegarde */ - protected Set<AdminStep> stepsForSave; - - public SaveLocalModel() { - super(AdminStep.SAVE_LOCAL); - } - - public boolean isLocalSourceNeedSave() { - return localSourceNeedSave; - } - - public void setLocalSourceNeedSave(boolean localSourceNeedSave) { - this.localSourceNeedSave = localSourceNeedSave; - firePropertyChange(LOCAL_SOURCE_NEED_SAVE_PROPERTY_NAME, null, - localSourceNeedSave); - } - - public boolean isDoBackup() { - return doBackup; - } - - public void setDoBackup(boolean doBackup) { - boolean canSave = isCanSaveLocal(); - boolean oldValue = this.doBackup; - this.doBackup = doBackup; - firePropertyChange(DO_BACKUP_PROPERTY_NAME, oldValue, doBackup); - firePropertyChange(CAN_SAVE_LOCAL_PROPERTY_NAME, canSave, isCanSaveLocal()); - } - - public File getBackupFile() { - return backupFile; - } - - public void setBackupFile(File backupFile) { - boolean canSave = isCanSaveLocal(); - File oldValue = this.backupFile; - this.backupFile = backupFile; - firePropertyChange(BACKUP_FILE_PROPERTY_NAME, oldValue, backupFile); - firePropertyChange(CAN_SAVE_LOCAL_PROPERTY_NAME, canSave, isCanSaveLocal()); - } - - public Set<AdminStep> getStepsForSave() { - if (stepsForSave == null) { - stepsForSave = new HashSet<>(); - } - return stepsForSave; - } - - public boolean containsStepForsave(AdminStep step) { - return stepsForSave != null && stepsForSave.contains(step); - } - - /** - * @return {@code true} si l'on peut reporter les modifications vers la base - * locale. - */ - public boolean isCanSaveLocal() { - boolean validate = !doBackup || - backupFile != null && - !backupFile.exists() && - backupFile.getName().endsWith(".sql.gz") && - backupFile.getParentFile().exists(); - - if (log.isDebugEnabled()) { - log.debug("can save ? " + validate); - } - return validate; - } - - public void addStepForSave(AdminStep step) { - getStepsForSave().add(step); - - // la sauvegarde est obligatoire - setLocalSourceNeedSave(true); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/save/SaveLocalUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/save/SaveLocalUI.jaxx deleted file mode 100644 index bee6ae2..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/save/SaveLocalUI.jaxx +++ /dev/null @@ -1,122 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<!-- ****************************************************************** --> -<!-- L'écran pour sauevegarder la base locale depuis la base de syncho --> -<!-- ****************************************************************** --> - -<fr.ird.observe.ui.admin.AdminTabUI> - - <import> - fr.ird.observe.ui.admin.AdminStep - fr.ird.observe.ui.admin.AdminUI - - jaxx.runtime.swing.CardLayout2Ext - - java.awt.Color - java.io.File - </import> - - <SaveLocalUIHandler id='handler' constructorParams='this'/> - - <SaveLocalModel id='stepModel' initializer='getModel().getSaveLocalModel()'/> - - <CardLayout2Ext id='pendingLayout' - constructorParams='this, "PENDING_content_panel"'/> - - <script><![CDATA[ -public SaveLocalUI(AdminUI parentContext) { - super(AdminStep.SAVE_LOCAL, parentContext); -} - -@Override -public void initUI(AdminUI ui) { - getHandler().initTabUI(ui, this); -} -]]> - </script> - - <JPanel id='PENDING_content'> - <Table constraints='BorderLayout.CENTER' fill='both'> - <row> - <cell fill='both'> - <JPanel background='{Color.WHITE}'> - <JLabel id="PENDING_content_label"/> - </JPanel> - </cell> - </row> - <row> - <cell fill='both' weighty='1' weightx='1'> - - <JPanel id='PENDING_content_panel'> - <JButton id="continueAction" constraints='"no"' - onActionPerformed='getHandler().skipOperation()'/> - - <JPanel layout='{new BorderLayout()}' constraints='"do"'> - - <JLabel id='needSaveText' constraints='BorderLayout.CENTER'/> - - <Table fill='both' constraints='BorderLayout.SOUTH'> - <row> - <cell columns='3'> - <JCheckBox id='doBackup' - onStateChanged='getStepModel().setDoBackup(((JCheckBox)event.getSource()).isSelected())'/> - </cell> - </row> - <row> - <cell> - <JLabel id="directoryLabel"/> - </cell> - <cell weightx='1' fill="horizontal"> - <JTextField id='directoryText' - onKeyReleased='getHandler().changeDirectory(new File(((JTextField)event.getSource()).getText()))'/> - </cell> - <cell anchor="east"> - <JButton id="backupFileChooseAction" - onActionPerformed="getHandler().chooseBackupFile()"/> - </cell> - </row> - <row> - <cell> - <JLabel id="fileLabel"/> - </cell> - <cell weightx='1' fill="horizontal" columns="2"> - <JTextField id='filenameText' - onKeyReleased='getHandler().changeFilename(((JTextField)event.getSource()).getText())'/> - </cell> - </row> - <row> - <cell fill='both' columns="3"> - <JButton id="startAction" - onActionPerformed="getHandler().doStartAction()"/> - </cell> - </row> - </Table> - </JPanel> - </JPanel> - - </cell> - </row> - </Table> - </JPanel> - -</fr.ird.observe.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/save/SaveLocalUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/save/SaveLocalUIHandler.java deleted file mode 100644 index b1aa980..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/save/SaveLocalUIHandler.java +++ /dev/null @@ -1,193 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin.save; - -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.service.AddSqlScriptProducerRequest; -import fr.ird.observe.services.service.SqlScriptProducerService; -import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeContext; -import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeEngine; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.admin.AdminStep; -import fr.ird.observe.ui.admin.AdminTabUIHandler; -import fr.ird.observe.ui.admin.AdminUI; -import fr.ird.observe.ui.admin.synchronize.referential.legacy.SynchronizeModel; -import jaxx.runtime.swing.wizard.ext.WizardState; -import org.apache.commons.io.IOUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.io.File; -import java.io.FileOutputStream; -import java.util.Date; - -import static org.nuiton.i18n.I18n.t; - -/** - * Le controleur des onglets. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class SaveLocalUIHandler extends AdminTabUIHandler { - - /** Logger */ - private static final Log log = LogFactory.getLog(SaveLocalUIHandler.class); - - private static final String UPDATE_VERSION_PATTERN = - "UPDATE %1$s SET topiaversion = %2$d WHERE topiaid='%3$s';\n"; - - protected ObserveSwingDataSource source; - - public SaveLocalUIHandler(SaveLocalUI ui) { - super(ui); - } - - @Override - public SaveLocalUI getUi() { - return (SaveLocalUI) super.getUi(); - } - - public void initTabUI(AdminUI ui, SaveLocalUI tabUI) { - - super.initTabUI(ui, tabUI); - - if (log.isDebugEnabled()) { - log.debug(" specialized for [" + tabUI.getStep() + "] for main ui " + ui.getClass().getName() + "@" + System.identityHashCode(ui)); - } - - String message = t("observe.actions.synchro.launch.operation", t(tabUI.getStep().getOperationLabel())); - tabUI.getStartAction().setText(message); - - } - - public void updateText() { - String text = ""; - if (getUi().getStepModel().containsStepForsave(AdminStep.SYNCHRONIZE)) { - text = t("observe.actions.synchro.referential.message.need.save.for.synchro.operation"); - text += "\n\n"; - } - if (getUi().getStepModel().containsStepForsave(AdminStep.VALIDATE)) { - text = t("observe.actions.synchro.referential.message.need.save.for.validation.operation"); - text += "\n\n"; - } - getUi().needSaveText.setText(text); - } - - public String updateText(boolean localSourceNeedSave) { - return localSourceNeedSave ? t("observe.actions.synchro.referential.message.synchro.local.modification") : t("observe.actions.synchro.referential.message.no.local.modification"); - } - - public void skipOperation() { - sendMessage(t("observe.actions.synchro.referential.message.saveLocal.skip")); - getModel().setStepState(AdminStep.SAVE_LOCAL, WizardState.SUCCESSED); -// getUi().getProgression().setText(t("observe.synchro.message.saveLocal.skip")); - // on passe directement à l'opération suivante - if (model.getNextStep() != null) { - model.gotoNextStep(); - } - } - - public void chooseBackupFile() { - File f = UIHelper.chooseDirectory( - getUi(), - t("observe.title.choose.db.dump.directory"), - t("observe.action.choose.db.dump.directory"), - new File(getUi().directoryText.getText()) - ); - changeDirectory(f); - } - - public void changeDirectory(File f) { - getUi().getStepModel().setBackupFile(new File(f, getUi().filenameText.getText())); - } - - public void changeFilename(String filename) { - getUi().getStepModel().setBackupFile(new File(getUi().directoryText.getText(), filename)); - } - - public void doStartAction() { - - addAdminWorker(getUi().getStartAction().getToolTipText(), this::doAction); - - } - - public WizardState doAction() throws Exception { - if (log.isDebugEnabled()) { - log.debug(this); - } - - source = model.getSafeLocalSource(false); - - SaveLocalModel stepModel = model.getSaveLocalModel(); - if (!stepModel.isLocalSourceNeedSave()) { - sendMessage("Aucune modification sur la base locale, opération non requise."); - // pas de modification sur la base locale - return WizardState.SUCCESSED; - } - - openSource(source); - - if (stepModel.isDoBackup()) { - - sendMessage("Sauvegarde de la base locale vers " + stepModel.getBackupFile()); - - // on effectue une sauvegarde de la base locale - File backupFile = stepModel.getBackupFile(); - - SqlScriptProducerService dumpService = source.newSqlScriptProducerService(); - AddSqlScriptProducerRequest request = AddSqlScriptProducerRequest.forH2().addSchema().addReferential().addAllData(); - byte[] dump = dumpService.produceAddSqlScript(request); - - try (FileOutputStream outputStream = new FileOutputStream(backupFile)) { - IOUtils.write(dump, outputStream); - } - - } - - if (stepModel.containsStepForsave(AdminStep.SYNCHRONIZE)) { - - sendMessage("Sauvegarde du référentiel."); - saveUnidirectionalSynchronizeReferential(); - } - - sendMessage(t("observe.actions.operation.message.done", new Date())); - - return WizardState.SUCCESSED; - } - - public void saveUnidirectionalSynchronizeReferential() { - - SynchronizeModel stepModel = getModel().getSynchronizeReferentielModel(); - - UnidirectionalReferentialSynchronizeEngine engine = stepModel.getEngine(); - - UnidirectionalReferentialSynchronizeContext referentialSynchronizeContext = stepModel.getReferentialSynchronizeContext(); - - engine.finish(referentialSynchronizeContext); - - - sendMessage(t("observe.actions.synchro.referential.message.apply.done", new Date())); - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/DataSynchroModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/DataSynchroModel.java deleted file mode 100644 index d77f8d6..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/DataSynchroModel.java +++ /dev/null @@ -1,119 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.data; - -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.ui.admin.AdminActionModel; -import fr.ird.observe.ui.admin.AdminStep; -import fr.ird.observe.ui.admin.synchronize.data.task.DataSynchronizeTaskSupport; -import fr.ird.observe.ui.storage.tabs.DataSelectionModel; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.DefaultListModel; - -/** - * Created on 02/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class DataSynchroModel extends AdminActionModel { - - /** Logger. */ - private static final Log log = LogFactory.getLog(DataSynchroModel.class); - - public static final String LEFT_SOURCE_PROPERTY_NAME = "leftSource"; - public static final String RIGHT_SOURCE_PROPERTY_NAME = "rightSource"; - public static final String TASKS_PROPERTY_NAME = "tasks"; - - public static final String LEFT_SELECTION_MODEL_CHANGED_PROPERTY_NAME = "leftSelectionModelChanged"; - public static final String RIGHT_SELECTION_MODEL_CHANGED_PROPERTY_NAME = "rightSelectionModelChanged"; - - /** la source sur le panneau de gauche. */ - protected ObserveSwingDataSource leftSource; - - /** la source sur le panneau de droite. */ - protected ObserveSwingDataSource rightSource; - - /** les données sélectionnées sur le panneau de gauche. */ - protected final DataSelectionModel leftSelectionDataModel; - - /** les données sélectionnées sur le panneau de droite. */ - protected final DataSelectionModel rightSelectionDataModel; - - protected final DefaultListModel<DataSynchronizeTaskSupport> tasks; - - public DataSynchroModel() { - super(AdminStep.DATA_SYNCHRONIZE); - - leftSelectionDataModel = new DataSelectionModel(); - leftSelectionDataModel.setUseData(true); - - rightSelectionDataModel = new DataSelectionModel(); - rightSelectionDataModel.setUseData(true); - tasks = new DefaultListModel<>(); - - } - - public ObserveSwingDataSource getLeftSource() { - return leftSource; - } - - public void setLeftSource(ObserveSwingDataSource leftSource) { - this.leftSource = leftSource; - firePropertyChange(LEFT_SOURCE_PROPERTY_NAME, leftSource); - } - - public ObserveSwingDataSource getRightSource() { - return rightSource; - } - - public void setRightSource(ObserveSwingDataSource rightSource) { - this.rightSource = rightSource; - firePropertyChange(RIGHT_SOURCE_PROPERTY_NAME, rightSource); - } - - public DataSelectionModel getLeftSelectionDataModel() { - return leftSelectionDataModel; - } - - public DataSelectionModel getRightSelectionDataModel() { - return rightSelectionDataModel; - } - - public void populateLeftSelectionModel() { - populateSelectionModel(leftSource, leftSelectionDataModel, LEFT_SELECTION_MODEL_CHANGED_PROPERTY_NAME); - } - - public void populateRightSelectionModel() { - populateSelectionModel(rightSource, rightSelectionDataModel, RIGHT_SELECTION_MODEL_CHANGED_PROPERTY_NAME); - } - - public DefaultListModel<DataSynchronizeTaskSupport> getTasks() { - return tasks; - } - - public void addTask(DataSynchronizeTaskSupport task) { - tasks.addElement(task); - } - - private void populateSelectionModel(ObserveSwingDataSource dataSource, DataSelectionModel selectionDataModel, String propertyName) { - - try { - - DataSelectionModel.populate(selectionDataModel, dataSource); - - } catch (Exception e) { - - if (log.isErrorEnabled()) { - log.error("could not populate selected model", e); - } - - } finally { - - // on notifie que le modèle de sélection a changé - // (il faut donc recalculé l'arbre de sélection) - firePropertyChange(propertyName, selectionDataModel); - - } - } -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/DataSynchroUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/DataSynchroUI.jaxx deleted file mode 100644 index 014ed8c..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/DataSynchroUI.jaxx +++ /dev/null @@ -1,139 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<!-- ************************************************************* --> -<!-- L'écran de synchronisation bi-directionnel des données --> -<!-- ************************************************************* --> - -<fr.ird.observe.ui.admin.AdminTabUI> - - <import> - fr.ird.observe.ui.UIHelper - fr.ird.observe.ui.admin.AdminUI - fr.ird.observe.ui.admin.AdminStep - fr.ird.observe.ui.tree.ObserveTreeHelper - fr.ird.observe.ui.tree.DataSelectionTreeCellRenderer - fr.ird.observe.ui.tree.DataSelectionTreeSelectionModel - fr.ird.observe.ui.storage.tabs.DataSelectionModel - - jaxx.runtime.SwingUtil - - javax.swing.ListSelectionModel - javax.swing.tree.TreeSelectionModel - - </import> - - <ObserveTreeHelper id='leftTreeHelper'/> - <ObserveTreeHelper id='rightTreeHelper'/> - - <DataSynchroUIHandler id='handler' constructorParams='this'/> - - <DataSynchroModel id='stepModel' initializer='getModel().getDataSynchroModel()'/> - - <DataSelectionModel id='leftSelectDataModel' - initializer='getModel().getDataSynchroModel().getLeftSelectionDataModel()'/> - <DataSelectionTreeSelectionModel id='leftSelectionModel'/> - - <DataSelectionModel id='rightSelectDataModel' - initializer='getModel().getDataSynchroModel().getRightSelectionDataModel()'/> - <DataSelectionTreeSelectionModel id='rightSelectionModel'/> - <JPanel id='invisiblePanel'> - <DataSelectionTreeCellRenderer id='leftSelectionRenderer'/> - <DataSelectionTreeCellRenderer id='rightSelectionRenderer'/> - </JPanel> - - <script><![CDATA[ -public DataSynchroUI(AdminUI parentContext) { - super(AdminStep.DATA_SYNCHRONIZE, parentContext); -} - -public void initUI(AdminUI ui) { - getHandler().initTabUI(ui, this); -} - -@Override -public void destroy() { - leftSelectionModel.clearSelection(); - rightSelectionModel.clearSelection(); - super.destroy(); -} -]]> - </script> - - <JPanel id='PENDING_content'> - <Table constraints='BorderLayout.CENTER' fill='both' weightx='1' - weighty='1'> - <row> - <cell> - <JButton id='startAction' onActionPerformed="getHandler().doStartAction()"/> - </cell> - </row> - </Table> - </JPanel> - <JPanel id='NEED_FIX_content'> - <JSplitPane id="contentSplitPane" constraints='BorderLayout.CENTER'> - <Table id='contentNorth' fill="both" weighty="1"> - <row> - <cell weightx="0.45"> - <JScrollPane id='leftTreePane' decorator='boxed'> - <JTree id='leftTree'/> - </JScrollPane> - </cell> - <cell weightx="0.1"> - <JPanel layout="{new BorderLayout()}" border='{new TitledBorder(" ")}'> - <JPanel id="middleActions" layout="{new GridLayout(0, 2)}" constraints='BorderLayout.CENTER'> - <JButton id="copyToRight" onActionPerformed="getHandler().addCopyToRightTasks()"/> - <JButton id="copyToLeft" onActionPerformed="getHandler().addCopyToLeftTasks()"/> - <JButton id="deleteFromLeft" onActionPerformed="getHandler().addDeleteFromLeftTasks()"/> - <JButton id="deleteFromRight" onActionPerformed="getHandler().addDeleteFromRightTasks()"/> - </JPanel> - </JPanel> - </cell> - <cell weightx="0.45"> - <JScrollPane id='rightTreePane' decorator='boxed'> - <JTree id='rightTree'/> - </JScrollPane> - </cell> - </row> - </Table> - <Table id='contentSouth' fill="both"> - <row weighty="1"> - <cell weightx="1"> - <JScrollPane id='actionsToConsumePane'> - <JList id="actionsToConsume"/> - </JScrollPane> - </cell> - </row> - <row> - <cell> - <JPanel layout="{new BorderLayout()}"> - <JButton id='applyAction' constraints='BorderLayout.CENTER' - onActionPerformed='getHandler().doExecuteAction()'/> - </JPanel> - </cell> - </row> - </Table> - </JSplitPane> - - </JPanel> - -</fr.ird.observe.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/DataSynchroUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/DataSynchroUIHandler.java deleted file mode 100644 index 7822ef3..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/DataSynchroUIHandler.java +++ /dev/null @@ -1,301 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.data; - -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaH2; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.service.actions.synchro.data.DataSynchronizeRequest; -import fr.ird.observe.services.service.actions.synchro.data.DataSynchronizeService; -import fr.ird.observe.services.service.actions.synchro.data.task.DataSynchronizeCopyTask; -import fr.ird.observe.services.service.actions.synchro.data.task.DataSynchronizeDeleteTask; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.admin.AdminStep; -import fr.ird.observe.ui.admin.AdminTabUI; -import fr.ird.observe.ui.admin.AdminTabUIHandler; -import fr.ird.observe.ui.admin.AdminUI; -import fr.ird.observe.ui.admin.config.ConfigUI; -import fr.ird.observe.ui.admin.synchronize.data.task.CopyToLeftDataSynchronizeTask; -import fr.ird.observe.ui.admin.synchronize.data.task.CopyToRightDataSynchronizeTask; -import fr.ird.observe.ui.admin.synchronize.data.task.DataSynchronizeTaskSupport; -import fr.ird.observe.ui.admin.synchronize.data.task.DeleteFromLeftDataSynchronizeTask; -import fr.ird.observe.ui.admin.synchronize.data.task.DeleteFromRightDataSynchronizeTask; -import fr.ird.observe.ui.storage.tabs.DataSelectionModel; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import jaxx.runtime.swing.wizard.ext.WizardState; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.DefaultListModel; -import javax.swing.border.TitledBorder; -import java.util.List; -import java.util.Map; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 02/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class DataSynchroUIHandler extends AdminTabUIHandler { - - /** Logger */ - private static final Log log = LogFactory.getLog(DataSynchroUIHandler.class); - - public DataSynchroUIHandler(DataSynchroUI ui) { - super(ui); - } - - public DataSynchroModel getStepModel() { - return model.getDataSynchroModel(); - } - - @Override - public DataSynchroUI getUi() { - return (DataSynchroUI) super.getUi(); - } - - @Override - public void updateState(AdminTabUI ui, WizardState newState) { - super.updateState(ui, newState); - } - - public void initTabUI(AdminUI ui, DataSynchroUI tabUI) { - - super.initTabUI(ui, tabUI); - - if (log.isDebugEnabled()) { - log.debug(" specialized for [" + tabUI.getStep() + "] for main ui " + ui.getClass().getName() + "@" + System.identityHashCode(ui)); - } - - getStepModel().getLeftSelectionDataModel().addPropertyChangeListener(evt -> { - - DataSelectionModel model = (DataSelectionModel) evt.getSource(); - boolean withDataSelected = !model.isDataEmpty(); - - tabUI.getCopyToRight().setEnabled(withDataSelected); - tabUI.getDeleteFromLeft().setEnabled(withDataSelected); - - }); - getStepModel().getRightSelectionDataModel().addPropertyChangeListener(evt -> { - - DataSelectionModel model = (DataSelectionModel) evt.getSource(); - boolean withDataSelected = !model.isDataEmpty(); - - tabUI.getCopyToLeft().setEnabled(withDataSelected); - tabUI.getDeleteFromRight().setEnabled(withDataSelected); - - }); - - UIHelper.initUI(tabUI.getLeftTreePane(), tabUI.getLeftTree()); - UIHelper.initUI(tabUI.getRightTreePane(), tabUI.getRightTree()); - - } - - public void doStartAction() { - - addAdminWorker(getUi().getStartAction().getToolTipText(), this::doStartAction0); - - } - - private WizardState doStartAction0() { - - DataSynchroUI tabUI = getUi(); - DataSynchroModel stepModel = getStepModel(); - ConfigUI configUI = (ConfigUI) parentUI.getStepUI(AdminStep.CONFIG); - - ObserveSwingDataSource leftSource = getModel().getSafeLocalSource(true); - stepModel.setLeftSource(leftSource); - - ObserveSwingDataSource rightSource = getModel().getSafeCentralSource(true); - stepModel.setRightSource(rightSource); - - tabUI.getLeftTreePane().setBorder(new TitledBorder(getModel().getLocalSourceModel().getLabel())); - stepModel.populateLeftSelectionModel(); - updateSelectionModel(tabUI, tabUI.getLeftTreeHelper(), tabUI.getLeftTree(), leftSource, stepModel.getLeftSelectionDataModel(), tabUI.getLeftSelectionModel()); - sendMessage(t("observe.actions.synchro.referential.message.data.leftData.loaded")); - - configUI.getLocalSourceConfig().setBorder(new TitledBorder(getModel().getLocalSourceLabel())); - - tabUI.getRightTreePane().setBorder(new TitledBorder(getModel().getCentralSourceModel().getLabel())); - stepModel.populateRightSelectionModel(); - updateSelectionModel(tabUI, tabUI.getRightTreeHelper(), tabUI.getRightTree(), rightSource, stepModel.getRightSelectionDataModel(), tabUI.getRightSelectionModel()); - sendMessage(t("observe.actions.synchro.referential.message.data.rightData.loaded")); - - configUI.getCentralSourceConfig().setBorder(new TitledBorder(getModel().getCentralSourceLabel())); - - return WizardState.NEED_FIX; - - } - - public void addCopyToLeftTasks() { - - DataSelectionModel rightSelectionDataModel = getStepModel().getRightSelectionDataModel(); - DataSelectionModel leftSelectionDataModel = getStepModel().getLeftSelectionDataModel(); - ObserveTreeHelper rightTreeHelper = getUi().getRightTreeHelper(); - ObserveTreeHelper leftTreeHelper = getUi().getLeftTreeHelper(); - Map<ReferentialReference<ProgramDto>, List<DataReference>> selectedDataByProgram = rightSelectionDataModel.getSelectedDataByProgram(); - rightSelectionDataModel.removeAllSelectedData(); - for (Map.Entry<ReferentialReference<ProgramDto>, List<DataReference>> entry : selectedDataByProgram.entrySet()) { - ReferentialReference<ProgramDto> program = entry.getKey(); - for (DataReference trip : entry.getValue()) { - boolean tripExistOnLeft = leftSelectionDataModel.containsData(program, trip); - getStepModel().addTask(new CopyToLeftDataSynchronizeTask(program, trip, tripExistOnLeft)); - rightTreeHelper.removeTrip(program, trip); - rightSelectionDataModel.removeTrip(program, trip); - - if (tripExistOnLeft) { - leftTreeHelper.removeTrip(program, trip); - leftSelectionDataModel.removeTrip(program, trip); - } - } - } - - - } - - public void addCopyToRightTasks() { - - DataSelectionModel leftSelectionDataModel = getStepModel().getLeftSelectionDataModel(); - DataSelectionModel rightSelectionDataModel = getStepModel().getRightSelectionDataModel(); - ObserveTreeHelper leftTreeHelper = getUi().getLeftTreeHelper(); - ObserveTreeHelper rightTreeHelper = getUi().getRightTreeHelper(); - Map<ReferentialReference<ProgramDto>, List<DataReference>> selectedDataByProgram = leftSelectionDataModel.getSelectedDataByProgram(); - leftSelectionDataModel.removeAllSelectedData(); - for (Map.Entry<ReferentialReference<ProgramDto>, List<DataReference>> entry : selectedDataByProgram.entrySet()) { - ReferentialReference<ProgramDto> program = entry.getKey(); - for (DataReference trip : entry.getValue()) { - - boolean tripExistOnRight = rightSelectionDataModel.containsData(program, trip); - getStepModel().addTask(new CopyToRightDataSynchronizeTask(program, trip, tripExistOnRight)); - leftTreeHelper.removeTrip(program, trip); - leftSelectionDataModel.removeTrip(program, trip); - - if (tripExistOnRight) { - rightTreeHelper.removeTrip(program, trip); - rightSelectionDataModel.removeTrip(program, trip); - } - } - } - - } - - public void addDeleteFromLeftTasks() { - - DataSelectionModel selectionDataModel = getStepModel().getLeftSelectionDataModel(); - ObserveTreeHelper treeHelper = getUi().getLeftTreeHelper(); - Map<ReferentialReference<ProgramDto>, List<DataReference>> selectedDataByProgram = selectionDataModel.getSelectedDataByProgram(); - selectionDataModel.removeAllSelectedData(); - for (Map.Entry<ReferentialReference<ProgramDto>, List<DataReference>> entry : selectedDataByProgram.entrySet()) { - ReferentialReference<ProgramDto> program = entry.getKey(); - for (DataReference trip : entry.getValue()) { - getStepModel().addTask(new DeleteFromLeftDataSynchronizeTask(program, trip)); - treeHelper.removeTrip(program, trip); - selectionDataModel.removeTrip(program, trip); - } - } - - } - - public void addDeleteFromRightTasks() { - - DataSelectionModel selectionDataModel = getStepModel().getRightSelectionDataModel(); - ObserveTreeHelper treeHelper = getUi().getRightTreeHelper(); - Map<ReferentialReference<ProgramDto>, List<DataReference>> selectedDataByProgram = selectionDataModel.getSelectedDataByProgram(); - selectionDataModel.removeAllSelectedData(); - for (Map.Entry<ReferentialReference<ProgramDto>, List<DataReference>> entry : selectedDataByProgram.entrySet()) { - ReferentialReference<ProgramDto> program = entry.getKey(); - for (DataReference trip : entry.getValue()) { - getStepModel().addTask(new DeleteFromRightDataSynchronizeTask(program, trip)); - treeHelper.removeTrip(program, trip); - selectionDataModel.removeTrip(program, trip); - } - } - - } - - public void doExecuteAction() { - - ObserveSwingDataSource leftSource = getStepModel().getLeftSource(); - boolean leftSourceIsH2 = leftSource.getConfiguration() instanceof ObserveDataSourceConfigurationTopiaH2; - - ObserveSwingDataSource rightSource = getStepModel().getRightSource(); - boolean rightSourceIsH2 = rightSource.getConfiguration() instanceof ObserveDataSourceConfigurationTopiaH2; - - DefaultListModel<DataSynchronizeTaskSupport> tasks = getStepModel().getTasks(); - int size = tasks.size(); - - DecoratorService decoratorService = getDecoratorService(); - ReferentialReferenceDecorator<ProgramDto> programDecorator = decoratorService.getReferentialReferenceDecorator(ProgramDto.class); - - DataSynchronizeRequest.Builder leftDataSynchronizeRequestBuilder = DataSynchronizeRequest.builder(leftSourceIsH2, rightSourceIsH2); - DataSynchronizeRequest.Builder rightDataSynchronizeRequestBuilder = DataSynchronizeRequest.builder(rightSourceIsH2, leftSourceIsH2); - for (int i = 0; i < size; i++) { - - DataSynchronizeTaskSupport task = tasks.getElementAt(i); - - String programStr = programDecorator.toString(task.getProgram()); - String tripStr = decoratorService.getTripReferenceDecorator(task.getTrip()).toString(task.getTrip()); - - if (task instanceof DeleteFromLeftDataSynchronizeTask) { - - sendMessage(t("observe.actions.synchro.data.prepare.deleteFromLeftTask", programStr, tripStr)); - leftDataSynchronizeRequestBuilder.addDeleteTask(new DataSynchronizeDeleteTask(task.getProgram().getId(), task.getTrip().getId())); - continue; - } - - if (task instanceof DeleteFromRightDataSynchronizeTask) { - sendMessage(t("observe.actions.synchro.data.prepare.deleteFromRightTask", programStr, tripStr)); - rightDataSynchronizeRequestBuilder.addDeleteTask(new DataSynchronizeDeleteTask(task.getProgram().getId(), task.getTrip().getId())); - continue; - } - - if (task instanceof CopyToLeftDataSynchronizeTask) { - CopyToLeftDataSynchronizeTask task1 = (CopyToLeftDataSynchronizeTask) task; - if (task1.isTripExistOnLeft()) { - sendMessage(t("observe.actions.synchro.data.prepare.deleteFromLeftTask", programStr, tripStr)); - leftDataSynchronizeRequestBuilder.addDeleteTask(new DataSynchronizeDeleteTask(task.getProgram().getId(), task.getTrip().getId())); - } - sendMessage(t("observe.actions.synchro.data.prepare.copyToLeftTask", programStr, tripStr)); - leftDataSynchronizeRequestBuilder.addCopyTask(new DataSynchronizeCopyTask(task.getProgram().getId(), task.getTrip().getId())); - continue; - } - - if (task instanceof CopyToRightDataSynchronizeTask) { - CopyToRightDataSynchronizeTask task1 = (CopyToRightDataSynchronizeTask) task; - if (task1.isTripExistOnRight()) { - sendMessage(t("observe.actions.synchro.data.prepare.deleteFromRightTask", programStr, tripStr)); - rightDataSynchronizeRequestBuilder.addDeleteTask(new DataSynchronizeDeleteTask(task.getProgram().getId(), task.getTrip().getId())); - } - sendMessage(t("observe.actions.synchro.data.prepare.copyToRightTask", programStr, tripStr)); - rightDataSynchronizeRequestBuilder.addCopyTask(new DataSynchronizeCopyTask(task.getProgram().getId(), task.getTrip().getId())); - } - - } - - DataSynchronizeService leftDataSynchronizeService = leftSource.newDataSynchronizeService(); - DataSynchronizeService rightDataSynchronizeService = rightSource.newDataSynchronizeService(); - - DataSynchronizeRequest leftDataSynchronizeRequest = leftDataSynchronizeRequestBuilder.build(); - if (leftDataSynchronizeRequest.isNotEmpty()) { - byte[][] copySqlCodes = rightDataSynchronizeService.getCopySqlCodes(leftDataSynchronizeRequest); - byte[][] deleteSqlCodes = leftDataSynchronizeService.getDeleteSqlCodes(leftDataSynchronizeRequest); - leftDataSynchronizeService.executeRequest(copySqlCodes, deleteSqlCodes); - } - - DataSynchronizeRequest rightDataSynchronizeRequest = rightDataSynchronizeRequestBuilder.build(); - if (rightDataSynchronizeRequest.isNotEmpty()) { - byte[][] copySqlCodes = leftDataSynchronizeService.getCopySqlCodes(rightDataSynchronizeRequest); - byte[][] deleteSqlCodes = rightDataSynchronizeService.getDeleteSqlCodes(rightDataSynchronizeRequest); - rightDataSynchronizeService.executeRequest(copySqlCodes, deleteSqlCodes); - } - - getModel().setStepState(WizardState.SUCCESSED); - - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/DataSynchronizeTaskListCellRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/DataSynchronizeTaskListCellRenderer.java deleted file mode 100644 index 510dda3..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/DataSynchronizeTaskListCellRenderer.java +++ /dev/null @@ -1,29 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.data; - -import fr.ird.observe.ui.admin.synchronize.data.task.DataSynchronizeTaskSupport; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.JList; -import java.awt.Component; - -/** - * Created on 03/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class DataSynchronizeTaskListCellRenderer extends DefaultListCellRenderer { - - private static final long serialVersionUID = 1L; - - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - - DataSynchronizeTaskSupport task = (DataSynchronizeTaskSupport) value; - super.getListCellRendererComponent(list, task.getLabel(), index, isSelected, cellHasFocus); - setIcon(task.getIcon()); - return this; - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/task/CopyToLeftDataSynchronizeTask.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/task/CopyToLeftDataSynchronizeTask.java deleted file mode 100644 index 8c6313c..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/task/CopyToLeftDataSynchronizeTask.java +++ /dev/null @@ -1,33 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.data.task; - -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 03/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class CopyToLeftDataSynchronizeTask extends DataSynchronizeTaskSupport { - - private final boolean tripExistOnLeft; - - public CopyToLeftDataSynchronizeTask(ReferentialReference<ProgramDto> programReference, DataReference tripReference, boolean tripExistOnLeft) { - super(programReference, tripReference, "copyToLeft"); - this.tripExistOnLeft=tripExistOnLeft; - } - - @Override - public String getLabel() { - return t("observe.actions.synchro.data.copyToLeftTask", decorateProgram(), decorateTrip()); - } - - public boolean isTripExistOnLeft() { - return tripExistOnLeft; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/task/CopyToRightDataSynchronizeTask.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/task/CopyToRightDataSynchronizeTask.java deleted file mode 100644 index abf3f53..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/task/CopyToRightDataSynchronizeTask.java +++ /dev/null @@ -1,33 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.data.task; - -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 03/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class CopyToRightDataSynchronizeTask extends DataSynchronizeTaskSupport { - - private final boolean tripExistOnRight; - - public CopyToRightDataSynchronizeTask(ReferentialReference<ProgramDto> programReference, DataReference tripReference, boolean tripExistOnRight) { - super(programReference, tripReference, "copyToRight"); - this.tripExistOnRight = tripExistOnRight; - } - - @Override - public String getLabel() { - return t("observe.actions.synchro.data.copyToRightTask", decorateProgram(), decorateTrip()); - } - - public boolean isTripExistOnRight() { - return tripExistOnRight; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/task/DataSynchronizeTaskSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/task/DataSynchronizeTaskSupport.java deleted file mode 100644 index a363c41..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/task/DataSynchronizeTaskSupport.java +++ /dev/null @@ -1,56 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.data.task; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import jaxx.runtime.SwingUtil; - -import javax.swing.Icon; - -/** - * Created on 03/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public abstract class DataSynchronizeTaskSupport { - - private final ReferentialReference<ProgramDto> program; - private final DataReference trip; - private final Icon icon; - - public abstract String getLabel(); - - public ReferentialReference<ProgramDto> getProgram() { - return program; - } - - public DataReference getTrip() { - return trip; - } - - public Icon getIcon() { - return icon; - } - - protected DataSynchronizeTaskSupport(ReferentialReference<ProgramDto> program, DataReference trip, String iconName) { - this.program = program; - this.trip = trip; - this.icon = SwingUtil.createActionIcon(iconName); - } - - protected String decorateProgram() { - DecoratorService decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); - String programStr = decoratorService.getReferentialReferenceDecorator(ProgramDto.class).toString(getProgram()); - return programStr; - } - - protected String decorateTrip() { - DecoratorService decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); - String tripStr = decoratorService.getTripReferenceDecorator(getTrip()).toString(getTrip()); - return tripStr; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/task/DeleteFromLeftDataSynchronizeTask.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/task/DeleteFromLeftDataSynchronizeTask.java deleted file mode 100644 index 267bf77..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/task/DeleteFromLeftDataSynchronizeTask.java +++ /dev/null @@ -1,25 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.data.task; - -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 03/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class DeleteFromLeftDataSynchronizeTask extends DataSynchronizeTaskSupport { - - public DeleteFromLeftDataSynchronizeTask(ReferentialReference<ProgramDto> programReference, DataReference tripReference) { - super(programReference, tripReference, "deleteFromLeft"); - } - - @Override - public String getLabel() { - return t("observe.actions.synchro.data.deleteFromLeftTask", decorateProgram(), decorateTrip()); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/task/DeleteFromRightDataSynchronizeTask.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/task/DeleteFromRightDataSynchronizeTask.java deleted file mode 100644 index d012850..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/data/task/DeleteFromRightDataSynchronizeTask.java +++ /dev/null @@ -1,25 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.data.task; - -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 03/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class DeleteFromRightDataSynchronizeTask extends DataSynchronizeTaskSupport { - - public DeleteFromRightDataSynchronizeTask(ReferentialReference<ProgramDto> programReference, DataReference tripReference) { - super(programReference, tripReference, "deleteFromRight"); - } - - @Override - public String getLabel() { - return t("observe.actions.synchro.data.deleteFromRightTask", decorateProgram(), decorateTrip()); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/legacy/ObsoleteReferentialReference.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/legacy/ObsoleteReferentialReference.java deleted file mode 100644 index 1eb9498..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/legacy/ObsoleteReferentialReference.java +++ /dev/null @@ -1,74 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.legacy; - -/*- - * #%L - * ObServe :: Application Swing - * %% - * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; - -import java.util.Objects; - -/** - * Représente une référence obsolète à remplacer. - * - * Created on 13/07/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class ObsoleteReferentialReference<R extends ReferentialDto> { - - private final ReferentialReference<R> referentialReference; - - public ObsoleteReferentialReference(Class<R>referentialName, ReferentialReference<R> referentialReference) { - this.referentialReference = referentialReference; - } - - public Class<R> getReferentialName() { - return getType(); - } - - public ReferentialReference<R> getReferentialReference() { - return referentialReference; - } - - public String getId() { - return referentialReference.getId(); - } - - public Class<R> getType() { - return referentialReference.getType(); - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - ObsoleteReferentialReference that = (ObsoleteReferentialReference) o; - return Objects.equals(getReferentialReference(), that.getReferentialReference()); - } - - @Override - public int hashCode() { - return Objects.hash(getReferentialReference()); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/legacy/ObsoleteReferentialReferenceListCellRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/legacy/ObsoleteReferentialReferenceListCellRenderer.java deleted file mode 100644 index 9d50169..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/legacy/ObsoleteReferentialReferenceListCellRenderer.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin.synchronize.referential.legacy; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import org.nuiton.decorator.Decorator; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.JList; -import java.awt.Component; - -import static org.nuiton.i18n.I18n.t; - -public class ObsoleteReferentialReferenceListCellRenderer extends DefaultListCellRenderer { - - private static final long serialVersionUID = 1L; - - protected transient DecoratorService decoratorService; - - public DecoratorService getDecoratorService() { - if (decoratorService == null) { - decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); - } - return decoratorService; - } - - @Override - public Component getListCellRendererComponent( - JList list, - Object value, - int index, - boolean isSelected, - boolean cellHasFocus) { - - ObsoleteReferentialReference referentialReference = (ObsoleteReferentialReference) value; - - DecoratorService service = getDecoratorService(); - Class referentialReferenceType = referentialReference.getReferentialReference().getType(); - String type = t(DecoratorService.getEntityLabel(referentialReferenceType)); - Decorator<?> decorator = service.getReferentialReferenceDecorator(referentialReferenceType); - - String text = type + " : " + decorator.toString(referentialReference.getReferentialReference()); - - return super.getListCellRendererComponent( - list, - text, - index, - isSelected, - cellHasFocus - ); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/legacy/SynchronizeModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/legacy/SynchronizeModel.java deleted file mode 100644 index 883ba83..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/legacy/SynchronizeModel.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin.synchronize.referential.legacy; - -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeCallbackResults; -import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeContext; -import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeEngine; -import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeResult; -import fr.ird.observe.ui.admin.AdminActionModel; -import fr.ird.observe.ui.admin.AdminStep; -import jaxx.runtime.swing.model.JaxxDefaultListModel; - -import javax.swing.DefaultListSelectionModel; -import java.util.List; - -/** - * Le modèle de l'opération de synchronization de réferentiel. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class SynchronizeModel extends AdminActionModel { - - private final JaxxDefaultListModel<ObsoleteReferentialReference> obsoleteReferences = new JaxxDefaultListModel<>(); - private final DefaultListSelectionModel obsoleteReferencesSelectionModel = new DefaultListSelectionModel(); - /** data source we want to synchronize. */ - protected ObserveSwingDataSource source; - /** data source which contains central referentiel. */ - protected ObserveSwingDataSource centralSource; - /** Le resultat de la synchronisation des référentiels. */ - private UnidirectionalReferentialSynchronizeResult referentialSynchronizeResult; - private UnidirectionalReferentialSynchronizeEngine engine; - private UnidirectionalReferentialSynchronizeContext referentialSynchronizeContext; - private UnidirectionalReferentialSynchronizeCallbackResults referentialSynchronizeCallbackResults; - - public SynchronizeModel() { - super(AdminStep.SYNCHRONIZE); - } - - public ObserveSwingDataSource getSource() { - return source; - } - - public void setSource(ObserveSwingDataSource source) { - this.source = source; - } - - public ObserveSwingDataSource getCentralSource() { - return centralSource; - } - - public void setCentralSource(ObserveSwingDataSource centralSource) { - this.centralSource = centralSource; - } - - public UnidirectionalReferentialSynchronizeResult getReferentialSynchronizeResult() { - return referentialSynchronizeResult; - } - - public void setReferentialSynchronizeResult(UnidirectionalReferentialSynchronizeResult referentialSynchronizeResult) { - this.referentialSynchronizeResult = referentialSynchronizeResult; - } - - public UnidirectionalReferentialSynchronizeEngine getEngine() { - return engine; - } - - public void setEngine(UnidirectionalReferentialSynchronizeEngine engine) { - this.engine = engine; - } - - public UnidirectionalReferentialSynchronizeContext getReferentialSynchronizeContext() { - return referentialSynchronizeContext; - } - - public void setReferentialSynchronizeContext(UnidirectionalReferentialSynchronizeContext referentialSynchronizeContext) { - this.referentialSynchronizeContext = referentialSynchronizeContext; - } - - public UnidirectionalReferentialSynchronizeCallbackResults getReferentialSynchronizeCallbackResults() { - return referentialSynchronizeCallbackResults; - } - - public void setReferentialSynchronizeCallbackResults(UnidirectionalReferentialSynchronizeCallbackResults referentialSynchronizeCallbackResults) { - this.referentialSynchronizeCallbackResults = referentialSynchronizeCallbackResults; - } - - public JaxxDefaultListModel<ObsoleteReferentialReference> getObsoleteReferences() { - return obsoleteReferences; - } - - public void setObsoleteReferences(List<ObsoleteReferentialReference> obsoleteReferences) { - this.obsoleteReferences.setAllElements(obsoleteReferences); - } - - public DefaultListSelectionModel getObsoleteReferencesSelectionModel() { - return obsoleteReferencesSelectionModel; - } - - public void destroy() { - obsoleteReferencesSelectionModel.clearSelection(); - obsoleteReferences.clear(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/legacy/SynchronizeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/legacy/SynchronizeUI.jaxx deleted file mode 100644 index 0bc020c..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/legacy/SynchronizeUI.jaxx +++ /dev/null @@ -1,120 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<!-- ****************************************** --> -<!-- L'écran de synchronization du référentiel --> -<!-- ****************************************** --> - -<fr.ird.observe.ui.admin.AdminTabUI> - - <import> - fr.ird.observe.ui.admin.AdminUI - fr.ird.observe.ui.admin.AdminStep - - jaxx.runtime.swing.CardLayout2 - jaxx.runtime.swing.wizard.ext.WizardState - - </import> - - <!-- un etat pour savoir quand on peut activer l'action apply --> - <Boolean id='canApply' javaBean='false'/> - - <SynchronizeUIHandler id='handler' constructorParams='this'/> - - <SynchronizeModel id='stepModel' initializer='getModel().getSynchronizeReferentielModel()'/> - - <CardLayout2 id='safeRefsPanelLayout'/> - - <script><![CDATA[ -public SynchronizeUI(AdminUI parentContext) { - super(AdminStep.SYNCHRONIZE, parentContext); -} - -@Override -public void initUI(AdminUI ui) { - getHandler().initTabUI(ui, this); -} - -@Override -public void destroy() { - stepModel.destroy(); - super.destroy(); - safeRefsPanelLayout.reset(safeRefsPanel); -} - -@Override -public void updateState(WizardState newState) { - getHandler().updateState(this, newState); -} - -protected void apply() { - getHandler().resolveObsoleteReference(); -} - -]]> - </script> - - <JPanel id='PENDING_content'> - <Table constraints='BorderLayout.CENTER' fill='both' weightx='1' - weighty='1'> - <row> - <cell> - <JButton id='startAction' onActionPerformed="getHandler().doStartAction()"/> - </cell> - </row> - </Table> - </JPanel> - - <JPanel id='NEED_FIX_content'> - <JScrollPane id='errorsPane' constraints='BorderLayout.NORTH'> - <JList id='obsoleteReferencesList'/> - </JScrollPane> - - <Table fill='both' constraints='BorderLayout.CENTER' - border='{new TitledBorder(t("observe.actions.synchro.referential.obsolete.entity.fix"))}'> - - <row> - <cell> - <JLabel text='observe.actions.synchro.referential.safe.entity.to.choose.label'/> - </cell> - <cell weightx='1' fill='both'> - - <!-- le panel dans lequel on positionne la liste déroulante de remplacement --> - <JPanel id='safeRefsPanel'/> - </cell> - </row> - <row> - <cell columns='2'> - <JSeparator/> - </cell> - </row> - <row> - <cell columns='2'> - <!-- pour appliquer les remplacements de l'entité obsolète --> - <JButton id='applyAction' onActionPerformed='getHandler().resolveObsoleteReference()'/> - </cell> - </row> - </Table> - - </JPanel> - -</fr.ird.observe.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/legacy/SynchronizeUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/legacy/SynchronizeUIHandler.java deleted file mode 100644 index 53659bc..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/legacy/SynchronizeUIHandler.java +++ /dev/null @@ -1,356 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin.synchronize.referential.legacy; - -import com.google.common.collect.ImmutableSet; -import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.service.actions.synchro.referential.diff.ReferentialSynchronizeDiffsEngine; -import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeCallbackRequest; -import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeCallbackRequests; -import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeCallbackResults; -import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeContext; -import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeEngine; -import fr.ird.observe.services.service.actions.synchro.referential.legacy.UnidirectionalReferentialSynchronizeResult; -import fr.ird.observe.ui.admin.AdminStep; -import fr.ird.observe.ui.admin.AdminTabUIHandler; -import fr.ird.observe.ui.admin.AdminUI; -import jaxx.runtime.swing.CardLayout2; -import jaxx.runtime.swing.editor.bean.BeanComboBox; -import jaxx.runtime.swing.model.JaxxDefaultListModel; -import jaxx.runtime.swing.wizard.ext.WizardState; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.DefaultListSelectionModel; -import javax.swing.JPanel; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionEvent; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Date; -import java.util.LinkedList; -import java.util.List; -import java.util.stream.Collectors; - -import static org.nuiton.i18n.I18n.t; - -/** - * Le controleur des onglets. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class SynchronizeUIHandler extends AdminTabUIHandler { - - /** Logger */ - private static final Log log = LogFactory.getLog(SynchronizeUIHandler.class); - - public SynchronizeUIHandler(SynchronizeUI ui) { - super(ui); - } - - public SynchronizeModel getStepModel() { - return model.getSynchronizeReferentielModel(); - } - - @Override - public SynchronizeUI getUi() { - return (SynchronizeUI) super.getUi(); - } - - public void initTabUI(AdminUI ui, SynchronizeUI tabUI) { - - super.initTabUI(ui, tabUI); - - if (log.isDebugEnabled()) { - log.debug(" specialized for [" + tabUI.getStep() + "] for main ui " + ui.getClass().getName() + "@" + System.identityHashCode(ui)); - } - - tabUI.getStartAction().setText(t("observe.actions.synchro.referential.legacy.launch.operation", t(tabUI.getStep().getOperationLabel()))); - - DefaultListSelectionModel obsoleteReferenceSelectionModel = tabUI.getModel().getSynchronizeReferentielModel().getObsoleteReferencesSelectionModel(); - obsoleteReferenceSelectionModel.addListSelectionListener(this::updateSelectedObsoleteEntity); - obsoleteReferenceSelectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - - } - - public void doStartAction() { - - addAdminWorker(getUi().getStartAction().getToolTipText(), this::doStartAction0); - - } - - private WizardState doStartAction0() throws Exception { - - if (log.isDebugEnabled()) { - log.debug(this); - } - - SynchronizeModel stepModel = getStepModel(); - - // on cree les sources de données - - ObserveSwingDataSource source = model.getSafeLocalSource(false); - stepModel.setSource(source); - - ObserveSwingDataSource centralSource = model.getSafeCentralSource(false); - stepModel.setCentralSource(centralSource); - - openSource(source); - openSource(centralSource); - - // construction du différentiel - sendMessage(t("observe.actions.synchro.referential.message.build.diff", centralSource.getLabel())); - - ReferentialSynchronizeDiffsEngine diffsEngine = new ReferentialSynchronizeDiffsEngine( - source.newReferentialSynchronizeDiffService(), - centralSource.newReferentialSynchronizeDiffService() - ); - - UnidirectionalReferentialSynchronizeEngine engine = new UnidirectionalReferentialSynchronizeEngine( - diffsEngine, source.newUnidirectionalReferentialSynchronizeLocalService() - ); - - stepModel.setEngine(engine); - - UnidirectionalReferentialSynchronizeContext unidirectionalReferentialSynchronizeContext = engine.prepareContext(); - - stepModel.setReferentialSynchronizeContext(unidirectionalReferentialSynchronizeContext); - - boolean needCallback = unidirectionalReferentialSynchronizeContext.isNeedCallback(); - - if (needCallback) { - - // il existe des références obsolètes à traiter - - sendMessage(t("observe.actions.operation.message.needFix")); - - stepModel.setReferentialSynchronizeCallbackResults(new UnidirectionalReferentialSynchronizeCallbackResults()); - - // des références obsolètes ont été détectées, on prépare les interfaces graphiques - // avec les données à corriger - - List<ObsoleteReferentialReference> obsoleteReferentialReferences = new LinkedList<>(); - UnidirectionalReferentialSynchronizeCallbackRequests callbackRequests = stepModel.getReferentialSynchronizeContext().getCallbackRequests(); - - for (UnidirectionalReferentialSynchronizeCallbackRequest<?> callbackRequest : callbackRequests) { - - Class referentialName = callbackRequest.getReferentialName(); - - obsoleteReferentialReferences.addAll( - callbackRequest.getReferentialsToReplace().stream() - .map(referentialReference -> new ObsoleteReferentialReference(referentialName, referentialReference)) - .collect(Collectors.toList())); - - } - - stepModel.setObsoleteReferences(obsoleteReferentialReferences); - - return WizardState.NEED_FIX; - - } - - // pas de reference obsolete à traiter - - // on termine le traitement - beforeSuccess(); - - return WizardState.SUCCESSED; - - } - - public <R extends ReferentialDto> void resolveObsoleteReference() { - - ObsoleteReferentialReference<R> obsoleteRef = (ObsoleteReferentialReference) getUi().getObsoleteReferencesList().getSelectedValue(); - - BeanComboBox<ReferentialReference<R>> safeComboBox = (BeanComboBox<ReferentialReference<R>>) getSafeComboBox(); - ReferentialReference<R> safeRef = (ReferentialReference<R>) safeComboBox.getSelectedItem(); - - UnidirectionalReferentialSynchronizeCallbackResults referentialSynchronizeCallbackResults = getStepModel().getReferentialSynchronizeCallbackResults(); - referentialSynchronizeCallbackResults.addCallbackResult(obsoleteRef.getType(), obsoleteRef.getId(), safeRef.getId()); - - // On supprime le référentiel corrigé de la liste des référentiels à corriger - - getStepModel().getObsoleteReferences().removeElement(obsoleteRef); - - // on supprime la sélection de la liste des remplacements - - safeComboBox.setSelectedItem(null); - - // S'il ne reste plus de référentiel à corriger, on peut terminer le traitement - - if (getStepModel().getObsoleteReferences().isEmpty()) { - - beforeSuccess(); - - getModel().setStepState(WizardState.SUCCESSED); -// updateState(getUi(), WizardState.SUCCESSED); - - } - - } - - private void updateSelectedObsoleteEntity(ListSelectionEvent e) { - - if (e.getValueIsAdjusting()) { - return; - } - - SynchronizeUI ui = getUi(); - - int row = getStepModel().getObsoleteReferencesSelectionModel().getMinSelectionIndex(); - - JaxxDefaultListModel<ObsoleteReferentialReference> obsoleteReferences = getStepModel().getObsoleteReferences(); - - if (row != -1 && obsoleteReferences.getElementAt(row) != null) { - - ObsoleteReferentialReference referentialReference = obsoleteReferences.getElementAt(row); - - String key = referentialReference.getReferentialName().getName(); - CardLayout2 safeRefsPanelLayout = ui.getSafeRefsPanelLayout(); - JPanel safeRefsPanel = ui.getSafeRefsPanel(); - if (safeRefsPanelLayout.contains(key)) { - - // la liste déroulante existe deja pour ce type - BeanComboBox<?> list = (BeanComboBox<?>) safeRefsPanelLayout.getComponent(safeRefsPanel, key); - - if (!getSafeComboBox().equals(list)) { - - // on l'affiche - safeRefsPanelLayout.show(safeRefsPanel, key); - - } - - } else { - - ReferentialReferenceDecorator decorator = getDecoratorService().getReferentialReferenceDecorator(referentialReference.getType()); - - UnidirectionalReferentialSynchronizeCallbackRequest<?> callbackRequest = getStepModel().getReferentialSynchronizeContext().getCallbackRequests().getCallbackRequest(referentialReference.getReferentialName()); - ImmutableSet<? extends ReferentialReference<?>> availableReferentials = callbackRequest.getAvailableReferentials(); - - List<ReferentialReference> data = new ArrayList<>(availableReferentials); - - // la liste n'existe pas encore - BeanComboBox<ReferentialReference> box = new BeanComboBox<>(ui); - box.setBean(this); - box.setProperty("safeEntity"); - box.setShowReset(true); - box.addPropertyChangeListener("selectedItem", evt -> updateCanApply()); - safeRefsPanel.add(box, key); - box.init(decorator, data); - - safeRefsPanelLayout.show(safeRefsPanel, key); - - } - - } - } - - private BeanComboBox<?> getSafeComboBox() { - SynchronizeUI ui = getUi(); - JPanel panel = ui.getSafeRefsPanel(); - return (BeanComboBox<?>) ui.getSafeRefsPanelLayout().getVisibleComponent(panel); - } - - private void updateCanApply() { - SynchronizeUI ui = getUi(); - BeanComboBox<?> safeComboBox = getSafeComboBox(); - ui.setCanApply(safeComboBox != null && safeComboBox.getSelectedItem() != null); - } - - private void beforeSuccess() { - - SynchronizeModel stepModel = getStepModel(); - - UnidirectionalReferentialSynchronizeEngine engine = stepModel.getEngine(); - - UnidirectionalReferentialSynchronizeContext referentialSynchronizeContext = stepModel.getReferentialSynchronizeContext(); - - UnidirectionalReferentialSynchronizeCallbackResults referentialSynchronizeCallbackResults = stepModel.getReferentialSynchronizeCallbackResults(); - - UnidirectionalReferentialSynchronizeResult referentialSynchronizeResult = engine.prepareResult(referentialSynchronizeContext, referentialSynchronizeCallbackResults); - stepModel.setReferentialSynchronizeResult(referentialSynchronizeResult); - - if (referentialSynchronizeResult.isEmpty()) { - - sendMessage(t("observe.actions.synchro.referential.message.ref.is.updtodate")); - - } else { - - for (Class<? extends ReferentialDto> referentialName : referentialSynchronizeResult.getReferentialNames()) { - - Collection<String> referentialAdded = referentialSynchronizeResult.getReferentialAdded(referentialName); - if (CollectionUtils.isNotEmpty(referentialAdded)) { - - sendMessage(t("observe.actions.synchro.referential.message.referentiel.was.added", referentialName, referentialAdded.size())); - for (String id : referentialAdded) { - sendMessage(" - " + id); - } - - } - - Collection<String> referentialUpdated = referentialSynchronizeResult.getReferentialUpdated(referentialName); - if (CollectionUtils.isNotEmpty(referentialUpdated)) { - - sendMessage(t("observe.actions.synchro.referential.message.referentiel.was.modified", referentialName, referentialUpdated.size())); - for (String id : referentialUpdated) { - sendMessage(" - " + id); - } - - } - - Collection<String> referentialRemoved = referentialSynchronizeResult.getReferentialRemoved(referentialName); - if (CollectionUtils.isNotEmpty(referentialRemoved)) { - - sendMessage(t("observe.actions.synchro.referential.message.referentiel.was.removed", referentialName, referentialRemoved.size())); - for (String id : referentialRemoved) { - sendMessage(" - " + id); - } - - } - - Collection<Pair<String, String>> referentialReplaced = referentialSynchronizeResult.getReferentialReplaced(referentialName); - if (CollectionUtils.isNotEmpty(referentialReplaced)) { - - sendMessage(t("observe.actions.synchro.referential.message.referentiel.was.replaced", referentialName, referentialReplaced.size())); - for (Pair<String, String> ids : referentialReplaced) { - sendMessage(" - " + ids.getLeft() + " → " + ids.getRight()); - } - - } - - } - - getModel().getSaveLocalModel().addStepForSave(AdminStep.SYNCHRONIZE); - - } - - sendMessage(t("observe.actions.operation.message.done", new Date())); - - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialReplaceUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialReplaceUIHandler.java deleted file mode 100644 index 764143c..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialReplaceUIHandler.java +++ /dev/null @@ -1,40 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng; - -import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import jaxx.runtime.swing.editor.bean.BeanComboBox; - -import java.awt.Dimension; -import java.beans.PropertyChangeListener; -import java.util.List; - -/** - * Created on 11/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - */ -public class ReferentialReplaceUIHandler<R extends ReferentialDto> { - - public static final String CONTEXT_NAME = "replaceUI"; - - private final ReferentialReplaceUI<R> ui; - protected PropertyChangeListener listenData; - - public ReferentialReplaceUIHandler(ReferentialReplaceUI<R> ui) { - this.ui = ui; - this.listenData = evt -> ui.setReplaceReference((ReferentialReference) evt.getNewValue()); - } - - public void init() { - BeanComboBox<ReferentialReference<R>> beanComboBox = ui.getList(); - - beanComboBox.setI18nPrefix("observe.common."); - beanComboBox.setMinimumSize(new Dimension(0, 24)); - beanComboBox.setBeanType((Class) ReferentialReference.class); - List<ReferentialReference<R>> references = ui.getContextValue(List.class,CONTEXT_NAME); - ReferentialReferenceDecorator<R> decorator = ui.getContextValue(ReferentialReferenceDecorator.class,CONTEXT_NAME); - beanComboBox.init(decorator, references); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchroConfigUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchroConfigUI.jaxx deleted file mode 100644 index 6092845..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchroConfigUI.jaxx +++ /dev/null @@ -1,80 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<!-- ************************************************************* --> -<!-- La configuration de l'import GPS --> -<!-- ************************************************************* --> - -<JPanel id="referentialSynchronizeConfig"> - - <import> - fr.ird.observe.configuration.ObserveSwingApplicationConfig - fr.ird.observe.services.service.actions.synchro.referential.ReferentialSynchronizeMode - fr.ird.observe.ui.admin.AdminUIModel - fr.ird.observe.validation.ValidationModelMode - - org.nuiton.validator.NuitonValidatorScope - - java.io.File - - javax.swing.JComboBox - - static fr.ird.observe.ui.UIHelper.getStringValue - </import> - - <ReferentialSynchroUIHandler id='handler' initializer='getContextValue(ReferentialSynchroUIHandler.class)'/> - - <AdminUIModel id='model' initializer='getContextValue(AdminUIModel.class)'/> - - <ReferentialSynchroModel id='stepModel' initializer='model.getReferentialSynchroModel()'/> - - <ButtonGroup id='synchronizeMode' - onStateChanged='stepModel.setSynchronizeMode((ReferentialSynchronizeMode) synchronizeMode.getSelectedValue())'/> - - <script><![CDATA[ -public void destroy() { - model = null; - stepModel = null; -} - -@Override -protected void finalize() throws Throwable { - super.finalize(); - destroy(); -} - -]]> - </script> - - <JPanel id="referentialSynchronizeConfigPanel" constraints='BorderLayout.CENTER' layout='{new GridLayout(0, 1)}'> - <JToggleButton id="LEFT_TO_RIGHT"/> - <JToggleButton id="RIGHT_TO_LEFT"/> - <JToggleButton id="BOTH"/> - </JPanel> - <Table constraints='BorderLayout.SOUTH' weightx='1' weighty='1'> - <row> - <cell> - <JLabel/> - </cell> - </row> - </Table> - -</JPanel> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchroModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchroModel.java deleted file mode 100644 index 83ae0a3..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchroModel.java +++ /dev/null @@ -1,299 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng; - -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.ReferentialReferenceSet; -import fr.ird.observe.services.service.actions.synchro.referential.ReferentialSynchronizeMode; -import fr.ird.observe.services.service.actions.synchro.referential.diff.ReferentialSynchronizeDiffsEngine; -import fr.ird.observe.services.service.actions.synchro.referential.ng.ReferentialSynchronizeService; -import fr.ird.observe.services.service.actions.synchro.referential.ng.ReferentialSynchronizeServiceEngine; -import fr.ird.observe.ui.admin.AdminActionModel; -import fr.ird.observe.ui.admin.AdminStep; -import fr.ird.observe.ui.admin.synchronize.referential.ng.task.AddReferentialSynchronizeTask; -import fr.ird.observe.ui.admin.synchronize.referential.ng.task.DeleteReferentialSynchronizeTask; -import fr.ird.observe.ui.admin.synchronize.referential.ng.task.DesactivateReferentialSynchronizeTask; -import fr.ird.observe.ui.admin.synchronize.referential.ng.task.ReferentialSynchronizeTaskSupport; -import fr.ird.observe.ui.admin.synchronize.referential.ng.tree.ReferentialSynchronizeTreeModel; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.ArrayList; -import java.util.List; - -/** - * Created on 02/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class ReferentialSynchroModel extends AdminActionModel { - - public static final String LEFT_SOURCE_PROPERTY_NAME = "leftSource"; - public static final String RIGHT_SOURCE_PROPERTY_NAME = "rightSource"; - public static final String TASKS_PROPERTY_NAME = "tasks"; - public static final String SYNCHRONIZE_MODE_PROPERTY_NAME = "synchronizeMode"; - public static final String RIGHT_TREE_MODEL_PROPERTY_NAME = "rightTreeModel"; - public static final String LEFT_TREE_MODEL_PROPERTY_NAME = "lefttTreeModel"; - public static final String COPY_RIGHT_PROPERTY_NAME = "copyRight"; - public static final String COPY_LEFT_PROPERTY_NAME = "copyLeft"; - public static final String SKIP_RIGHT_PROPERTY_NAME = "skipRight"; - public static final String SKIP_LEFT_PROPERTY_NAME = "skipLeft"; - public static final String DELETE_RIGHT_PROPERTY_NAME = "deleteRight"; - public static final String DELETE_LEFT_PROPERTY_NAME = "deleteLeft"; - public static final String DESACTIVATE_RIGHT_PROPERTY_NAME = "desactivateRight"; - public static final String DESACTIVATE_LEFT_PROPERTY_NAME = "desactivateLeft"; - public static final String DESACTIVATE_WITH_REPLACE_RIGHT_PROPERTY_NAME = "desactivateWithReplaceRight"; - public static final String DESACTIVATE_WITH_REPLACE_LEFT_PROPERTY_NAME = "desactivateWithReplaceLeft"; - public static final String REVERT_RIGHT_PROPERTY_NAME = "revertRight"; - public static final String REVERT_LEFT_PROPERTY_NAME = "revertLeft"; - /** Logger. */ - private static final Log log = LogFactory.getLog(ReferentialSynchroModel.class); - private final ReferentialSynchronizeTaskListModel tasks; - private ObserveSwingDataSource leftSource; - private ObserveSwingDataSource rightSource; - private ReferentialSynchronizeMode synchronizeMode; - private ReferentialSynchronizeTreeModel leftTreeModel; - private ReferentialSynchronizeTreeModel rightTreeModel; - private ReferentialSynchronizeDiffsEngine engine; - private boolean copyLeft; - private boolean revertLeft; - private boolean skipLeft; - private boolean deleteLeft; - private boolean desactivateLeft; - private boolean desactivateWithReplaceLeft; - private boolean copyRight; - private boolean revertRight; - private boolean skipRight; - private boolean deleteRight; - private boolean desactivateRight; - private boolean desactivateWithReplaceRight; - - public ReferentialSynchroModel() { - super(AdminStep.REFERENTIAL_SYNCHRONIZE); - this.tasks = new ReferentialSynchronizeTaskListModel(); - } - - public ReferentialSynchronizeMode getSynchronizeMode() { - return synchronizeMode; - } - - public void setSynchronizeMode(ReferentialSynchronizeMode synchronizeMode) { - Object oldValue = getSynchronizeMode(); - this.synchronizeMode = synchronizeMode; - firePropertyChange(SYNCHRONIZE_MODE_PROPERTY_NAME, oldValue, synchronizeMode); - } - - public ObserveSwingDataSource getLeftSource() { - return leftSource; - } - - public void setLeftSource(ObserveSwingDataSource leftSource) { - this.leftSource = leftSource; - firePropertyChange(LEFT_SOURCE_PROPERTY_NAME, leftSource); - } - - public ObserveSwingDataSource getRightSource() { - return rightSource; - } - - public void setRightSource(ObserveSwingDataSource rightSource) { - this.rightSource = rightSource; - firePropertyChange(RIGHT_SOURCE_PROPERTY_NAME, rightSource); - } - - public ReferentialSynchronizeTreeModel getLeftTreeModel() { - return leftTreeModel; - } - - public void setLeftTreeModel(ReferentialSynchronizeTreeModel leftTreeModel) { - Object oldValue = getLeftTreeModel(); - this.leftTreeModel = leftTreeModel; - firePropertyChange(LEFT_TREE_MODEL_PROPERTY_NAME, oldValue, leftTreeModel); - } - - public ReferentialSynchronizeTreeModel getRightTreeModel() { - return rightTreeModel; - } - - public void setRightTreeModel(ReferentialSynchronizeTreeModel rightTreeModel) { - Object oldValue = getRightTreeModel(); - this.rightTreeModel = rightTreeModel; - firePropertyChange(RIGHT_TREE_MODEL_PROPERTY_NAME, oldValue, rightTreeModel); - } - - public ReferentialSynchronizeTaskListModel getTasks() { - return tasks; - } - - public void setEngine(ReferentialSynchronizeDiffsEngine engine) { - this.engine = engine; - } - - public <D extends ReferentialDto> List<ReferentialReference<D>> getPossibleReplaceUniverse(boolean left, Class<D> type, ReferentialReference<D> referenceToReplace) { - - ReferentialReferenceSet<D> referencesSet; - if (left) { - referencesSet = engine.getLeftEnabledReferentialReferenceSet(type); - } else { - referencesSet = engine.getRightEnabledReferentialReferenceSet(type); - } - - List<ReferentialReference<D>> references = new ArrayList<>(referencesSet.getReferences()); - references.remove(referenceToReplace); - - for (ReferentialSynchronizeTaskSupport task : tasks) { - - if (!type.equals(task.getType())) { - continue; - } - if (left == task.isLeft()) { - - if (task instanceof DeleteReferentialSynchronizeTask) { - - // on enlève ce référentiel car il a été supprimé de ce côté - ReferentialReference<D> referential = task.getReferential(); - references.remove(referential); - } - - if (task instanceof DesactivateReferentialSynchronizeTask) { - - // on enlève ce référentiel car il a été désactivé de ce côté - ReferentialReference<D> referential = task.getReferential(); - references.remove(referential); - } - - continue; - } - - if (type.equals(task.getType())) { - - if (task instanceof AddReferentialSynchronizeTask) { - - // on ajoute ce référentiel car il a été ajouté depuis l'autre côté - ReferentialReference<D> referential = task.getReferential(); - references.add(referential); - } - - } - - } - - return references; - } - - public boolean isCopyRight() { - return copyRight; - } - - public void setCopyRight(boolean copyRight) { - this.copyRight = copyRight; - firePropertyChange(COPY_RIGHT_PROPERTY_NAME, copyRight); - } - - public boolean isCopyLeft() { - return copyLeft; - } - - public void setCopyLeft(boolean copyLeft) { - this.copyLeft = copyLeft; - firePropertyChange(COPY_LEFT_PROPERTY_NAME, copyLeft); - } - - public boolean isRevertRight() { - return revertRight; - } - - public void setRevertRight(boolean revertRight) { - this.revertRight = revertRight; - firePropertyChange(REVERT_RIGHT_PROPERTY_NAME, revertRight); - } - - public boolean isRevertLeft() { - return revertLeft; - } - - public void setRevertLeft(boolean revertLeft) { - this.revertLeft = revertLeft; - firePropertyChange(REVERT_LEFT_PROPERTY_NAME, revertLeft); - } - - public boolean isSkipLeft() { - return skipLeft; - } - - public void setSkipLeft(boolean skipLeft) { - this.skipLeft = skipLeft; - firePropertyChange(SKIP_LEFT_PROPERTY_NAME, skipLeft); - } - - public boolean isSkipRight() { - return skipRight; - } - - public void setSkipRight(boolean skipRight) { - this.skipRight = skipRight; - firePropertyChange(SKIP_RIGHT_PROPERTY_NAME, skipRight); - } - - public boolean isDeleteLeft() { - return deleteLeft; - } - - public void setDeleteLeft(boolean deleteLeft) { - this.deleteLeft = deleteLeft; - firePropertyChange(DELETE_LEFT_PROPERTY_NAME, deleteLeft); - } - - public boolean isDeleteRight() { - return deleteRight; - } - - public void setDeleteRight(boolean deleteRight) { - this.deleteRight = deleteRight; - firePropertyChange(DELETE_RIGHT_PROPERTY_NAME, deleteRight); - } - - public boolean isDesactivateRight() { - return desactivateRight; - } - - public void setDesactivateRight(boolean desactivateRight) { - this.desactivateRight = desactivateRight; - firePropertyChange(DESACTIVATE_RIGHT_PROPERTY_NAME, desactivateRight); - } - - public boolean isDesactivateLeft() { - return desactivateLeft; - } - - public void setDesactivateLeft(boolean desactivateLeft) { - this.desactivateLeft = desactivateLeft; - firePropertyChange(DESACTIVATE_LEFT_PROPERTY_NAME, desactivateLeft); - } - - public boolean isDesactivateWithReplaceRight() { - return desactivateWithReplaceRight; - } - - public void setDesactivateWithReplaceRight(boolean desactivateWithReplaceRight) { - this.desactivateWithReplaceRight = desactivateWithReplaceRight; - firePropertyChange(DESACTIVATE_WITH_REPLACE_RIGHT_PROPERTY_NAME, desactivateWithReplaceRight); - } - - public boolean isDesactivateWithReplaceLeft() { - return desactivateWithReplaceLeft; - } - - public void setDesactivateWithReplaceLeft(boolean desactivateWithReplaceLeft) { - this.desactivateWithReplaceLeft = desactivateWithReplaceLeft; - firePropertyChange(DESACTIVATE_WITH_REPLACE_LEFT_PROPERTY_NAME, desactivateWithReplaceLeft); - } - - - public ReferentialSynchronizeServiceEngine newReferentialSynchronizeServiceEngine() { - ReferentialSynchronizeService leftService = leftSource.newReferentialSynchronizeService(); - ReferentialSynchronizeService rightService = rightSource.newReferentialSynchronizeService(); - return new ReferentialSynchronizeServiceEngine(leftService, rightService); - } -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchroUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchroUI.jaxx deleted file mode 100644 index 2c08573..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchroUI.jaxx +++ /dev/null @@ -1,144 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<!-- ************************************************************* --> -<!-- L'écran de synchronisation bi-directionnel des données --> -<!-- ************************************************************* --> - -<fr.ird.observe.ui.admin.AdminTabUI> - - <import> - fr.ird.observe.ui.UIHelper - fr.ird.observe.ui.admin.AdminUI - fr.ird.observe.ui.admin.AdminStep - fr.ird.observe.ui.admin.synchronize.referential.ng.action.ApplyAction - fr.ird.observe.ui.admin.synchronize.referential.ng.action.RegisterCopyTaskAction - fr.ird.observe.ui.admin.synchronize.referential.ng.action.RegisterDeleteTaskAction - fr.ird.observe.ui.admin.synchronize.referential.ng.action.RegisterDesactivateTaskAction - fr.ird.observe.ui.admin.synchronize.referential.ng.action.RegisterRevertTaskAction - fr.ird.observe.ui.admin.synchronize.referential.ng.action.RegisterSkipTaskAction - fr.ird.observe.ui.admin.synchronize.referential.ng.tree.ReferentialSynchronizeTreeModel - fr.ird.observe.ui.admin.synchronize.referential.ng.tree.ReferentialSynchronizeTreeCellRenderer - fr.ird.observe.ui.tree.ObserveTreeHelper - - javax.swing.ListSelectionModel - - static org.nuiton.i18n.I18n.t; - - </import> - - <ObserveTreeHelper id='leftTreeHelper'/> - <ObserveTreeHelper id='rightTreeHelper'/> - - <ReferentialSynchroUIHandler id='handler' constructorParams='this'/> - - <ReferentialSynchroModel id='stepModel' javaBean='getModel().getReferentialSynchroModel()'/> - - <ReferentialSynchronizeTreeModel id="leftTreeModel" javaBean="getStepModel().getLeftTreeModel()"/> - <ReferentialSynchronizeTreeModel id="rightTreeModel" javaBean="getStepModel().getRightTreeModel()"/> - <JPanel id='invisiblePanel'> - - </JPanel> - - <script><![CDATA[ -public ReferentialSynchroUI(AdminUI parentContext) { - super(AdminStep.REFERENTIAL_SYNCHRONIZE, parentContext); -} - -public void initUI(AdminUI ui) { - getHandler().initTabUI(ui, this); -} - -@Override -public void destroy() { - leftTreeModel.clearSelection(); - rightTreeModel.clearSelection(); - super.destroy(); -} -]]> - </script> - - <JPanel id='PENDING_content'> - <Table constraints='BorderLayout.CENTER' fill='both' weightx='1' - weighty='1'> - <row> - <cell> - <JButton id='startAction' onActionPerformed="getHandler().doStartAction()"/> - </cell> - </row> - </Table> - </JPanel> - <JPanel id='NEED_FIX_content'> - <JSplitPane id="contentSplitPane" constraints='BorderLayout.CENTER'> - <Table id='contentNorth' fill="both" weighty="1"> - <row> - <cell weightx="0.5"> - <JScrollPane id='leftTreePane'> - <JTree id='leftTree'/> - </JScrollPane> - </cell> - <cell> - <JPanel layout="{new BorderLayout()}" border='{new TitledBorder("")}'> - <JToolBar id="middleActions" layout="{new GridLayout(0, 2)}" constraints='BorderLayout.CENTER'> - <JButton id="copyLeft" opaque="true"/> - <JButton id="copyRight" opaque="true"/> - <JButton id="revertLeft" opaque="true"/> - <JButton id="revertRight" opaque="true"/> - <JButton id="desactivateLeft" opaque="false"/> - <JButton id="desactivateRight" opaque="false"/> - <JButton id="desactivateWithReplaceLeft" opaque="false"/> - <JButton id="desactivateWithReplaceRight" opaque="false"/> - <JButton id="deleteLeft" opaque="false"/> - <JButton id="deleteRight" opaque="false"/> - <JButton id="skipLeft" opaque="false"/> - <JButton id="skipRight" opaque="false"/> - </JToolBar> - </JPanel> - </cell> - <cell weightx="0.5"> - <JScrollPane id='rightTreePane'> - <JTree id='rightTree'/> - </JScrollPane> - </cell> - </row> - </Table> - <Table id='contentSouth' fill="both"> - <row weighty="1"> - <cell weightx="1"> - <JScrollPane id='actionsToConsumePane'> - <JList id="actionsToConsume"/> - </JScrollPane> - </cell> - </row> - <row> - <cell> - <JPanel layout="{new BorderLayout()}"> - <JButton id='applyAction' constraints='BorderLayout.CENTER'/> - </JPanel> - </cell> - </row> - </Table> - </JSplitPane> - - </JPanel> - -</fr.ird.observe.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchroUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchroUIHandler.java deleted file mode 100644 index 0ce60a1..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchroUIHandler.java +++ /dev/null @@ -1,191 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng; - -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.service.actions.synchro.referential.ReferentialSynchronizeMode; -import fr.ird.observe.services.service.actions.synchro.referential.diff.ReferentialSynchronizeDiffService; -import fr.ird.observe.services.service.actions.synchro.referential.diff.ReferentialSynchronizeDiffsEngine; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.admin.AdminStep; -import fr.ird.observe.ui.admin.AdminTabUIHandler; -import fr.ird.observe.ui.admin.AdminUI; -import fr.ird.observe.ui.admin.config.ConfigUI; -import fr.ird.observe.ui.admin.synchronize.referential.ng.tree.ReferentialSynchronizeTreeModel; -import fr.ird.observe.ui.admin.synchronize.referential.ng.tree.ReferentialSynchronizeTreeModelsBuilder; -import jaxx.runtime.context.JAXXInitialContext; -import jaxx.runtime.swing.wizard.ext.WizardState; -import org.apache.commons.lang3.tuple.Pair; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JScrollPane; -import javax.swing.JTree; -import javax.swing.border.TitledBorder; -import javax.swing.event.TreeSelectionListener; -import java.awt.Color; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 02/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class ReferentialSynchroUIHandler extends AdminTabUIHandler { - - /** Logger */ - private static final Log log = LogFactory.getLog(ReferentialSynchroUIHandler.class); - - private final TreeSelectionListener treeSelectionListener; - - public ReferentialSynchroUIHandler(ReferentialSynchroUI ui) { - super(ui); - this.treeSelectionListener = evt -> updateEnabledActions(); - } - - public ReferentialSynchroModel getStepModel() { - return model.getReferentialSynchroModel(); - } - - @Override - public ReferentialSynchroUI getUi() { - return (ReferentialSynchroUI) super.getUi(); - } - - public void initTabUI(AdminUI ui, ReferentialSynchroUI tabUI) { - - super.initTabUI(ui, tabUI); - - if (log.isDebugEnabled()) { - log.debug(" specialized for [" + tabUI.getStep() + "] for main ui " + ui.getClass().getName() + "@" + System.identityHashCode(ui)); - } - - ConfigUI configUI = (ConfigUI) ui.getStepUI(AdminStep.CONFIG); - JAXXInitialContext tx = new JAXXInitialContext().add(configUI).add(this); - ReferentialSynchroConfigUI extraConfig = new ReferentialSynchroConfigUI(tx); - configUI.getExtraConfig().add(extraConfig); - - } - - public void doStartAction() { - - addAdminWorker(getUi().getStartAction().getToolTipText(), this::doStartAction0); - - } - - private WizardState doStartAction0() { - - ReferentialSynchroModel stepModel = getStepModel(); - - ObserveSwingDataSource leftSource = getModel().getSafeLocalSource(true); - stepModel.setLeftSource(leftSource); - - ObserveSwingDataSource rightSource = getModel().getSafeCentralSource(true); - stepModel.setRightSource(rightSource); - - ReferentialSynchronizeDiffService leftDiffSynchronizeService = leftSource.newReferentialSynchronizeDiffService(); - ReferentialSynchronizeDiffService rightDiffSynchronizeService = rightSource.newReferentialSynchronizeDiffService(); - - ReferentialSynchronizeDiffsEngine engine = new ReferentialSynchronizeDiffsEngine(leftDiffSynchronizeService, rightDiffSynchronizeService); - stepModel.setEngine(engine); - - ReferentialSynchronizeMode synchronizeMode = stepModel.getSynchronizeMode(); - ReferentialSynchronizeTreeModelsBuilder treeModelsBuilder = new ReferentialSynchronizeTreeModelsBuilder(synchronizeMode, engine); - Pair<ReferentialSynchronizeTreeModel, ReferentialSynchronizeTreeModel> treePair = treeModelsBuilder.build(); - stepModel.setLeftTreeModel(treePair.getLeft()); - stepModel.setRightTreeModel(treePair.getRight()); - - stepModel.getTasks().removeAllElements(); - - ReferentialSynchroUI ui = getUi(); - initTree(ui.getLeftTree(), - ui.getLeftTreePane(), - stepModel.getLeftTreeModel(), - getModel().getLocalSourceModel().getLabel(), - t("observe.actions.synchro.referential.message.referential.leftData.loaded")); - - initTree(ui.getRightTree(), - ui.getRightTreePane(), - stepModel.getRightTreeModel(), - getModel().getCentralSourceModel().getLabel(), - t("observe.actions.synchro.referential.message.referential.rightData.loaded")); - - return WizardState.NEED_FIX; - - } - - private void updateEnabledActions() { - - ReferentialSynchroModel stepModel = getStepModel(); - - updateLeftTreeEnableActions(stepModel.getLeftTreeModel()); - updateRightTreeEnableActions(stepModel.getRightTreeModel()); - - } - - private void updateLeftTreeEnableActions(ReferentialSynchronizeTreeModel treeModel) { - - ReferentialSynchroModel stepModel = getStepModel(); - - treeModel.updateSelectedActions(); - stepModel.setCopyLeft(treeModel.isCanAdd() || treeModel.isCanUpdate()); - stepModel.setDeleteLeft(treeModel.isCanDelete()); - stepModel.setDesactivateLeft(treeModel.isCanDelete()); - stepModel.setDesactivateWithReplaceLeft(treeModel.isCanDelete()); - stepModel.setRevertLeft(treeModel.isCanRevert()); - stepModel.setSkipLeft(treeModel.isCanSkip()); - } - - private void updateRightTreeEnableActions(ReferentialSynchronizeTreeModel treeModel) { - - ReferentialSynchroModel stepModel = getStepModel(); - - treeModel.updateSelectedActions(); - - stepModel.setCopyRight(treeModel.isCanAdd() || treeModel.isCanUpdate()); - stepModel.setDeleteRight(treeModel.isCanDelete()); - stepModel.setDesactivateRight(treeModel.isCanDelete()); - stepModel.setDesactivateWithReplaceRight(treeModel.isCanDelete()); - stepModel.setRevertRight(treeModel.isCanRevert()); - stepModel.setSkipRight(treeModel.isCanSkip()); - } - - private void initTree(JTree tree, JScrollPane treePane, ReferentialSynchronizeTreeModel treeModel, String title, String message) { - - ReferentialSynchronizeMode newValue = getStepModel().getSynchronizeMode(); - - Color color = - (treeModel.isLeft() && newValue.isLeftWrite() || !treeModel.isLeft() && newValue.isRightWrite()) ? - Color.BLACK : Color.RED; - - TitledBorder border = new TitledBorder(title); - border.setTitleColor(color); - - treePane.setBorder(border); - tree.setModel(treeModel); - tree.setSelectionModel(treeModel); - - treeModel.removeTreeSelectionListener(treeSelectionListener); - treeModel.addTreeSelectionListener(treeSelectionListener); - - UIHelper.initUI(treePane, tree); - //UIHelper.expandTree(tree); - - sendMessage(message); - - if (treeModel.isLeft()) { - - updateLeftTreeEnableActions(treeModel); - - } else { - updateRightTreeEnableActions(treeModel); - } - - ConfigUI configUI = (ConfigUI) parentUI.getStepUI(AdminStep.CONFIG); - configUI.getLocalSourceConfig().setBorder(new TitledBorder(getModel().getLocalSourceLabel())); - configUI.getCentralSourceConfig().setBorder(new TitledBorder(getModel().getCentralSourceLabel())); - - } - - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchronizeResources.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchronizeResources.java deleted file mode 100644 index e297835..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchronizeResources.java +++ /dev/null @@ -1,161 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng; - -import fr.ird.observe.services.service.actions.synchro.referential.ng.task.ReferentialSynchronizeTaskType; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node.ReferenceReferentialSynchroNodeSupport; - -import javax.swing.Icon; -import java.util.function.Predicate; - -import static org.nuiton.i18n.I18n.n; - -/** - * Created on 12/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - */ -public enum ReferentialSynchronizeResources { - - ADD( - "copyToRight", - "copyToLeft", - n("observe.actions.synchro.referential.task.addToRight"), - n("observe.actions.synchro.referential.task.addToLeft"), - null, - null, - null, - null, - ReferentialSynchronizeTaskType.ADD, - ReferenceReferentialSynchroNodeSupport::isCanAdd), - UPDATE( - "copyToRight", - "copyToLeft", - n("observe.actions.synchro.referential.task.updateToRight"), - n("observe.actions.synchro.referential.task.updateToLeft"), - null, - null, - null, - null, - ReferentialSynchronizeTaskType.UPDATE, - ReferenceReferentialSynchroNodeSupport::isCanUpdate), - COPY( - "copyToRight", - "copyToLeft", - null, - null, - n("observe.actions.synchro.referential.action.copyToRight.tip"), - n("observe.actions.synchro.referential.action.copyToLeft.tip"), - ReferentialSynchroModel.COPY_LEFT_PROPERTY_NAME, - ReferentialSynchroModel.COPY_RIGHT_PROPERTY_NAME, - null, - node -> false), - DELETE( - "deleteFromLeft", - "deleteFromRight", - n("observe.actions.synchro.referential.task.deleteFromLeft"), - n("observe.actions.synchro.referential.task.deleteFromRight"), - n("observe.actions.synchro.referential.action.deleteFromLeft.tip"), - n("observe.actions.synchro.referential.action.deleteFromRight.tip"), - ReferentialSynchroModel.DELETE_LEFT_PROPERTY_NAME, - ReferentialSynchroModel.DELETE_RIGHT_PROPERTY_NAME, - ReferentialSynchronizeTaskType.DELETE, - ReferenceReferentialSynchroNodeSupport::isCanDelete), - REVERT( - "revertFromLeft", - "revertFromRight", - n("observe.actions.synchro.referential.task.revertFromLeft"), - n("observe.actions.synchro.referential.task.revertFromRight"), - n("observe.actions.synchro.referential.action.revertFromLeft.tip"), - n("observe.actions.synchro.referential.action.revertFromRight.tip"), - ReferentialSynchroModel.REVERT_LEFT_PROPERTY_NAME, - ReferentialSynchroModel.REVERT_RIGHT_PROPERTY_NAME, - ReferentialSynchronizeTaskType.REVERT, - ReferenceReferentialSynchroNodeSupport::isCanRevert), - SKIP( - "skipFromLeft", - "skipFromRight", - n("observe.actions.synchro.referential.task.skipFromLeft"), - n("observe.actions.synchro.referential.task.skipFromRight"), - n("observe.actions.synchro.referential.action.skipFromLeft.tip"), - n("observe.actions.synchro.referential.action.skipFromRight.tip"), - ReferentialSynchroModel.SKIP_LEFT_PROPERTY_NAME, - ReferentialSynchroModel.SKIP_RIGHT_PROPERTY_NAME, - null, - node -> true), - DESACTIVATE( - "desactivateFromLeft", - "desactivateFromRight", - n("observe.actions.synchro.referential.task.desactivateWithReplaceFromLeft"), - n("observe.actions.synchro.referential.task.desactivateWithReplaceFromRight"), - n("observe.actions.synchro.referential.action.desactivateFromLeft.tip"), - n("observe.actions.synchro.referential.action.desactivateFromRight.tip"), - ReferentialSynchroModel.DESACTIVATE_LEFT_PROPERTY_NAME, - ReferentialSynchroModel.DESACTIVATE_RIGHT_PROPERTY_NAME, - ReferentialSynchronizeTaskType.DESACTIVATE, - ReferenceReferentialSynchroNodeSupport::isCanDelete); - - private final String leftActionName; - private final String leftTaskI18nKey; - private final String rightActionName; - private final String leftActionTipI18nKey; - private final String rightTaskI18nKey; - private final String rightActionTipI18nKey; - private final String leftPropertyName; - private final String rightPropertyName; - private final Predicate<ReferenceReferentialSynchroNodeSupport> predicate; - private final ReferentialSynchronizeTaskType taskType; - private transient Icon actionIcon; - - ReferentialSynchronizeResources(String leftActionName, - String rightActionName, - String leftTaskI18nKey, - String rightTaskI18nKey, - String leftActionTipI18nKey, - String rightActionTipI18nKey, - String leftPropertyName, - String rightPropertyName, - ReferentialSynchronizeTaskType taskType, - Predicate<ReferenceReferentialSynchroNodeSupport> predicate) { - this.leftActionName = leftActionName; - this.rightActionName = rightActionName; - this.leftTaskI18nKey = leftTaskI18nKey; - this.rightTaskI18nKey = rightTaskI18nKey; - this.leftActionTipI18nKey = leftActionTipI18nKey; - this.rightActionTipI18nKey = rightActionTipI18nKey; - this.leftPropertyName = leftPropertyName; - this.rightPropertyName = rightPropertyName; - this.taskType = taskType; - this.predicate = predicate; - } - - public Predicate<ReferenceReferentialSynchroNodeSupport> getPredicate() { - return predicate; - } - - public Icon getIcon(boolean left) { - if (actionIcon == null) { - actionIcon = UIHelper.getUIManagerActionIcon(left ? leftActionName : rightActionName); - } - return actionIcon; - } - - public String getTaskLabel(boolean left) { - return left ? leftTaskI18nKey : rightTaskI18nKey; - } - - public String getActionTip(boolean left) { - return left ? leftActionTipI18nKey : rightActionTipI18nKey; - } - - public String getActionName(boolean left) { - return left ? leftActionName : rightActionName; - } - - public String getPropertyName(boolean left) { - return left ? leftPropertyName : rightPropertyName; - } - - public ReferentialSynchronizeTaskType getTaskType() { - return taskType; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchronizeTaskListCellRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchronizeTaskListCellRenderer.java deleted file mode 100644 index 1b7bfa8..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchronizeTaskListCellRenderer.java +++ /dev/null @@ -1,29 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng; - -import fr.ird.observe.ui.admin.synchronize.referential.ng.task.ReferentialSynchronizeTaskSupport; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.JList; -import java.awt.Component; - -/** - * Created on 03/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class ReferentialSynchronizeTaskListCellRenderer extends DefaultListCellRenderer { - - private static final long serialVersionUID = 1L; - - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { - - ReferentialSynchronizeTaskSupport task = (ReferentialSynchronizeTaskSupport) value; - super.getListCellRendererComponent(list, "<html><body>" + task.getLabel(), index, isSelected, cellHasFocus); - setIcon(task.getIcon()); - return this; - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchronizeTaskListModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchronizeTaskListModel.java deleted file mode 100644 index df8ddc0..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/ReferentialSynchronizeTaskListModel.java +++ /dev/null @@ -1,52 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng; - -import fr.ird.observe.ui.admin.synchronize.referential.ng.task.ReferentialSynchronizeTaskSupport; - -import javax.swing.DefaultListModel; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; - -/** - * Created on 13/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class ReferentialSynchronizeTaskListModel extends DefaultListModel<ReferentialSynchronizeTaskSupport> implements Iterable<ReferentialSynchronizeTaskSupport> { - - private static final long serialVersionUID = 1L; - - private boolean tasksIsAdjusting; - - public void addTasks(Collection<ReferentialSynchronizeTaskSupport> addedTasks) { - - tasksIsAdjusting = true; - try { - int minIndex = size(); - int maxIndex = minIndex + addedTasks.size() - 1; - ensureCapacity(maxIndex); - - for (ReferentialSynchronizeTaskSupport addedTask : addedTasks) { - addElement(addedTask); - } - - super.fireIntervalAdded(this, minIndex, maxIndex); - } finally { - tasksIsAdjusting = false; - } - } - - @Override - protected void fireIntervalAdded(Object source, int index0, int index1) { - if (tasksIsAdjusting) { - return; - } - super.fireIntervalAdded(source, index0, index1); - } - - @Override - public Iterator<ReferentialSynchronizeTaskSupport> iterator() { - return Collections.list(elements()).iterator(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/ApplyAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/ApplyAction.java deleted file mode 100644 index 6521a3f..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/ApplyAction.java +++ /dev/null @@ -1,86 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.action; - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.service.actions.synchro.referential.ReferentialSynchronizeMode; -import fr.ird.observe.services.service.actions.synchro.referential.ng.ReferentialSynchronizeServiceEngine; -import fr.ird.observe.services.service.actions.synchro.referential.ng.ReferentialSynchronizeServiceProduceSqlsRequest; -import fr.ird.observe.services.service.actions.synchro.referential.ng.ReferentialSynchronizeServiceProduceSqlsResult; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.actions.AbstractObserveAction; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchroModel; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchroUI; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchroUIHandler; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchronizeTaskListModel; -import fr.ird.observe.ui.admin.synchronize.referential.ng.task.ReferentialSynchronizeTaskSupport; -import jaxx.runtime.swing.wizard.ext.WizardState; - -import java.awt.event.ActionEvent; -import java.util.Set; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 12/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class ApplyAction extends AbstractObserveAction { - - private static final long serialVersionUID = 1L; - - private final ReferentialSynchroUI ui; - - public ApplyAction(ReferentialSynchroUI ui) { - super(t("observe.action.apply"), UIHelper.getUIManagerActionIcon("accept")); - this.ui = ui; - } - - @Override - public void actionPerformed(ActionEvent e) { - - ui.getHandler().addAdminWorker("Application des modifications.", this::apply); - - } - - private WizardState apply() { - - ReferentialSynchroModel stepModel = ui.getStepModel(); - - ReferentialSynchroUIHandler handler = ui.getHandler(); - - ReferentialSynchronizeMode synchronizeMode = stepModel.getSynchronizeMode(); - boolean leftIsWrite = synchronizeMode.isLeftWrite(); - boolean rightIsWrite = synchronizeMode.isRightWrite(); - - Set<Class<? extends ReferentialDto>> referentialTypesInShell = stepModel.getLeftSource().newDataSourceService().getReferentialTypesInShell(); - - ReferentialSynchronizeServiceProduceSqlsRequest.Builder builder = - ReferentialSynchronizeServiceProduceSqlsRequest.builder(stepModel.getLeftTreeModel().getIdsOnlyExistingInThisSide(), - stepModel.getRightTreeModel().getIdsOnlyExistingInThisSide(), - referentialTypesInShell); - - ReferentialSynchronizeTaskListModel tasks = stepModel.getTasks(); - - for (ReferentialSynchronizeTaskSupport task : tasks) { - - String taskLabel = t("observe.actions.synchro.referential.task.prepare", task.getStripLabel()); - - handler.sendMessage(taskLabel); - - task.registerTask(builder); - - } - - ReferentialSynchronizeServiceProduceSqlsRequest produceSqlsRequests = builder.build(); - - ReferentialSynchronizeServiceEngine engine = stepModel.newReferentialSynchronizeServiceEngine(); - - ReferentialSynchronizeServiceProduceSqlsResult sqlsRequests = engine.produceSqlsRequests(produceSqlsRequests); - - engine.executeSqlRequests(sqlsRequests); - - return WizardState.SUCCESSED; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterAddTaskAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterAddTaskAction.java deleted file mode 100644 index fc3c116..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterAddTaskAction.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.action; - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchroUI; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; -import fr.ird.observe.ui.admin.synchronize.referential.ng.task.AddReferentialSynchronizeTask; -import fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node.ReferenceReferentialSynchroNodeSupport; - -import java.util.Collection; -import java.util.function.Predicate; - -/** - * Created on 12/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class RegisterAddTaskAction extends RegisterTasksActionSupport { - - private static final long serialVersionUID = 1L; - private transient Collection<ReferenceReferentialSynchroNodeSupport> nodes; - - public RegisterAddTaskAction(ReferentialSynchroUI ui, boolean left) { - super(ui, ReferentialSynchronizeResources.ADD, left, false); - } - - @Override - protected <R extends ReferentialDto> AddReferentialSynchronizeTask<R> createTask(boolean left, ReferentialReference<R> reference, ReferentialReference<R> replaceReference) { - return new AddReferentialSynchronizeTask<>(left, reference); - } - - @Override - protected Collection<ReferenceReferentialSynchroNodeSupport> getReferenceReferentialSynchroNodes(Predicate<ReferenceReferentialSynchroNodeSupport> predicate) { - return nodes; - } - - public void updateNodes() { - - this.nodes = super.getReferenceReferentialSynchroNodes(predicate); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterCopyTaskAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterCopyTaskAction.java deleted file mode 100644 index 1f06ce3..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterCopyTaskAction.java +++ /dev/null @@ -1,41 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.action; - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchroUI; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; -import fr.ird.observe.ui.admin.synchronize.referential.ng.task.AddReferentialSynchronizeTask; - -/** - * Created on 12/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class RegisterCopyTaskAction extends RegisterTasksActionSupport { - - private static final long serialVersionUID = 1L; - - private final RegisterAddTaskAction addAction; - private final RegisterUpdateTaskAction updateAction; - - public RegisterCopyTaskAction(ReferentialSynchroUI ui, boolean left) { - super(ui, ReferentialSynchronizeResources.COPY, left, false); - addAction = new RegisterAddTaskAction(ui, left); - updateAction = new RegisterUpdateTaskAction(ui, left); - - } - - @Override - protected void createTasks() { - addAction.updateNodes(); - updateAction.updateNodes(); - addAction.createTasks(); - updateAction.createTasks(); - } - - @Override - protected <R extends ReferentialDto> AddReferentialSynchronizeTask<R> createTask(boolean left, ReferentialReference<R> reference, ReferentialReference<R> replaceReference) { - return new AddReferentialSynchronizeTask<>(left, reference); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterDeleteTaskAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterDeleteTaskAction.java deleted file mode 100644 index fde63d1..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterDeleteTaskAction.java +++ /dev/null @@ -1,34 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.action; - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchroUI; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; -import fr.ird.observe.ui.admin.synchronize.referential.ng.task.DeleteReferentialSynchronizeTask; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 12/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class RegisterDeleteTaskAction extends RegisterTasksActionSupport { - - private static final long serialVersionUID = 1L; - - public RegisterDeleteTaskAction(ReferentialSynchroUI ui, boolean left) { - super(ui, ReferentialSynchronizeResources.DELETE, left, true); - } - - @Override - protected String getReplaceTitle(ReferentialReference reference) { - return t("observe.actions.synchro.referential.replaceBeforeDelete.title", typeStr, referenceStr); - } - - @Override - protected <R extends ReferentialDto> DeleteReferentialSynchronizeTask<R> createTask(boolean left, ReferentialReference<R> reference, ReferentialReference<R> replaceReference) { - return new DeleteReferentialSynchronizeTask<>(left, reference, replaceReference); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterDesactivateTaskAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterDesactivateTaskAction.java deleted file mode 100644 index 4cd10f2..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterDesactivateTaskAction.java +++ /dev/null @@ -1,34 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.action; - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchroUI; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; -import fr.ird.observe.ui.admin.synchronize.referential.ng.task.DesactivateReferentialSynchronizeTask; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 12/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class RegisterDesactivateTaskAction extends RegisterTasksActionSupport { - - private static final long serialVersionUID = 1L; - - public RegisterDesactivateTaskAction(ReferentialSynchroUI ui, boolean left, boolean replace) { - super(ui, ReferentialSynchronizeResources.DESACTIVATE, left, replace); - } - - @Override - protected String getReplaceTitle(ReferentialReference reference) { - return t("observe.actions.synchro.referential.replaceBeforeDesactivate.title", typeStr, referenceStr); - } - - @Override - protected <R extends ReferentialDto> DesactivateReferentialSynchronizeTask<R> createTask(boolean left, ReferentialReference<R> reference, ReferentialReference<R> replaceReference) { - return new DesactivateReferentialSynchronizeTask<>(left, reference, replaceReference); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterRevertTaskAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterRevertTaskAction.java deleted file mode 100644 index cbf36dd..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterRevertTaskAction.java +++ /dev/null @@ -1,27 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.action; - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchroUI; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; -import fr.ird.observe.ui.admin.synchronize.referential.ng.task.RevertReferentialSynchronizeTask; - -/** - * Created on 12/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class RegisterRevertTaskAction extends RegisterTasksActionSupport { - - private static final long serialVersionUID = 1L; - - public RegisterRevertTaskAction(ReferentialSynchroUI ui, boolean left) { - super(ui, ReferentialSynchronizeResources.REVERT, left, false); - } - - @Override - protected <R extends ReferentialDto> RevertReferentialSynchronizeTask<R> createTask(boolean left, ReferentialReference<R> reference, ReferentialReference<R> replaceReference) { - return new RevertReferentialSynchronizeTask<>(left, reference); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterSkipTaskAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterSkipTaskAction.java deleted file mode 100644 index e52bd63..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterSkipTaskAction.java +++ /dev/null @@ -1,27 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.action; - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchroUI; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; -import fr.ird.observe.ui.admin.synchronize.referential.ng.task.SkipReferentialSynchronizeTask; - -/** - * Created on 12/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class RegisterSkipTaskAction extends RegisterTasksActionSupport { - - private static final long serialVersionUID = 1L; - - public RegisterSkipTaskAction(ReferentialSynchroUI ui, boolean left) { - super(ui, ReferentialSynchronizeResources.SKIP, left, false); - } - - @Override - protected <R extends ReferentialDto> SkipReferentialSynchronizeTask<R> createTask(boolean left, ReferentialReference<R> reference, ReferentialReference<R> replaceReference) { - return new SkipReferentialSynchronizeTask<>(left, reference); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterTasksActionSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterTasksActionSupport.java deleted file mode 100644 index d5ceb86..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterTasksActionSupport.java +++ /dev/null @@ -1,190 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.action; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.actions.AbstractObserveAction; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialReplaceUI; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialReplaceUIHandler; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchroUI; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; -import fr.ird.observe.ui.admin.synchronize.referential.ng.task.ReferentialSynchronizeTaskSupport; -import fr.ird.observe.ui.admin.synchronize.referential.ng.tree.ReferentialSynchronizeTreeModel; -import fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node.ReferenceReferentialSynchroNodeSupport; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import jaxx.runtime.context.JAXXInitialContext; -import org.apache.commons.lang3.NotImplementedException; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.i18n.I18n; - -import javax.swing.Action; -import javax.swing.JOptionPane; -import java.awt.event.ActionEvent; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; -import java.util.function.Predicate; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 12/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public abstract class RegisterTasksActionSupport extends AbstractObserveAction { - - /** Logger. */ - private static final Log log = LogFactory.getLog(RegisterTasksActionSupport.class); - - private static final long serialVersionUID = 1L; - protected final Predicate<ReferenceReferentialSynchroNodeSupport> predicate; - private final ReferentialSynchroUI ui; - private final boolean left; - private final boolean needReplace; - protected String typeStr; - protected String referenceStr; - - public RegisterTasksActionSupport(ReferentialSynchroUI ui, - ReferentialSynchronizeResources resource, - boolean left, - boolean needReplace) { - super(null, null); - String tip = resource.getActionTip(left); - if (tip != null) { - putValue(SHORT_DESCRIPTION, t(tip)); - } - String actionName = resource.getActionName(left); - if (actionName != null) { - putValue(Action.SMALL_ICON, UIHelper.getUIManagerActionIcon(actionName)); - } - this.ui = ui; - this.left = left; - this.needReplace = needReplace; - this.predicate = resource.getPredicate(); - String propertyName = resource.getPropertyName(left); - if (propertyName != null) { - ui.getModel().getReferentialSynchroModel().addPropertyChangeListener(propertyName, evt -> setEnabled((Boolean) evt.getNewValue())); - } - } - - protected abstract <R extends ReferentialDto> ReferentialSynchronizeTaskSupport<R> createTask(boolean left, ReferentialReference<R> reference, ReferentialReference<R> replaceReference); - - public boolean isLeft() { - return left; - } - - protected String getReplaceTitle(ReferentialReference reference) { - throw new NotImplementedException(""); - } - - @Override - public void actionPerformed(ActionEvent e) { - - ReferentialSynchronizeTreeModel treeModel = getTreeModel(); - - createTasks(); - - treeModel.clearSelection(); - - } - - protected void createTasks() { - createTasks(getTreeModel(), predicate); - } - - protected <R extends ReferentialDto> void createTasks(ReferentialSynchronizeTreeModel treeModel, Predicate<ReferenceReferentialSynchroNodeSupport> predicate) { - - Collection<ReferenceReferentialSynchroNodeSupport> removedNodes = new LinkedList<>(); - Collection<ReferentialSynchronizeTaskSupport> addedTasks = new LinkedList<>(); - - for (ReferenceReferentialSynchroNodeSupport node : getReferenceReferentialSynchroNodes(predicate)) { - - ReferentialReference<R> reference = node.getUserObject(); - ReferentialReference<R> replaceReference = null; - - if (needReplace) { - - Class<R> type = reference.getType(); - - List<ReferentialReference<R>> references = ui.getStepModel().getPossibleReplaceUniverse(left, type, reference); - - ReferentialReferenceDecorator<R> decorator = ObserveSwingApplicationContext.get().getDecoratorService().getReferentialReferenceDecorator(type); - - ReferentialReplaceUI<R> replaceUI = new ReferentialReplaceUI<>(new JAXXInitialContext() - .add(ReferentialReplaceUIHandler.CONTEXT_NAME, reference) - .add(ReferentialReplaceUIHandler.CONTEXT_NAME, references) - .add(ReferentialReplaceUIHandler.CONTEXT_NAME, decorator) - .add(this)); - - typeStr = t(DecoratorService.getEntityLabel(ObserveTreeHelper.TREE_NODE_PREFIX, type)); - referenceStr = ui.getHandler().getDecoratorService().getReferentialReferenceDecorator(type).toString(reference); - replaceUI.getMessage().setText(t("observe.actions.synchro.referential.replaceBefore.message", typeStr, referenceStr)); - - int response = UIHelper.askUser( - null, - t(getReplaceTitle(reference), typeStr, referenceStr), - replaceUI, - JOptionPane.WARNING_MESSAGE, - new Object[]{I18n.t("observe.choice.replace"), I18n.t("observe.choice.cancel")}, - 1); - - switch (response) { - case JOptionPane.CLOSED_OPTION: - case 1: - - break; - case 0: - replaceReference = replaceUI.getReplaceReference(); - break; - } - - if (log.isInfoEnabled()) { - log.info("replaceReference: " + replaceReference); - } - - if (replaceReference == null) { - if (log.isWarnEnabled()) { - log.warn("Skip this task, no replace referential reference selected"); - } - - continue; - } - - if (log.isInfoEnabled()) { - log.info("Selected replace referential reference: " + replaceReference); - } - - } - - ReferentialSynchronizeTaskSupport task = createTask(left, reference, replaceReference); - - if (log.isInfoEnabled()) { - log.info("Add " + task.getStripLabel()); - } - - ui.getHandler().sendMessage(task.getStripLabel()); - - removedNodes.add(node); - addedTasks.add(task); - - } - - treeModel.removeReferenceNodes(removedNodes); - ui.getStepModel().getTasks().addTasks(addedTasks); - } - - protected Collection<ReferenceReferentialSynchroNodeSupport> getReferenceReferentialSynchroNodes(Predicate<ReferenceReferentialSynchroNodeSupport> predicate) { - return getTreeModel().filterSelectedReferenceNodes(predicate); - } - - protected ReferentialSynchronizeTreeModel getTreeModel() { - return left ? ui.getStepModel().getLeftTreeModel() : ui.getStepModel().getRightTreeModel(); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterUpdateTaskAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterUpdateTaskAction.java deleted file mode 100644 index a7740f0..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/action/RegisterUpdateTaskAction.java +++ /dev/null @@ -1,43 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.action; - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchroUI; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; -import fr.ird.observe.ui.admin.synchronize.referential.ng.task.UpdateReferentialSynchronizeTask; -import fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node.ReferenceReferentialSynchroNodeSupport; - -import java.util.Collection; -import java.util.function.Predicate; - -/** - * Created on 12/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class RegisterUpdateTaskAction extends RegisterTasksActionSupport { - - private static final long serialVersionUID = 1L; - - private Collection<ReferenceReferentialSynchroNodeSupport> nodes; - - public RegisterUpdateTaskAction(ReferentialSynchroUI ui, boolean left) { - super(ui, ReferentialSynchronizeResources.UPDATE, left, false); - } - - @Override - protected <R extends ReferentialDto> UpdateReferentialSynchronizeTask<R> createTask(boolean left, ReferentialReference<R> reference, ReferentialReference<R> replaceReference) { - return new UpdateReferentialSynchronizeTask<>(left, reference); - } - - @Override - protected Collection<ReferenceReferentialSynchroNodeSupport> getReferenceReferentialSynchroNodes(Predicate<ReferenceReferentialSynchroNodeSupport> predicate) { - return nodes; - } - - public void updateNodes() { - this.nodes = super.getReferenceReferentialSynchroNodes(predicate); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/AddReferentialSynchronizeTask.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/AddReferentialSynchronizeTask.java deleted file mode 100644 index 44ae959..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/AddReferentialSynchronizeTask.java +++ /dev/null @@ -1,19 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.task; - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; - -/** - * Created on 09/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class AddReferentialSynchronizeTask<R extends ReferentialDto> extends ReferentialSynchronizeTaskSupport<R> { - - public AddReferentialSynchronizeTask(boolean left, ReferentialReference<R> data) { - super(ReferentialSynchronizeResources.ADD, left, data); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/DeleteReferentialSynchronizeTask.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/DeleteReferentialSynchronizeTask.java deleted file mode 100644 index 71dd314..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/DeleteReferentialSynchronizeTask.java +++ /dev/null @@ -1,19 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.task; - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; - -/** - * Created on 09/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class DeleteReferentialSynchronizeTask<R extends ReferentialDto> extends ReferentialSynchronizeTaskWithReplaceSupport<R> { - - public DeleteReferentialSynchronizeTask(boolean left, ReferentialReference<R> data, ReferentialReference<R> replaceData) { - super(ReferentialSynchronizeResources.DELETE, left, data, replaceData); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/DesactivateReferentialSynchronizeTask.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/DesactivateReferentialSynchronizeTask.java deleted file mode 100644 index 3ce1210..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/DesactivateReferentialSynchronizeTask.java +++ /dev/null @@ -1,40 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.task; - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 09/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class DesactivateReferentialSynchronizeTask<R extends ReferentialDto> extends ReferentialSynchronizeTaskWithReplaceSupport<R> { - - private final String withoutReplaceI18nKey; - - public DesactivateReferentialSynchronizeTask(boolean left, ReferentialReference<R> data, ReferentialReference<R> replaceData) { - super(ReferentialSynchronizeResources.DESACTIVATE, left, data, replaceData); - - withoutReplaceI18nKey = left - ? n("observe.actions.synchro.referential.task.desactivateFromLeft") - : n("observe.actions.synchro.referential.task.desactivateFromRight"); - } - - @Override - public String getLabel() { - if (replaceDataStr == null) { - - // sans remplacement - return t(withoutReplaceI18nKey, typeStr, dataStr); - - } else { - - return super.getLabel(); - } - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/ReferentialSynchronizeTaskSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/ReferentialSynchronizeTaskSupport.java deleted file mode 100644 index 2076bc2..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/ReferentialSynchronizeTaskSupport.java +++ /dev/null @@ -1,79 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.task; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.service.actions.synchro.referential.ng.ReferentialSynchronizeServiceProduceSqlsRequest; -import fr.ird.observe.services.service.actions.synchro.referential.ng.task.ReferentialSynchronizeTaskType; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; - -import javax.swing.Icon; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 03/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public abstract class ReferentialSynchronizeTaskSupport<R extends ReferentialDto> { - - protected final String dataStr; - protected final String typeStr; - protected final String i18nKey; - private final ReferentialReference<R> referential; - private final Icon icon; - private final boolean left; - private final ReferentialSynchronizeTaskType taskType; - - protected ReferentialSynchronizeTaskSupport(ReferentialSynchronizeResources resource, - boolean left, - ReferentialReference<R> referential) { - this.left = left; - this.referential = referential; - this.icon = resource.getIcon(left); - this.i18nKey = resource.getTaskLabel(left); - this.taskType = resource.getTaskType(); - this.dataStr = ObserveSwingApplicationContext.get().getDecoratorService().getReferentialReferenceDecorator(referential.getType()).toString(referential); - this.typeStr = t(DecoratorService.getEntityLabel(referential.getType())); - } - - public boolean isLeft() { - return left; - } - - public ReferentialSynchronizeTaskType getTaskType() { - return taskType; - } - - public String getLabel() { - return t(i18nKey, typeStr, dataStr); - } - - public String getStripLabel() { - return getLabel().replaceAll("<[^>]+>", ""); - } - - public Class<R> getType() { - return referential.getType(); - } - - public String getId() { - return referential.getId(); - } - - public ReferentialReference<R> getReferential() { - return referential; - } - - public Icon getIcon() { - return icon; - } - - public void registerTask(ReferentialSynchronizeServiceProduceSqlsRequest.Builder builder) { - builder.addTask(isLeft(), taskType, getType(), getId(), null); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/ReferentialSynchronizeTaskWithReplaceSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/ReferentialSynchronizeTaskWithReplaceSupport.java deleted file mode 100644 index ace9be9..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/ReferentialSynchronizeTaskWithReplaceSupport.java +++ /dev/null @@ -1,39 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.task; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.service.actions.synchro.referential.ng.ReferentialSynchronizeServiceProduceSqlsRequest; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 11/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - */ -public abstract class ReferentialSynchronizeTaskWithReplaceSupport<R extends ReferentialDto> extends ReferentialSynchronizeTaskSupport<R> { - - protected final String replaceDataStr; - private final ReferentialReference<R> replaceData; - - protected ReferentialSynchronizeTaskWithReplaceSupport(ReferentialSynchronizeResources resource, boolean left, ReferentialReference<R> data, ReferentialReference<R> replaceData) { - super(resource, left, data); - this.replaceData = replaceData; - this.replaceDataStr = replaceData == null ? null : ObserveSwingApplicationContext.get().getDecoratorService().getReferentialReferenceDecorator(replaceData.getType()).toString(replaceData); - } - - public String getReplaceId() { - return replaceData == null ? null : replaceData.getId(); - } - - @Override - public String getLabel() { - return t(i18nKey, typeStr, dataStr, replaceDataStr); - } - - public void registerTask(ReferentialSynchronizeServiceProduceSqlsRequest.Builder builder) { - builder.addTask(isLeft(), getTaskType(), getType(), getId(), getReplaceId()); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/RevertReferentialSynchronizeTask.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/RevertReferentialSynchronizeTask.java deleted file mode 100644 index 0398e29..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/RevertReferentialSynchronizeTask.java +++ /dev/null @@ -1,19 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.task; - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; - -/** - * Created on 09/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class RevertReferentialSynchronizeTask<R extends ReferentialDto> extends ReferentialSynchronizeTaskSupport<R> { - - public RevertReferentialSynchronizeTask(boolean left, ReferentialReference<R> data) { - super(ReferentialSynchronizeResources.REVERT, left, data); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/SkipReferentialSynchronizeTask.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/SkipReferentialSynchronizeTask.java deleted file mode 100644 index 63b11f8..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/SkipReferentialSynchronizeTask.java +++ /dev/null @@ -1,24 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.task; - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.service.actions.synchro.referential.ng.ReferentialSynchronizeServiceProduceSqlsRequest; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; - -/** - * Created on 09/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class SkipReferentialSynchronizeTask<R extends ReferentialDto> extends ReferentialSynchronizeTaskSupport<R> { - - public SkipReferentialSynchronizeTask(boolean left, ReferentialReference<R> data) { - super(ReferentialSynchronizeResources.SKIP, left, data); - } - - @Override - public void registerTask(ReferentialSynchronizeServiceProduceSqlsRequest.Builder builder) { - // Skip! - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/UpdateReferentialSynchronizeTask.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/UpdateReferentialSynchronizeTask.java deleted file mode 100644 index 7a0091a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/task/UpdateReferentialSynchronizeTask.java +++ /dev/null @@ -1,19 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.task; - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.admin.synchronize.referential.ng.ReferentialSynchronizeResources; - -/** - * Created on 09/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class UpdateReferentialSynchronizeTask<R extends ReferentialDto> extends ReferentialSynchronizeTaskSupport<R> { - - public UpdateReferentialSynchronizeTask(boolean left, ReferentialReference<R> data) { - super(ReferentialSynchronizeResources.UPDATE, left, data); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/ReferentialSynchronizeTreeCellRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/ReferentialSynchronizeTreeCellRenderer.java deleted file mode 100644 index 7d97370..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/ReferentialSynchronizeTreeCellRenderer.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin.synchronize.referential.ng.tree; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node.ReferenceReferentialSynchroNodeSupport; -import fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node.ReferentialSynchroNodeSupport; -import fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node.TypeReferentialSynchroNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.decorator.Decorator; - -import javax.swing.Icon; -import javax.swing.JTree; -import javax.swing.tree.DefaultTreeCellRenderer; -import java.awt.Color; -import java.awt.Component; - -import static org.nuiton.i18n.I18n.t; - -/** - * Le renderer pour décorer l'arbre de sélection des données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.2 - */ -public class ReferentialSynchronizeTreeCellRenderer extends DefaultTreeCellRenderer { - - /** Logger */ - private static final Log log = LogFactory.getLog(ReferentialSynchronizeTreeCellRenderer.class); - - private static final long serialVersionUID = 1L; - - protected transient DecoratorService decoratorService; - - public ReferentialSynchronizeTreeCellRenderer() { - - setBackgroundNonSelectionColor(null); - setBackgroundSelectionColor(null); - setBackground(null); - - setTextNonSelectionColor(Color.BLACK); - setTextSelectionColor(Color.BLUE); - } - - public DecoratorService getDecoratorService() { - if (decoratorService == null) { - decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); - } - return decoratorService; - } - - @Override - public Component getTreeCellRendererComponent( - JTree tree, - Object value, - boolean sel, - boolean expanded, - boolean leaf, - int row, - boolean hasFocus) { - - if (!(value instanceof ReferentialSynchroNodeSupport)) { - return this; - } - - // get the icon to set for the node - ReferentialSynchroNodeSupport node = (ReferentialSynchroNodeSupport) value; - - String text = null; - Icon icon = null; - if (node instanceof TypeReferentialSynchroNode) { - TypeReferentialSynchroNode node1 = (TypeReferentialSynchroNode) node; - icon = node1.getIcon(); - text = "<html><body>" + t(DecoratorService.getEntityLabel(ObserveTreeHelper.TREE_NODE_PREFIX, node1.getUserObject())); - int childCount = node1.getChildCount(); - text += " <i>(" + childCount + ")</i>"; - } else if (node instanceof ReferenceReferentialSynchroNodeSupport) { - ReferenceReferentialSynchroNodeSupport node1 = (ReferenceReferentialSynchroNodeSupport) node; - - icon = node1.getIcon(); - ReferentialReference reference = node1.getUserObject(); - Decorator<?> decorator = getDecoratorService().getReferentialReferenceDecorator(reference.getType()); - text = "<html><body>" + decorator.toString(reference); - text += " <i>(" + reference.getVersion() + " - " + reference.getLastUpdateDate() + ")</i>"; - } - - Component comp = super.getTreeCellRendererComponent(tree, text, sel, expanded, leaf, row, hasFocus); - - setIcon(icon); - setToolTipText(text); - return comp; - } - - @Override - public Color getBackgroundNonSelectionColor() { - // Fixes http://forge.codelutin.com/issues/830 for jdk 7 - return Color.WHITE; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/ReferentialSynchronizeTreeModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/ReferentialSynchronizeTreeModel.java deleted file mode 100644 index 2363892..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/ReferentialSynchronizeTreeModel.java +++ /dev/null @@ -1,393 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.tree; - -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.ImmutableSetMultimap; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node.ReferenceReferentialSynchroNodeSupport; -import fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node.ReferentialSynchroNodeSupport; -import fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node.RootReferentialSynchroNode; -import fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node.TypeReferentialSynchroNode; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.event.TreeModelListener; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.DefaultTreeSelectionModel; -import javax.swing.tree.RowMapper; -import javax.swing.tree.TreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; -import java.beans.PropertyChangeListener; -import java.io.Serializable; -import java.util.Collection; -import java.util.Enumeration; -import java.util.LinkedList; -import java.util.function.Predicate; - -/** - * Created on 10/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - */ -public class ReferentialSynchronizeTreeModel implements TreeSelectionModel, TreeModel, Serializable { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(ReferentialSynchronizeTreeModel.class); - - private final DefaultTreeSelectionModel treeSelectionModel; - private final DefaultTreeModel treeModel; - private final ImmutableSetMultimap<Class<? extends ReferentialDto>, String> idsOnlyExistOnThisSide; - - private boolean canAdd; - private boolean canUpdate; - private boolean canDelete; - private boolean canRevert; - private boolean valueIsAdjusting; - - public ReferentialSynchronizeTreeModel(RootReferentialSynchroNode root, - ImmutableSetMultimap<Class<? extends ReferentialDto>, String> idsOnlyExistOnThisSide) { - this.treeModel = new DefaultTreeModel(root); - this.idsOnlyExistOnThisSide = idsOnlyExistOnThisSide; - this.treeSelectionModel = new DefaultTreeSelectionModel(); - setSelectionMode(DISCONTIGUOUS_TREE_SELECTION); - } - - public ImmutableSetMultimap<Class<? extends ReferentialDto>, String> getIdsOnlyExistingInThisSide() { - return idsOnlyExistOnThisSide; - } - - - public synchronized void updateSelectedActions() { - - canAdd = canUpdate = canDelete = canRevert = false; - - for (TreePath selectionPath : getSelectionPaths()) { - ReferentialSynchroNodeSupport lastPathComponent = (ReferentialSynchroNodeSupport) selectionPath.getLastPathComponent(); - - if (lastPathComponent instanceof ReferenceReferentialSynchroNodeSupport) { - - ReferenceReferentialSynchroNodeSupport node = (ReferenceReferentialSynchroNodeSupport) lastPathComponent; - canAdd |= node.isCanAdd(); - canUpdate |= node.isCanUpdate(); - canDelete |= node.isCanDelete(); - canRevert |= node.isCanRevert(); - - } - - } - - } - - public Collection<ReferenceReferentialSynchroNodeSupport> filterSelectedReferenceNodes(Predicate<ReferenceReferentialSynchroNodeSupport> predicate) { - - ImmutableSet.Builder<ReferenceReferentialSynchroNodeSupport> builder = ImmutableSet.builder(); - - for (TreePath selectionPath : getSelectionPaths()) { - ReferentialSynchroNodeSupport lastPathComponent = (ReferentialSynchroNodeSupport) selectionPath.getLastPathComponent(); - if (lastPathComponent instanceof ReferenceReferentialSynchroNodeSupport) { - ReferenceReferentialSynchroNodeSupport node = (ReferenceReferentialSynchroNodeSupport) lastPathComponent; - if (predicate.test(node)) { - builder.add(node); - } - } - } - return builder.build(); - } - - public boolean isCanAdd() { - return canAdd; - } - - public boolean isCanUpdate() { - return canUpdate; - } - - public boolean isCanDelete() { - return canDelete; - } - - public boolean isCanRevert() { - return canRevert; - } - - public boolean isCanSkip() { - return getSelectionCount() > 0; - } - - public boolean isLeft() { - return getRoot().isLeft(); - } - - public void removeReferenceNode(ReferenceReferentialSynchroNodeSupport node) { - - TypeReferentialSynchroNode parent = node.getParent(); - treeModel.removeNodeFromParent(node); - if (parent.isLeaf()) { - treeModel.removeNodeFromParent(parent); - } else { - treeModel.reload(parent); - } - } - - @Override - public RootReferentialSynchroNode getRoot() { - return (RootReferentialSynchroNode) treeModel.getRoot(); - } - - @Override - public Object getChild(Object parent, int index) { - return treeModel.getChild(parent, index); - } - - @Override - public int getChildCount(Object parent) { - return treeModel.getChildCount(parent); - } - - @Override - public boolean isLeaf(Object node) { - return treeModel.isLeaf(node); - } - - @Override - public void valueForPathChanged(TreePath path, Object newValue) { - treeModel.valueForPathChanged(path, newValue); - } - - @Override - public int getIndexOfChild(Object parent, Object child) { - return treeModel.getIndexOfChild(parent, child); - } - - @Override - public void addTreeModelListener(TreeModelListener l) { - treeModel.addTreeModelListener(l); - } - - @Override - public void removeTreeModelListener(TreeModelListener l) { - treeModel.removeTreeModelListener(l); - } - - @Override - public int getSelectionMode() { - return treeSelectionModel.getSelectionMode(); - } - - @Override - public void setSelectionMode(int mode) { - treeSelectionModel.setSelectionMode(mode); - } - - @Override - public void addSelectionPath(TreePath path) { - addSelectionPaths(path); - } - - @Override - public void removeSelectionPath(TreePath path) { - removeSelectionPaths(path); - } - - @Override - public void addSelectionPaths(TreePath... paths) { - - valueIsAdjusting = true; - - try { - Collection<TreePath> collectedPaths = new LinkedList<>(); - - collectPaths(collectedPaths, paths); - - if (log.isDebugEnabled()) { - log.debug("path(s) to add: " + collectedPaths.size()); - } - treeSelectionModel.addSelectionPaths(collectedPaths.toArray(new TreePath[collectedPaths.size()])); - } finally { - - valueIsAdjusting = false; - - } - } - - @Override - public void removeSelectionPaths(TreePath... paths) { - - if (valueIsAdjusting) { - return; - } - - valueIsAdjusting = true; - - try { - Collection<TreePath> collectedPaths = new LinkedList<>(); - - collectPaths(collectedPaths, paths); - - if (log.isDebugEnabled()) { - log.debug("path(s) to remove: " + collectedPaths.size()); - } - treeSelectionModel.removeSelectionPaths(collectedPaths.toArray(new TreePath[collectedPaths.size()])); - } finally { - - valueIsAdjusting = false; - - } - - } - - @Override - public TreePath getSelectionPath() { - return treeSelectionModel.getSelectionPath(); - } - - @Override - public void setSelectionPath(TreePath path) { - - if (isPathSelected(path)) { - removeSelectionPaths(path); - } else { - addSelectionPaths(path); - } - - } - - @Override - public TreePath[] getSelectionPaths() { - return treeSelectionModel.getSelectionPaths(); - } - - @Override - public void setSelectionPaths(TreePath[] paths) { - treeSelectionModel.setSelectionPaths(paths); - } - - @Override - public int getSelectionCount() { - return treeSelectionModel.getSelectionCount(); - } - - @Override - public boolean isPathSelected(TreePath path) { - return treeSelectionModel.isPathSelected(path); - } - - @Override - public boolean isSelectionEmpty() { - return treeSelectionModel.isSelectionEmpty(); - } - - @Override - public void clearSelection() { - treeSelectionModel.clearSelection(); - } - - @Override - public RowMapper getRowMapper() { - return treeSelectionModel.getRowMapper(); - } - - @Override - public void setRowMapper(RowMapper newMapper) { - treeSelectionModel.setRowMapper(newMapper); - } - - @Override - public int[] getSelectionRows() { - return treeSelectionModel.getSelectionRows(); - } - - @Override - public int getMinSelectionRow() { - return treeSelectionModel.getMinSelectionRow(); - } - - @Override - public int getMaxSelectionRow() { - return treeSelectionModel.getMaxSelectionRow(); - } - - @Override - public boolean isRowSelected(int row) { - return treeSelectionModel.isRowSelected(row); - } - - @Override - public void resetRowSelection() { - treeSelectionModel.resetRowSelection(); - } - - @Override - public int getLeadSelectionRow() { - return treeSelectionModel.getLeadSelectionRow(); - } - - @Override - public TreePath getLeadSelectionPath() { - return treeSelectionModel.getLeadSelectionPath(); - } - - @Override - public void addPropertyChangeListener(PropertyChangeListener listener) { - treeSelectionModel.addPropertyChangeListener(listener); - } - - @Override - public void removePropertyChangeListener(PropertyChangeListener listener) { - treeSelectionModel.removePropertyChangeListener(listener); - } - - @Override - public void addTreeSelectionListener(TreeSelectionListener x) { - treeSelectionModel.addTreeSelectionListener(x); - } - - @Override - public void removeTreeSelectionListener(TreeSelectionListener x) { - treeSelectionModel.removeTreeSelectionListener(x); - } - - private void collectPaths(Collection<TreePath> collectedPaths, TreePath... paths) { - for (TreePath path : paths) { - - collectedPaths.add(path); - - Object node = path.getLastPathComponent(); - - if (node instanceof TypeReferentialSynchroNode) { - TypeReferentialSynchroNode node1 = (TypeReferentialSynchroNode) node; - - Enumeration children = node1.children(); - while (children.hasMoreElements()) { - ReferenceReferentialSynchroNodeSupport childNode = (ReferenceReferentialSynchroNodeSupport) children.nextElement(); - collectedPaths.add(path.pathByAddingChild(childNode)); - } - - } - - } - - } - - public void removeReferenceNodes(Collection<ReferenceReferentialSynchroNodeSupport> removedNodes) { - - valueIsAdjusting = true; - - try { - for (ReferenceReferentialSynchroNodeSupport removedNode : removedNodes) { - TypeReferentialSynchroNode typeNode = removedNode.getParent(); - if (typeNode.getChildCount() == 1) { - treeModel.removeNodeFromParent(typeNode); - } else { - treeModel.removeNodeFromParent(removedNode); - } - } - } finally { - valueIsAdjusting = false; - } - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/ReferentialSynchronizeTreeModelsBuilder.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/ReferentialSynchronizeTreeModelsBuilder.java deleted file mode 100644 index 8aec5bd..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/ReferentialSynchronizeTreeModelsBuilder.java +++ /dev/null @@ -1,171 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.tree; - -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.ImmutableSetMultimap; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.ReferentialReferenceSet; -import fr.ird.observe.services.service.actions.synchro.referential.ReferentialSynchronizeMode; -import fr.ird.observe.services.service.actions.synchro.referential.diff.ReferentialSynchronizeDiff; -import fr.ird.observe.services.service.actions.synchro.referential.diff.ReferentialSynchronizeDiffState; -import fr.ird.observe.services.service.actions.synchro.referential.diff.ReferentialSynchronizeDiffs; -import fr.ird.observe.services.service.actions.synchro.referential.diff.ReferentialSynchronizeDiffsEngine; -import fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node.AddedReferenceReferentialSynchroNode; -import fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node.ReferenceReferentialSynchroNodeSupport; -import fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node.RootReferentialSynchroNode; -import fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node.TypeReferentialSynchroNode; -import fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node.UpdatedReferenceReferentialSynchroNode; -import org.apache.commons.lang3.tuple.Pair; - -import java.util.Objects; -import java.util.Optional; - -/** - * Created on 11/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - */ -public class ReferentialSynchronizeTreeModelsBuilder { - - private final ReferentialSynchronizeDiffsEngine engine; - private final RootReferentialSynchroNode leftRootNode; - private final RootReferentialSynchroNode rightRootNode; - private final ImmutableSetMultimap.Builder<Class<? extends ReferentialDto>, String> leftIdsBuilder = ImmutableSetMultimap.builder(); - private final ImmutableSetMultimap.Builder<Class<? extends ReferentialDto>, String> rightIdsBuilder = ImmutableSetMultimap.builder(); - - public ReferentialSynchronizeTreeModelsBuilder(ReferentialSynchronizeMode synchronizeMode, ReferentialSynchronizeDiffsEngine engine) { - Objects.nonNull(synchronizeMode); - Objects.nonNull(engine); - this.engine = engine; - this.leftRootNode = new RootReferentialSynchroNode(true, synchronizeMode.isLeftWrite()); - this.rightRootNode = new RootReferentialSynchroNode(false, synchronizeMode.isRightWrite()); - } - - public Pair<ReferentialSynchronizeTreeModel, ReferentialSynchronizeTreeModel> build() { - - ReferentialSynchronizeDiffs synchronizeDiffs = engine.build(); - - ImmutableSet<Class<? extends ReferentialDto>> referentialNames = synchronizeDiffs.getReferentialNames(); - - ReferentialSynchronizeDiff leftDiff = synchronizeDiffs.getLeftDiff(); - ReferentialSynchronizeDiff rightDiff = synchronizeDiffs.getRightDiff(); - - boolean rightCanWrite = rightRootNode.isCanWrite(); - boolean leftCanWrite = leftRootNode.isCanWrite(); - - CreateAddNode leftAddNode = new CreateAddNode(rightCanWrite, leftCanWrite, false); - CreateAddNode rightAddNode = new CreateAddNode(leftCanWrite, rightCanWrite, false); - CreateNode leftUpdateNode = new CreateUpdateNode(rightCanWrite, false, leftCanWrite); - CreateNode rightUpdateNode = new CreateUpdateNode(leftCanWrite, false, rightCanWrite); - - for (Class<? extends ReferentialDto> referentialName : referentialNames) { - - { - // Tous les référentiels ajoutés à gauche peuvent être copié à droite - Optional<ImmutableSet<ReferentialSynchronizeDiffState>> optionalDiffStates = leftDiff.getAddedReferentials(referentialName); - if (optionalDiffStates.isPresent()) { - addFromLeft(leftRootNode, optionalDiffStates.get(), referentialName, leftAddNode); - } - } - { - // Tous les référentiels mises à jour à gauche peuvent être copié à droite - Optional<ImmutableSet<ReferentialSynchronizeDiffState>> optionalDiffStates = leftDiff.getUpdatedReferentials(referentialName); - if (optionalDiffStates.isPresent()) { - addFromLeft(leftRootNode, optionalDiffStates.get(), referentialName, leftUpdateNode); - } - } - { - // Tous les référentiels ajoutés à droite peuvent être supprimé ou désactivés - Optional<ImmutableSet<ReferentialSynchronizeDiffState>> optionalDiffStates = rightDiff.getAddedReferentials(referentialName); - if (optionalDiffStates.isPresent()) { - addFromRight(rightRootNode, optionalDiffStates.get(), referentialName, rightAddNode); - } - } - { - // Tous les référentiels mises à jour à droite peuvent être remis en arrière - Optional<ImmutableSet<ReferentialSynchronizeDiffState>> optionalDiffStates = rightDiff.getUpdatedReferentials(referentialName); - if (optionalDiffStates.isPresent()) { - addFromRight(rightRootNode, optionalDiffStates.get(), referentialName, rightUpdateNode); - } - } - - } - - ReferentialSynchronizeTreeModel leftTreeModel = new ReferentialSynchronizeTreeModel(leftRootNode, leftAddNode.getIds()); - ReferentialSynchronizeTreeModel rightTreeModel = new ReferentialSynchronizeTreeModel(rightRootNode, rightAddNode.getIds()); - return Pair.of(leftTreeModel, rightTreeModel); - - } - - private <R extends ReferentialDto> void addFromLeft(RootReferentialSynchroNode rootNode, ImmutableSet<ReferentialSynchronizeDiffState> diffStates, Class<R> referentialName, CreateNode createNode) { - ReferentialReferenceSet<R> referenceSet = engine.getLeftReferentialReferenceSet(referentialName, diffStates); - ImmutableSet<ReferentialReference<R>> references = referenceSet.getReferences(); - if (!references.isEmpty()) { - TypeReferentialSynchroNode typeNode = rootNode.getOrAddTypeNode(referentialName); - for (ReferentialReference<R> reference : references) { - createNode.createNode(typeNode, reference); - } - - } - } - - private <R extends ReferentialDto> void addFromRight(RootReferentialSynchroNode rootNode, ImmutableSet<ReferentialSynchronizeDiffState> diffStates, Class<R> referentialName, CreateNode createNode) { - ReferentialReferenceSet<R> referenceSet = engine.getRightReferentialReferenceSet(referentialName, diffStates); - ImmutableSet<ReferentialReference<R>> references = referenceSet.getReferences(); - if (!references.isEmpty()) { - TypeReferentialSynchroNode typeNode = rootNode.getOrAddTypeNode(referentialName); - for (ReferentialReference<R> reference : references) { - createNode.createNode(typeNode, reference); - } - } - } - - private static abstract class CreateNode { - - protected final boolean canCopy; - protected final boolean canDelete; - protected final boolean canRevert; - - protected CreateNode(boolean canCopy, boolean canDelete, boolean canRevert) { - this.canCopy = canCopy; - this.canDelete = canDelete; - this.canRevert = canRevert; - } - - public abstract void createNode(TypeReferentialSynchroNode typeNode, ReferentialReference<?> reference); - - } - - private static class CreateAddNode extends CreateNode { - - private final ImmutableSetMultimap.Builder<Class<? extends ReferentialDto>, String> idsBuilder = ImmutableSetMultimap.builder(); - - protected CreateAddNode(boolean canCopy, boolean canDelete, boolean canRevert) { - super(canCopy, canDelete, canRevert); - } - - @Override - public void createNode(TypeReferentialSynchroNode typeNode, ReferentialReference<?> reference) { - ReferenceReferentialSynchroNodeSupport node = new AddedReferenceReferentialSynchroNode(reference, canCopy, false, canDelete, canRevert); - typeNode.add(node); - idsBuilder.put(reference.getType(), reference.getId()); - } - - public ImmutableSetMultimap<Class<? extends ReferentialDto>, String> getIds() { - return idsBuilder.build(); - } - } - - private static class CreateUpdateNode extends CreateNode { - - protected CreateUpdateNode(boolean canCopy, boolean canDelete, boolean canRevert) { - super(canCopy, canDelete, canRevert); - } - - @Override - public void createNode(TypeReferentialSynchroNode typeNode, ReferentialReference<?> reference) { - ReferenceReferentialSynchroNodeSupport node = new UpdatedReferenceReferentialSynchroNode(reference, false, canCopy, canDelete, canRevert); - typeNode.add(node); - } - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/node/AddedReferenceReferentialSynchroNode.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/node/AddedReferenceReferentialSynchroNode.java deleted file mode 100644 index dcb31f5..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/node/AddedReferenceReferentialSynchroNode.java +++ /dev/null @@ -1,20 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node; - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; - -/** - * Created on 11/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - */ -public class AddedReferenceReferentialSynchroNode extends ReferenceReferentialSynchroNodeSupport { - - private static final long serialVersionUID = 1L; - - public AddedReferenceReferentialSynchroNode(ReferentialReference<? extends ReferentialDto> referentialReference, boolean canAdd, boolean canUpdate, boolean canDelete, boolean canRevert) { - super(referentialReference, "synchroAdd", canAdd, canUpdate, canDelete, canRevert); - } - - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/node/ReferenceReferentialSynchroNodeSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/node/ReferenceReferentialSynchroNodeSupport.java deleted file mode 100644 index 0ebb9d2..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/node/ReferenceReferentialSynchroNodeSupport.java +++ /dev/null @@ -1,61 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node; - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.UIHelper; - -/** - * Created on 09/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public abstract class ReferenceReferentialSynchroNodeSupport extends ReferentialSynchroNodeSupport { - - private static final long serialVersionUID = 1L; - - private final boolean canAdd; - private final boolean canUpdate; - private final boolean canDelete; - private final boolean canRevert; - - protected ReferenceReferentialSynchroNodeSupport(ReferentialReference<? extends ReferentialDto> referentialReference, - String iconName, - boolean canAdd, - boolean canUpdate, - boolean canDelete, - boolean canRevert) { - super(UIHelper.createActionIcon(iconName), referentialReference); - this.canAdd = canAdd; - this.canUpdate = canUpdate; - this.canDelete = canDelete; - this.canRevert = canRevert; - } - - public boolean isCanAdd() { - return canAdd; - } - - public boolean isCanUpdate() { - return canUpdate; - } - - public boolean isCanDelete() { - return canDelete; - } - - public boolean isCanRevert() { - return canRevert; - } - - @Override - public TypeReferentialSynchroNode getParent() { - return (TypeReferentialSynchroNode) super.getParent(); - } - - @Override - public ReferentialReference getUserObject() { - return (ReferentialReference) super.getUserObject(); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/node/ReferentialSynchroNodeSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/node/ReferentialSynchroNodeSupport.java deleted file mode 100644 index a206fe9..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/node/ReferentialSynchroNodeSupport.java +++ /dev/null @@ -1,38 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node; - -import javax.swing.Icon; -import javax.swing.tree.DefaultMutableTreeNode; - -/** - * Created on 09/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - */ -public abstract class ReferentialSynchroNodeSupport extends DefaultMutableTreeNode { - - private static final long serialVersionUID = 1L; - - private transient Icon icon; - - protected ReferentialSynchroNodeSupport(Icon icon, Object userObject) { - setUserObject(userObject); - this.icon = icon; - } - - public Icon getIcon() { - return icon; - } - - public boolean isLeft() { - return getRoot().isLeaf(); - } - - public boolean isRight() { - return !isLeft(); - } - - @Override - public ReferentialSynchroNodeSupport getParent() { - return (ReferentialSynchroNodeSupport) super.getParent(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/node/RootReferentialSynchroNode.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/node/RootReferentialSynchroNode.java deleted file mode 100644 index 3ba65dd..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/node/RootReferentialSynchroNode.java +++ /dev/null @@ -1,55 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node; - -import fr.ird.observe.services.dto.referential.ReferentialDto; - -import java.util.Enumeration; - -/** - * Created on 10/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class RootReferentialSynchroNode extends ReferentialSynchroNodeSupport { - - private static final long serialVersionUID = 1L; - - private final boolean left; - private final boolean canWrite; - - public RootReferentialSynchroNode(boolean left, boolean canWrite) { - super(null, null); - this.left = left; - this.canWrite = canWrite; - } - - @Override - public boolean isLeft() { - return left; - } - - public boolean isCanWrite() { - return canWrite; - } - - public <R extends ReferentialDto> TypeReferentialSynchroNode getOrAddTypeNode(Class<R> referentialName) { - TypeReferentialSynchroNode node = getChild(referentialName); - if (node == null) { - node = new TypeReferentialSynchroNode(referentialName); - add(node); - } - return node; - } - - public <R extends ReferentialDto> TypeReferentialSynchroNode getChild(Class<R> referentialName) { - Enumeration children = children(); - while (children.hasMoreElements()) { - TypeReferentialSynchroNode o = (TypeReferentialSynchroNode) children.nextElement(); - if (referentialName.equals(o.getUserObject())) { - return o; - } - } - return null; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/node/TypeReferentialSynchroNode.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/node/TypeReferentialSynchroNode.java deleted file mode 100644 index 1d3ec2d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/node/TypeReferentialSynchroNode.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node; - -import fr.ird.observe.services.dto.referential.ReferentialDto; - -import javax.swing.UIManager; -import java.util.Enumeration; - -/** - * Created on 09/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - */ -public class TypeReferentialSynchroNode extends ReferentialSynchroNodeSupport { - - private static final long serialVersionUID = 1L; - - public TypeReferentialSynchroNode(Class<? extends ReferentialDto> type) { - super(UIManager.getIcon("navigation.sub.referentiel-16"), type); - } - - @Override - public RootReferentialSynchroNode getParent() { - return (RootReferentialSynchroNode) super.getParent(); - } - - public <R extends ReferentialDto> ReferenceReferentialSynchroNodeSupport getChild(String id) { - Enumeration children = children(); - while (children.hasMoreElements()) { - ReferenceReferentialSynchroNodeSupport o = (ReferenceReferentialSynchroNodeSupport) children.nextElement(); - if (id.equals(o.getUserObject().getId())) { - return o; - } - } - return null; - } - - @Override - public Class<? extends ReferentialDto> getUserObject() { - return (Class) super.getUserObject(); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/node/UpdatedReferenceReferentialSynchroNode.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/node/UpdatedReferenceReferentialSynchroNode.java deleted file mode 100644 index 5d4560e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/synchronize/referential/ng/tree/node/UpdatedReferenceReferentialSynchroNode.java +++ /dev/null @@ -1,19 +0,0 @@ -package fr.ird.observe.ui.admin.synchronize.referential.ng.tree.node; - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; - -/** - * Created on 11/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - */ -public class UpdatedReferenceReferentialSynchroNode extends ReferenceReferentialSynchroNodeSupport { - - private static final long serialVersionUID = 1L; - - public UpdatedReferenceReferentialSynchroNode(ReferentialReference<? extends ReferentialDto> referentialReference, boolean canAdd, boolean canUpdate, boolean canDelete, boolean canRevert) { - super(referentialReference, "synchroUpdate", canAdd, canUpdate, canDelete, canRevert); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateConfigUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateConfigUI.jaxx deleted file mode 100644 index 3ab8d74..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateConfigUI.jaxx +++ /dev/null @@ -1,184 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<!-- ************************************************************* --> -<!-- La configuration de l'import GPS --> -<!-- ************************************************************* --> - -<JPanel id="validateConfig"> - - <import> - fr.ird.observe.ui.admin.AdminUIModel - fr.ird.observe.validation.ValidationModelMode - - org.nuiton.validator.NuitonValidatorScope - - java.io.File - - javax.swing.JComboBox - - static fr.ird.observe.ui.UIHelper.getStringValue - </import> - - <ValidateUIHandler id='handler' - initializer='getContextValue(ValidateUIHandler.class)'/> - - <AdminUIModel id='model' initializer='getContextValue(AdminUIModel.class)'/> - - <ValidateModel id='validateModel' initializer='model.getValidateModel()'/> - - <ButtonGroup id='validateContentModel' - onStateChanged='validateModel.setModelMode((ValidationModelMode) validateContentModel.getSelectedValue())'/> - - <script><![CDATA[ -public void destroy() { - model = null; - validateModel = null; -} - -@Override -protected void finalize() throws Throwable { - super.finalize(); - destroy(); -} - -]]> - </script> - - <JPanel constraints='BorderLayout.NORTH' layout='{new BorderLayout()}'> - <Table id="validateDataConfig" constraints='BorderLayout.NORTH'> - - <!-- validation mode --> - <row> - <cell anchor="west"> - <JLabel id='validateModeLabel'/> - </cell> - <cell weightx='1' fill="horizontal"> - <Table fill='both' weightx='1'> - <row> - <cell> - <JRadioButton id="DATA"/> - </cell> - </row> - <row> - <cell> - <JRadioButton id="REFERENTIEL"/> - </cell> - </row> - <!--row> - <cell> - <JRadioButton id="ALL"/> - </cell> - </row--> - </Table> - </cell> - </row> - <row> - <cell anchor="west" columns="2"> - <JLabel id='credentialsInfo'/> - </cell> - </row> - - <!-- validation scopes --> - <row> - <cell anchor="west"> - <JLabel id='validateScopesLabel'/> - </cell> - <cell weightx='1' fill="horizontal"> - <Table id='validateScopes' fill='both' weightx='1'> - <row> - <cell> - <JCheckBox id='ERROR' - onItemStateChanged='getHandler().updateValidationScopes((JCheckBox)event.getSource())'/> - </cell> - </row> - <row> - <cell> - <JCheckBox id='WARNING' - onItemStateChanged='getHandler().updateValidationScopes((JCheckBox)event.getSource())'/> - </cell> - </row> - <row> - <cell> - <JCheckBox id='INFO' - onItemStateChanged='getHandler().updateValidationScopes((JCheckBox)event.getSource())'/> - </cell> - </row> - </Table> - </cell> - </row> - <!-- validation resume --> - <row> - <cell anchor="west" columns="2"> - <JLabel id='validateResume'/> - </cell> - </row> - <row> - <cell anchor="west" columns="2"> - <JLabel actionIcon='information' - text='observe.info.selected.validators'/> - </cell> - </row> - </Table> - - <Table id='validationReportConfig' fill='both' - constraints='BorderLayout.CENTER'> - <row> - <cell columns="2"> - <JCheckBox id='generateValidationReport' - onItemStateChanged='validateModel.setGenerateReport(((JCheckBox)event.getSource()).isSelected())'/> - </cell> - </row> - <row> - <cell> - <JLabel id="validationReportDirectoryLabel"/> - </cell> - <cell weightx='1' fill="horizontal"> - <JTextField id='validationReportDirectoryText' - onKeyReleased='getHandler().changeValidationReportDirectory(this, new File(((JTextField)event.getSource()).getText()))'/> - </cell> - <cell anchor="east"> - <JButton id="chooseValidationReportFileAction" - onActionPerformed="getHandler().chooseValidationReportFile(this)"/> - </cell> - </row> - <row> - <cell> - <JLabel id="validationReportFileLabel"/> - </cell> - <cell weightx='1' fill="horizontal" columns="2"> - <JTextField - id='validationReportFilenameText' - onKeyReleased='getHandler().changeValidationReportFilename(this, ((JTextField)event.getSource()).getText())'/> - </cell> - </row> - </Table> - - </JPanel> - <Table constraints='BorderLayout.SOUTH' weightx='1' weighty='1'> - <row> - <cell> - <JLabel/> - </cell> - </row> - </Table> - -</JPanel> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateEntityListCellRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateEntityListCellRenderer.java deleted file mode 100644 index 190fcde..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateEntityListCellRenderer.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin.validate; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.services.dto.AbstractReference; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.service.actions.validate.ValidateResultForDto; -import fr.ird.observe.services.service.actions.validate.ValidateResultForDtos; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.decorator.Decorator; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.JList; -import java.awt.Component; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.EnumMap; -import java.util.HashMap; -import java.util.Iterator; -import java.util.Map; - -import static org.nuiton.i18n.I18n.t; - -public class ValidateEntityListCellRenderer extends DefaultListCellRenderer implements PropertyChangeListener { - - private static final long serialVersionUID = 1L; - - /** Logger */ - private static final Log log = LogFactory.getLog(ValidateEntityListCellRenderer.class); - - protected final ValidateModel model; - - protected final Map<Object, String> renderCache; - - protected DecoratorService service; - - public ValidateEntityListCellRenderer(ValidateModel model) { - this.model = model; - renderCache = new HashMap<>(); - // on ecoute les modifications de messages sur le model - this.model.addPropertyChangeListener(ValidateModel.PROPERTY_MESSAGES, this); - } - - @Override - public void propertyChange(PropertyChangeEvent evt) { - - Map<?, ?> value = (Map<?, ?>) evt.getNewValue(); - if (log.isDebugEnabled()) { - log.debug("messages changed : " + - (value == null ? 0 : value.size()) + - ", rebuild render cache"); - } - synchronized (renderCache) { - renderCache.clear(); - if (model.getMessages() == null) { - return; - } - - for (Class<?> klass : model.getMessageTypes()) { - String type = t(DecoratorService.getEntityLabel(klass)); - renderCache.put(klass, type); - } - } - - } - - public DecoratorService getService() { - if (service == null) { - service = ObserveSwingApplicationContext.get().getDecoratorService(); - } - return service; - } - - @Override - public Component getListCellRendererComponent(JList list, - Object value, - int index, - boolean isSelected, - boolean cellHasFocus) { - if (value != null) { - DecoratorService decoratorService = getService(); - if (value instanceof Class<?>) { - value = renderCache.get(value); - } else { - value = valueFromRefDto(decoratorService, (AbstractReference) value); - } - } - return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus); - } - - public Object valueFromRefDto(DecoratorService decoratorService, AbstractReference value) { - String s = renderCache.get(value); - if (s != null) { - return s; - } - - if (log.isDebugEnabled()) { - log.debug("compute render cache for " + value.getId()); - } - - ValidateResultForDto validateResultForDto = model.getMessages(value); - - EnumMap<NuitonValidatorScope, Integer> scopes = - ValidateResultForDtos.getScopesCount(validateResultForDto); - - StringBuilder buffer = new StringBuilder(); - - Decorator<?> decorator; - if (value instanceof ReferentialReference) { - decorator = decoratorService.getReferentialReferenceDecorator(value.getType()); - } else { - decorator = decoratorService.getDataReferenceDecorator(value.getType()); - } - - buffer.append(decorator.toString(value)); - buffer.append(" ("); - - Iterator<NuitonValidatorScope> itr = scopes.keySet().iterator(); - while (itr.hasNext()) { - NuitonValidatorScope scope = itr.next(); - int nb = scopes.get(scope); - String t = t(scope.getLabel()); - buffer.append(t).append(" : ").append(nb); - if (itr.hasNext()) { - buffer.append(", "); - } - } - buffer.append(")"); - s = buffer.toString(); - renderCache.put(value, s); - return s; - } - -} - diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateModel.java deleted file mode 100644 index c4b9cba..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateModel.java +++ /dev/null @@ -1,261 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin.validate; - -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.services.dto.AbstractReference; -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.services.service.actions.validate.ValidateResultForDto; -import fr.ird.observe.services.service.actions.validate.ValidateResultForDtoType; -import fr.ird.observe.services.service.actions.validate.ValidatorDto; -import fr.ird.observe.services.service.actions.validate.ValidatorDtos; -import fr.ird.observe.ui.admin.AdminActionModel; -import fr.ird.observe.ui.admin.AdminStep; -import fr.ird.observe.validation.ValidationModelMode; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.validator.NuitonValidatorScope; - -import java.io.File; -import java.util.Date; -import java.util.EnumSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -/** - * Modele pour preparer une validation de donnees d'une base. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.3 - */ -public class ValidateModel extends AdminActionModel { - - public static final String PROPERTY_ALL_CONTEXT_NAMES = "allContextNames"; - - public static final String PROPERTY_CONTEXT_NAME = "contextName"; - - public static final String PROPERTY_SCOPES = "scopes"; - - public static final String PROPERTY_MODEL_MODE = "modelMode"; - - public static final String PROPERTY_GENERATE_REPORT = "generateReport"; - - public static final String PROPERTY_REPORT_FILE = "reportFile"; - - public static final String PROPERTY_MESSAGES = "messages"; - - /** Logger */ - private static final Log log = LogFactory.getLog(ValidateModel.class); - - /** les scopes a utiliser */ - protected final EnumSet<NuitonValidatorScope> scopes; - - /** le lastName du context de validation */ - protected String contextName; - - /** le type de modele a utiliser */ - protected ValidationModelMode modelMode; - - /** pour generer un rapport et le sauvegarder */ - protected boolean generateReport; - - /** le fichier où sauvegarder les résultats de la validation */ - protected File reportFile = new File(""); - - /** tout les validateur de la base */ - protected ImmutableSet<ValidatorDto> allValidators; - - /** les validateurs selectionnées */ - protected Set<ValidatorDto> validators; - - /** le dictionnaire des paths d'entites detectees */ - protected Map<Class<? extends IdDto>, ValidateResultForDtoType> messages; - - public ValidateModel() { - super(AdminStep.VALIDATE); - scopes = EnumSet.noneOf(NuitonValidatorScope.class); - messages = new TreeMap<>(); - } - - /** - * @return le lastName par defaut du fichier de sauvegarde de la base locale - * (expression calculée à partir de la date courante et du pattern - * {@link ObserveSwingApplicationConfig#REPORT_PATTERN}). - */ - public String getDefaultReportFilename() { - return String.format(ObserveSwingApplicationConfig.REPORT_PATTERN, new Date()); - } - - public String getContextName() { - return contextName; - } - - public void setContextName(String contextName) { - Object oldvalue = this.contextName; - this.contextName = contextName; - validators = null; - firePropertyChange(PROPERTY_CONTEXT_NAME, oldvalue, contextName); - } - - public ValidationModelMode getModelMode() { - return modelMode; - } - - public void setModelMode(ValidationModelMode modelMode) { - Object oldvalue = this.modelMode; - this.modelMode = modelMode; - validators = null; - firePropertyChange(PROPERTY_MODEL_MODE, oldvalue, modelMode); - } - - public EnumSet<NuitonValidatorScope> getScopes() { - return scopes; - } - - public boolean isGenerateReport() { - return generateReport; - } - - public void setGenerateReport(boolean generateReport) { - Object oldValue = this.generateReport; - this.generateReport = generateReport; - firePropertyChange(PROPERTY_GENERATE_REPORT, oldValue, generateReport); - } - - public File getReportFile() { - return reportFile; - } - - public void setReportFile(File reportFile) { - Object oldValue = this.reportFile; - this.reportFile = reportFile; - firePropertyChange(PROPERTY_REPORT_FILE, oldValue, reportFile); - } - - public void setAllValidators(ImmutableSet<ValidatorDto> allValidators) { - this.allValidators = allValidators; - } - - public Set<ValidatorDto> getValidators() { - if (validators == null) { - if (allValidators != null && getContextName() != null) { - validators = ValidatorDtos.filter( - allValidators, - getModelMode().isData(), - getModelMode().isReferential(), - getScopes(), - getContextName()); - } else { - validators = Sets.newHashSet(); - } - - } - return validators; - } - - public Map<Class<? extends IdDto>, ValidateResultForDtoType> getMessages() { - return messages; - } - - public void setMessages(Map<Class<? extends IdDto>, ValidateResultForDtoType> messages) { - Object oldValue = this.messages; - this.messages = messages; - firePropertyChange(PROPERTY_MESSAGES, oldValue, messages); - } - - public Set<Class<? extends IdDto>> getMessageTypes() { - Set<Class<? extends IdDto>> result; - - if (messages != null && !messages.isEmpty()) { - result = messages.keySet(); - } else { - result = Sets.newHashSet(); - } - - return result; - } - - public List<AbstractReference> getMessagesDto(Class dtoType) { - - List<AbstractReference> result = Lists.newArrayList(); - - if (messages != null) { - - ValidateResultForDtoType resultForDtoType = messages.get(dtoType); - - ImmutableSet<ValidateResultForDto> validateResultForDto = resultForDtoType.getValidateResultForDto(); - - for (ValidateResultForDto resultForDto : validateResultForDto) { - - result.add(resultForDto.getDto()); - } - } - return result; - } - - public ValidateResultForDto getMessages(AbstractReference referenceDto) { - - ValidateResultForDto result = null; - - if (messages != null) { - - ValidateResultForDtoType resultForDtoType = messages.get(referenceDto.getType()); - - result = resultForDtoType.getValidateResult(referenceDto); - - } - - return result; - } - - public void addScope(NuitonValidatorScope scope) { - scopes.add(scope); - validators = null; - firePropertyChange(PROPERTY_SCOPES, null, scopes); - } - - public void removeScope(NuitonValidatorScope scope) { - scopes.remove(scope); - validators = null; - firePropertyChange(PROPERTY_SCOPES, null, scopes); - } - - @Override - public void destroy() { - super.destroy(); - if (messages != null) { - setMessages(null); - } - if (validators != null) { - validators = null; - } - } - - public ImmutableSet<ValidatorDto> getAllValidators() { - return allValidators; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateUI.jaxx deleted file mode 100644 index a41f85c..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateUI.jaxx +++ /dev/null @@ -1,127 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<!-- ********************************************** --> -<!-- L'écran de validation des données observers --> -<!-- ********************************************** --> - -<fr.ird.observe.ui.admin.AdminTabUI> - - <import> - fr.ird.observe.ui.UIHelper - fr.ird.observe.ui.admin.AdminStep - fr.ird.observe.ui.admin.AdminTabUI - fr.ird.observe.ui.admin.AdminUI - fr.ird.observe.ui.admin.validate.ValidationMessageTableModel - - - jaxx.runtime.swing.wizard.ext.WizardState - jaxx.runtime.validator.swing.SimpleBeanValidatorMessageTableModel - - org.jdesktop.swingx.JXTitledPanel - - javax.swing.ListSelectionModel - - </import> - - <ValidateUIHandler id='handler' constructorParams='this'/> - - <ValidateModel id='stepModel' initializer='getModel().getValidateModel()'/> - - <DefaultListModel id='typeModel'/> - - <DefaultListModel id='refModel'/> - - <ValidationMessageTableModel id='messagesModel'/> - - <DefaultListSelectionModel id='typeSelectionModel' - onValueChanged='if (!event.getValueIsAdjusting() && !typeSelectionModel.isSelectionEmpty()) { getHandler().updateSelectedType(); }'/> - - <DefaultListSelectionModel id='refSelectionModel' - onValueChanged='if (!event.getValueIsAdjusting() && !refSelectionModel.isSelectionEmpty()) { getHandler().updateSelectedRef(); }'/> - - <script><![CDATA[ -public ValidateUI(AdminUI parentContext) { - super(AdminStep.VALIDATE, parentContext); -} - -@Override -public void initUI(AdminUI ui) { - getHandler().initTabUI(ui, this); -} - -@Override -public void updateState(WizardState newState) { - getHandler().updateState(this, newState); -} -]]> - </script> - - <JPanel id='PENDING_content'> - <Table constraints='BorderLayout.CENTER' fill='both' weightx='1' - weighty='1'> - <row> - <cell> - <JButton id='startButton' - onActionPerformed="getHandler().startAction()"/> - </cell> - </row> - </Table> - </JPanel> - - <JPanel id='NEED_FIX_content'> - - <JSplitPane id='splitpane' constraints='BorderLayout.CENTER'> - - <!-- up : entities view --> - <JXTitledPanel id='navigationView'> - <JSplitPane id='splitpane2'> - <JScrollPane> - <JList id='typeList'/> - </JScrollPane> - <JScrollPane> - <JList id='refList'/> - </JScrollPane> - </JSplitPane> - </JXTitledPanel> - - <!-- down : message view --> - <JXTitledPanel id='messageView'> - <JScrollPane> - <JTable id='messageTable'/> - </JScrollPane> - </JXTitledPanel> - - </JSplitPane> - - <JPanel constraints='BorderLayout.SOUTH' layout='{new BorderLayout()}'> - - <JLabel id='resumeLabel' constraints='BorderLayout.CENTER'/> - - <JPanel constraints='BorderLayout.SOUTH' layout='{new BorderLayout()}'> - <JButton id='saveReport' constraints='BorderLayout.CENTER' - onActionPerformed='getHandler().saveReport()'/> - </JPanel> - - </JPanel> - </JPanel> -</fr.ird.observe.ui.admin.AdminTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateUIHandler.java deleted file mode 100644 index c0ae499..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidateUIHandler.java +++ /dev/null @@ -1,603 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.admin.validate; - -import com.google.common.base.Charsets; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Iterables; -import com.google.common.collect.Maps; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.AbstractReference; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.services.service.actions.validate.ValidateDataRequest; -import fr.ird.observe.services.service.actions.validate.ValidateDataResult; -import fr.ird.observe.services.service.actions.validate.ValidateReferentialsRequest; -import fr.ird.observe.services.service.actions.validate.ValidateReferentialsResult; -import fr.ird.observe.services.service.actions.validate.ValidateResultForDto; -import fr.ird.observe.services.service.actions.validate.ValidateResultForDtoType; -import fr.ird.observe.services.service.actions.validate.ValidateResultForDtos; -import fr.ird.observe.services.service.actions.validate.ValidateService; -import fr.ird.observe.services.service.actions.validate.ValidationMessage; -import fr.ird.observe.services.service.actions.validate.ValidatorDto; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.admin.AdminStep; -import fr.ird.observe.ui.admin.AdminTabUI; -import fr.ird.observe.ui.admin.AdminTabUIHandler; -import fr.ird.observe.ui.admin.AdminUI; -import fr.ird.observe.ui.admin.AdminUIModel; -import fr.ird.observe.ui.admin.config.ConfigUI; -import fr.ird.observe.ui.admin.config.SelectDataUI; -import fr.ird.observe.ui.storage.tabs.DataSelectionModel; -import fr.ird.observe.ui.util.ObserveValidationMessageTableRenderer; -import fr.ird.observe.validation.ValidationModelMode; -import jaxx.runtime.SwingUtil; -import jaxx.runtime.context.JAXXInitialContext; -import jaxx.runtime.swing.wizard.ext.WizardState; -import org.apache.commons.io.FileUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.decorator.Decorator; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.ComboBoxModel; -import javax.swing.DefaultComboBoxModel; -import javax.swing.DefaultListModel; -import javax.swing.JCheckBox; -import javax.swing.JTable; -import javax.swing.RowSorter; -import javax.swing.SortOrder; -import java.io.File; -import java.io.IOException; -import java.util.Collections; -import java.util.Date; -import java.util.EnumSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.stream.Collectors; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -//import jaxx.runtime.validator.swing.SwingValidator; - -/** - * Le controleur des onglets. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ValidateUIHandler extends AdminTabUIHandler { - - public static final String[] EMPTY_STRING_ARRAY = new String[]{}; - - public static final String LINE = - "--------------------------------------------------------------------------------"; - - /** Logger */ - private static final Log log = LogFactory.getLog(ValidateUIHandler.class); - - protected ObserveSwingDataSource source; - - protected Decorator<TripSeineDto> dTrip; - - protected Decorator<ProgramDto> dProgram; - - public ValidateUIHandler(AdminTabUI ui) { - super(ui); - } - - public void initTabUI(AdminUI ui, ValidateUI tabUI) { - - super.initTabUI(ui, tabUI); - - if (log.isDebugEnabled()) { - log.debug(" specialized for [" + tabUI.getStep() + "] for main ui " + ui.getClass().getName() + "@" + System.identityHashCode(ui)); - } - - JTable messageTable = tabUI.getMessageTable(); - - messageTable.setDefaultRenderer(Object.class, new ObserveValidationMessageTableRenderer()); - messageTable.getRowSorter().setSortKeys( - Collections.singletonList(new RowSorter.SortKey(0, SortOrder.ASCENDING))); - SwingUtil.setI18nTableHeaderRenderer( - messageTable, - n("validator.scope.header"), - n("validator.scope.header.tip"), - n("validator.field.header"), - n("validator.field.header.tip"), - n("validator.message.header"), - n("validator.message.header.tip")); - SwingUtil.fixTableColumnWidth(messageTable, 0, 25); - - ValidateEntityListCellRenderer listRenderer = - new ValidateEntityListCellRenderer(tabUI.getStepModel()); - tabUI.getTypeList().setCellRenderer(listRenderer); - tabUI.getRefList().setCellRenderer(listRenderer); - - tabUI.getStartButton().setText(t("observe.actions.synchro.launch.operation", t(tabUI.getStep().getOperationLabel()))); - - // initialisation de l'ui de configuration - if (log.isInfoEnabled()) { - log.info("Init extra configuration for " + tabUI.getName()); - } - - ConfigUI configUI = (ConfigUI) ui.getStepUI(AdminStep.CONFIG); - JAXXInitialContext tx = new JAXXInitialContext().add(configUI).add(this); - ValidateConfigUI extraConfig = new ValidateConfigUI(tx); - configUI.getExtraConfig().add(extraConfig); - - final SelectDataUI selectTabUI = (SelectDataUI) ui.getStepUI(AdminStep.SELECT_DATA); - - getModel().getValidateModel().addPropertyChangeListener(ValidateModel.PROPERTY_MODEL_MODE, evt -> { - ValidationModelMode value = (ValidationModelMode) evt.getNewValue(); - if (value == null) { - // rien a faire pour le moment... - return; - } - DataSelectionModel selectDataModel; - selectDataModel = selectTabUI.getSelectDataModel(); - if (log.isDebugEnabled()) { - log.debug("validation model changed to " + value); - } - switch (value) { - case REFERENTIEL: - - selectDataModel.setUseData(false); - selectDataModel.setUseReferentiel(true); - break; - case DATA: - selectDataModel.setUseData(true); - selectDataModel.setUseReferentiel(false); - break; - case ALL: - selectDataModel.setUseData(true); - selectDataModel.setUseReferentiel(true); - break; - } - //updateModel(); - }); - - selectTabUI.getModel().addPropertyChangeListener(AdminUIModel.SELECTION_MODEL_CHANGED_PROPERTY_NAME, evt -> { - AdminUIModel model1 = (AdminUIModel) evt.getSource(); - if (!model1.containsStep(selectTabUI.getStep())) { - // avoid multi-cast - return; - } - DataSelectionModel value = (DataSelectionModel) evt.getNewValue(); - if (log.isInfoEnabled()) { - log.info("selection model changed to " + value); - } - updateSelectionModel(selectTabUI); - }); - - ImmutableSet<ValidatorDto> validators = ObserveSwingApplicationContext.get().getValidators(); - - ValidateModel stepModel = model.getValidateModel(); - - stepModel.setAllValidators(validators); - } - - public void updateState(ValidateUI tabUI, WizardState newState) { - - super.updateState(tabUI, newState); - - if (newState == WizardState.NEED_FIX) { - updateTypes(); - tabUI.resumeLabel.setText(t("observe.actions.validate.save.reportFile", tabUI.getStepModel().getReportFile())); - String actionText; - if (tabUI.getStepModel().isGenerateReport()) { - actionText = t("observe.actions.validate.save"); - } else { - actionText = t("observe.actions.validate.continue.with.no.save.report"); - } - tabUI.saveReport.setText(actionText); - return; - } - if (newState == WizardState.RUNNING) { - tabUI.typeList.clearSelection(); - tabUI.refList.clearSelection(); - tabUI.messageTable.clearSelection(); - tabUI.typeModel.clear(); - tabUI.refModel.clear(); - tabUI.messagesModel.clear(); - } - if (newState == WizardState.SUCCESSED) { - } - } - - public void updateTypes() { - - ValidateUI tabUI = (ValidateUI) ui; - - DefaultListModel typeModel = tabUI.typeModel; - tabUI.typeSelectionModel.clearSelection(); - typeModel.clear(); - - Set<Class<? extends IdDto>> messageTypes = tabUI.getStepModel().getMessageTypes(); - - List<Class<? extends IdDto>> classes = getDecoratorService().sortTypes(messageTypes); - - for (Class<? extends IdDto> e : classes) { - - typeModel.addElement(e); - - } - - tabUI.typeList.setSelectedIndex(0); - } - - public void updateSelectedType() { - - - ValidateUI tabUI = (ValidateUI) ui; - - getModel().setBusy(true); - // on nettoye le modele des refs - try { - tabUI.refSelectionModel.clearSelection(); - tabUI.refModel.clear(); - - Object o = tabUI.typeList.getSelectedValue(); - if (log.isInfoEnabled()) { - log.info("new selected type = " + o); - } - if (o == null) { - return; - } - - Class<?> type = (Class<?>) o; - - List<AbstractReference> refs = tabUI.getStepModel().getMessagesDto(type); - for (AbstractReference ref : Iterables.limit(refs, 100)) { - if (log.isDebugEnabled()) { - log.debug("add ref = " + ref); - } - tabUI.refModel.addElement(ref); - } - tabUI.refList.setSelectedIndex(0); - } finally { - getModel().setBusy(false); - } - - } - - public void updateSelectedRef() { - - - ValidateUI tabUI = (ValidateUI) ui; - - // on nettoye le modele des messages - tabUI.messageTable.clearSelection(); - tabUI.messagesModel.clear(); - - Object o = tabUI.refList.getSelectedValue(); - - if (log.isDebugEnabled()) { - log.debug("new selected ref = " + o); - } - - if (o == null) { - return; - } - - AbstractReference ref = (AbstractReference) o; - - if (log.isDebugEnabled()) { - log.debug(ref); - } - - ValidateResultForDto resultForDto = tabUI.getStepModel().getMessages(ref); - - ImmutableSet<ValidationMessage> messages = resultForDto.getMessages(); - - tabUI.messagesModel.setMessages(messages); - - - } - - public void startAction() { - - addAdminWorker(((ValidateUI) ui).getStartButton().getToolTipText(), this::doAction); - } - - public WizardState doAction() throws Exception { - if (log.isDebugEnabled()) { - log.debug(this); - } - - WizardState init = initDB(); - - if (init != null) { - // une erreur ou une annulation - return init; - } - - launchValidation(); - - Map<Class<? extends IdDto>, ValidateResultForDtoType> messages = model.getValidateModel().getMessages(); - if (messages == null || messages.isEmpty()) { - - // pas de validation ou bien pas d'erreurs rencontrées - - sendMessage(t("observe.actions.validation.message.nothing.to.do")); - sendMessage(t("observe.actions.validation.message.operation.done", new Date())); - - return WizardState.SUCCESSED; - } - - sendMessage( - t("observe.actions.validation.message.operation.needFix", new Date())); - - return WizardState.NEED_FIX; - } - - protected WizardState initDB() throws Exception { - - - // on recupere la source de données - source = model.getSafeLocalSource(false); - - DecoratorService decoratorService = getDecoratorService(); - - dTrip = decoratorService.getDecoratorByType(TripSeineDto.class); - - dProgram = decoratorService.getDecoratorByType(ProgramDto.class); - - openSource(source); - - // recuperation des validateurs du modele - - ValidateModel validationModel = model.getValidateModel(); - Set<ValidatorDto> validators = validationModel.getValidators(); - - sendMessage(t("observe.actions.validation.message.use.storage", - source.getLabel())); - - sendMessage(t("observe.actions.validation.message.prepare.validators")); - - if (!validators.isEmpty()) { - - // des validateurs ont été trouvés - - for (ValidatorDto v : validators) { - String label = t(DecoratorService.getEntityLabel(v.getDtoType())); - sendMessage(t("observe.actions.validation.message.detected", label)); - } - } else { - sendMessage(t("observe.message.no.validation.detected")); - } - - return null; - } - - public void launchValidation() throws Exception { - - // on vide les anciens messages - ValidateModel stepModel = model.getValidateModel(); - stepModel.setMessages(null); - - DataSelectionModel dataModel = model.getSelectionDataModel(); - - ObserveSwingDataSource dataSourceToValidate = model.getLocalSource(); - - if (!dataSourceToValidate.isOpen()) { - dataSourceToValidate.open(); - } - - ValidateService validateService = dataSourceToValidate.newValidateService(); - - Map<Class<? extends IdDto>, ValidateResultForDtoType> messages = Maps.newHashMap(); - - if (dataModel.isUseReferentiel()) { - - // validation des referentiels selectionnes - ValidateReferentialsRequest request = new ValidateReferentialsRequest(); - - request.setReferentialTypes(ImmutableSet.copyOf(dataModel.getSelectedReferentiel())); - request.setScopes(ImmutableSet.copyOf(stepModel.getScopes())); - request.setValidationContext(stepModel.getContextName()); - - ValidateReferentialsResult result = validateService.validateReferentials(request); - - messages.putAll(result.getResultByType()); - } - - if (dataModel.isUseData()) { - - // validation des donnees observateur selectionnee - ValidateDataRequest request = new ValidateDataRequest(); - - request.setDataIds(ImmutableSet.copyOf(dataModel.getSelectedData().stream() - .map(DataReference.ID_FUNCTION) - .collect(Collectors.toSet()))); - request.setScopes(ImmutableSet.copyOf(stepModel.getScopes())); - request.setValidationContext(stepModel.getContextName()); - - ValidateDataResult result = validateService.validateData(request); - - messages.putAll(result.getResultByType()); - } - - dataSourceToValidate.close(); - - stepModel.setMessages(messages); - - } - - public void saveReport() { - WizardState finalState = null; - ValidateModel validationModel = model.getValidateModel(); - try { - if (validationModel.isGenerateReport()) { - - sendMessage( - t("observe.actions.validation.message.save.report", validationModel.getReportFile())); - - generateReportFile(validationModel); - } else { - sendMessage( - t("observe.actions.validation.message.not.save.report")); - } - finalState = WizardState.SUCCESSED; - } catch (Exception e) { - validationModel.setError(e); - finalState = WizardState.FAILED; - } finally { - model.setStepState(AdminStep.VALIDATE, finalState); - } - } - - //FIXME A remplacer par une template - public void generateReportFile(ValidateModel validationModel) throws IOException { - File reportFile = validationModel.getReportFile(); - if (log.isInfoEnabled()) { - log.info("save report in " + reportFile); - } - - DecoratorService service = getDecoratorService(); - StringBuilder builder = new StringBuilder(); - builder.append(LINE).append('\n'); - - builder.append(t("observe.actions.validate.report.title", new Date())).append('\n'); - builder.append(t("observe.actions.validate.report.scopes", validationModel.getScopes())).append('\n'); - builder.append(t("observe.actions.validate.report.contextName", validationModel.getContextName())).append('\n'); - - Map<Class<? extends IdDto>, ValidateResultForDtoType> messages = validationModel.getMessages(); - - builder.append(t("observe.actions.validate.report.entities.with.messages", messages.size())).append('\n'); - builder.append(LINE).append('\n').append('\n'); - - for (ValidateResultForDtoType validateResultForDtoType : messages.values()) { - - ImmutableSet<ValidateResultForDto> validateResultForDtos = validateResultForDtoType.getValidateResultForDto(); - for (ValidateResultForDto validateResultForDto : validateResultForDtos) { - - AbstractReference referenceDto = validateResultForDto.getDto(); - - String refStr = service.decorate(referenceDto); - - Set<ValidationMessage> refMessages = validateResultForDto.getMessages(); - - EnumSet<NuitonValidatorScope> scopes = ValidateResultForDtos.getScopes(validateResultForDto); - - builder.append(t("observe.actions.validate.report.entity", referenceDto.getId(), refStr, refMessages.size(), scopes)).append('\n'); - for (NuitonValidatorScope scope : scopes) { - - List<ValidationMessage> messagesByScope = ValidateResultForDtos.scopeMessageFilter(scope, validateResultForDto); - - for (ValidationMessage message : messagesByScope) { - - builder.append(message).append('\n'); - - } - - builder.append('\n'); - } - - } - builder.append(LINE).append('\n').append('\n'); - } - - String content = builder.toString(); - if (log.isInfoEnabled()) { - log.info(content); - } - FileUtils.write(reportFile, content, Charsets.UTF_8.name()); - } - - - // ------------------------------------------------------------------------ - // -- ValidateConfgUI methods - // ------------------------------------------------------------------------ - - public void updateValidationScopes(JCheckBox checkBox) { - NuitonValidatorScope scope = getValidatorScope(checkBox); - ValidateModel validateModel = getModel().getValidateModel(); - if (checkBox.isSelected()) { - // ajout du scope - validateModel.addScope(scope); - } else { - // supprime le scope - validateModel.removeScope(scope); - } - } - - public ComboBoxModel updateComboModel(Object... datas) { - if (datas == null) { - return new DefaultComboBoxModel(); - } - return new DefaultComboBoxModel(datas); - } - - public String updateValidatorResumeLabel(boolean valid) { - - ValidateModel validateModel = getModel().getValidateModel(); - - if (validateModel == null) { - return null; - } - return t("observe.actions.validate.selected.validators", validateModel.getValidators().size()); - } - - public AdminStep getObjectOperation(JCheckBox checkBox) { - return AdminStep.valueOf(checkBox.getName()); - } - - public NuitonValidatorScope getValidatorScope(JCheckBox checkBox) { - return (NuitonValidatorScope) checkBox.getClientProperty("value"); - } - - public boolean isScopeSelected(Set<NuitonValidatorScope> scopes, JCheckBox checkBox) { - NuitonValidatorScope scope = getValidatorScope(checkBox); - return scopes.contains(scope); - } - - public boolean isObjectOperationSelected(Set<AdminStep> objectOperations, JCheckBox checkBox) { -// AdminStep scope = getObjectOperation(checkBox); - return objectOperations.contains(getObjectOperation(checkBox)); - } - - public void chooseValidationReportFile(ValidateConfigUI configUI) { - File f = UIHelper.chooseDirectory( - configUI, - t("observe.actions.validate.title.choose.report.directory"), - t("observe.actions.validate.choose.report.directory"), - new File(configUI.validationReportDirectoryText.getText()) - ); - changeValidationReportDirectory(configUI, f); - } - - public void changeValidationReportDirectory(ValidateConfigUI configUI, File f) { - getModel().getValidateModel().setReportFile(new File(f, configUI.validationReportFilenameText.getText())); - } - - public void changeValidationReportFilename(ValidateConfigUI configUI, String filename) { - getModel().getValidateModel().setReportFile(new File(configUI.validationReportDirectoryText.getText(), filename)); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidationMessageTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidationMessageTableModel.java deleted file mode 100644 index 2ebbe31..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/admin/validate/ValidationMessageTableModel.java +++ /dev/null @@ -1,115 +0,0 @@ -package fr.ird.observe.ui.admin.validate; - -/*- - * #%L - * ObServe :: Application Swing - * %% - * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import fr.ird.observe.services.service.actions.validate.ValidationMessage; -import jaxx.runtime.SwingUtil; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.table.AbstractTableModel; -import java.util.Collection; -import java.util.List; - -/** - * @author Sylvain Bavencoff - bavencoff@codelutin.com - */ -public class ValidationMessageTableModel extends AbstractTableModel { - - private static final long serialVersionUID = 1L; - - public static final String[] columnNames = - {"validator.scope", "validator.field", "validator.message"}; - - public static final Class<?>[] columnClasses = - {NuitonValidatorScope.class, String.class, String.class}; - - protected final List<ValidationMessage> messages = Lists.newArrayList(); - - @Override - public int getRowCount() { - return messages.size(); - } - - @Override - public int getColumnCount() { - return columnNames.length; - } - - @Override - public boolean isCellEditable(int row, int column) { - // cells are never editable in this model - return false; - } - - @Override - public Class<?> getColumnClass(int columnIndex) { - SwingUtil.ensureColumnIndex(this, columnIndex); - return columnClasses[columnIndex]; - } - - @Override - public String getColumnName(int column) { - SwingUtil.ensureColumnIndex(this, column); - return columnNames[column]; - } - - @Override - public Object getValueAt(int rowIndex, int columnIndex) { - - ValidationMessage message = messages.get(rowIndex); - - Object value; - - switch (columnIndex) { - case 0: - value = message.getScope(); - break; - case 1: - value = message.getFieldName(); - break; - case 2: - value = message.getMessage(); - break; - default: - value = null; - } - - return value; - } - - public void setMessages(Collection<ValidationMessage> messages) { - this.messages.clear(); - this.messages.addAll(messages); - fireTableDataChanged(); - } - - public void clear() { - messages.clear(); - fireTableDataChanged(); - } - - public ValidationMessage getRow(int row) { - return messages.get(row); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ContentMode.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ContentMode.java deleted file mode 100644 index 32adcf0..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ContentMode.java +++ /dev/null @@ -1,38 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content; - -/** - * Pour caractériser le mode d'un écran. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public enum ContentMode { - - /** pour un écran de création d'une nouvelle donnée */ - CREATE, - /** pour un écran de modification d'une donée */ - UPDATE, - /** pour un écran en lecture seul */ - READ -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ContentUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ContentUI.jaxx deleted file mode 100644 index 61ace5d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ContentUI.jaxx +++ /dev/null @@ -1,160 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<org.jdesktop.swingx.JXTitledPanel - abstract='true' genericType='E extends IdDto' implements="fr.ird.observe.ui.content.ObserveContentUI<E>" - title='{getHandler().updateTitle(getContentTitle())}' - contentContainer='{contentContainer}' - leftDecoration='{titleLeft}' - rightDecoration='{titleRightToolBar}' - _READIcon='SwingUtil.getUIManagerActionIcon("mode-read")' - _CREATEIcon='SwingUtil.getUIManagerActionIcon("mode-create")' - _UPDATEIcon='SwingUtil.getUIManagerActionIcon("mode-update")' - _READTip='t("observe.content.mode.read.tip")' - _CREATERip='t("observe.content.mode.create.tip")' - _UPDATETip='t("observe.content.mode.update.tip")'> - - <import> - fr.ird.observe.ObserveSwingApplicationContext - fr.ird.observe.db.DataContext - fr.ird.observe.db.ObserveSwingDataSource - fr.ird.observe.configuration.ObserveSwingApplicationConfig - fr.ird.observe.ui.actions.shared.GoUpUIAction - fr.ird.observe.ui.actions.shared.GoDownUIAction - fr.ird.observe.ui.tree.ObserveTreeHelper - - fr.ird.observe.services.dto.IdDto - - org.jdesktop.jxlayer.JXLayer - - jaxx.runtime.swing.BlockingLayerUI - jaxx.runtime.validator.swing.SwingValidatorMessageTableModel - - javax.swing.JComboBox - javax.swing.JList - javax.swing.UIManager - </import> - - <ObserveSwingApplicationConfig id='config' initializer='ObserveSwingApplicationContext.get().getConfig()'/> - - <SwingValidatorMessageTableModel id='errorTableModel' initializer='getContextValue(SwingValidatorMessageTableModel.class)'/> - - <!--FIXME a supprimer a la fin de la migration de service --> - <ObserveSwingDataSource id='dataSource' initializer='ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource()'/> - - <DataContext id='dataContext' javaBean='ObserveSwingApplicationContext.get().getDataContext()'/> - - <ObserveTreeHelper id='treeHelper' initializer='getContextValue(ObserveTreeHelper.class)'/> - - <ContentUIModel id='model' genericType='E' initializer='ContentUIModel.newModel(this)'/> - - <ContentUIHandler id='handler' genericType='E' initializer='ContentUIHandler.newHandler(this)'/> - - <IdDto id='bean' initializer='model.getBean()'/> - - <!-- icon of the content --> - <Icon id='contentIcon' javaBean='null'/> - - <String id='contentTitle' javaBean='null'/> - - <BlockingLayerUI id='blockLayerUI'/> - - <script><![CDATA[ -public Object getSelectedBean(JComboBox combo) { - return combo.getSelectedItem(); -} - -public Object getSelectedBean(JList list) { - return list.getSelectedValue(); -} - -public void init() { - getHandler().initUI(); -} - -public void open() { - getHandler().openUI(); -} - -public boolean close() { - return getHandler().closeUI(); -} - -public void startEdit(E o) { - getHandler().startEditUI(); -} - -public void restartEdit() { - getHandler().restartEditUI(); -} - -public void stopEdit() { - getHandler().stopEditUI(); -} - -public void resetEdit() { - getHandler().resetEditUI(); -} - -public void save(boolean refresh) { - getHandler().saveUI(refresh); -} - -public void delete() { - getHandler().deleteUI(); -} - -]]> - </script> - - <JLabel id='titleLeft'/> - - <JToolBar id='titleRightToolBar'> - - <JXLayer id="actionUpPane"> - <JButton id='actionUp'/> - </JXLayer> - - <JXLayer id="actionDownPane"> - <JButton id='actionDown'/> - </JXLayer> - - <JLabel id='titleRight'/> - </JToolBar> - - <JPanel id='contentContainer'> - - <JXLayer UI='{blockLayerUI}' constraints='BorderLayout.CENTER'> - - <JPanel id='body'/> - - </JXLayer> - - <Table id='actions' constraints='BorderLayout.SOUTH'/> - - </JPanel> - - <JPanel id="invisible" visible='false'> - - </JPanel> - -</org.jdesktop.swingx.JXTitledPanel> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ContentUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ContentUIHandler.java deleted file mode 100644 index 2142473..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ContentUIHandler.java +++ /dev/null @@ -1,1122 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content; - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; -import fr.ird.observe.ObserveOpenDataManager; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.ObserveSwingTechnicalException; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.application.swing.decoration.decorators.DataReferenceDecorator; -import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.AbstractObserveDto; -import fr.ird.observe.services.dto.DataDto; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.services.dto.reference.request.ReferenceSetRequestDefinition; -import fr.ird.observe.services.dto.reference.request.ReferenceSetRequestDefinitions; -import fr.ird.observe.services.dto.reference.request.ReferenceSetRequestKeyDefinition; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.ReferentialReferenceSet; -import fr.ird.observe.services.dto.referential.ReferentialReferences; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.actions.shared.AbstractUIAction; -import fr.ird.observe.ui.content.ref.ContentReferenceUIHandler; -import fr.ird.observe.ui.tree.AbstractObserveTreeCellRenderer; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.validation.ValidationContext; -import jaxx.runtime.JAXXContext; -import jaxx.runtime.swing.JAXXButtonGroup; -import jaxx.runtime.swing.editor.bean.BeanComboBox; -import jaxx.runtime.swing.editor.bean.BeanListHeader; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; -import jaxx.runtime.validator.swing.SwingValidatorUtil; -import org.apache.commons.lang3.BooleanUtils; -import org.apache.commons.lang3.reflect.ConstructorUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.decorator.Decorator; -import org.nuiton.decorator.DecoratorUtil; -import org.nuiton.decorator.JXPathDecorator; -import org.nuiton.jaxx.widgets.gis.absolute.CoordinatesEditor; -import org.nuiton.jaxx.widgets.select.FilterableDoubleList; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.AbstractButton; -import javax.swing.ActionMap; -import javax.swing.Icon; -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.JToolBar; -import javax.swing.UIManager; -import java.awt.Component; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -import static org.nuiton.i18n.I18n.t; - -/** - * Le controleur d'un écran d'édition. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public abstract class ContentUIHandler<E extends IdDto> { - - /** Logger */ - static private final Log log = LogFactory.getLog(ContentUIHandler.class); - - protected final String prefix; - - private final DataContextType parentType; - - private final DataContextType type; - - private final Icon errorIcon; - - /** l'interface graphique que le controleur utilise */ - protected final ObserveContentUI<E> ui; - - public static <E extends IdDto> ContentUIHandler<E> newHandler(ObserveContentUI<E> ui) { - - String uiName = ui.getClass().getName(); - String modelName = uiName + "Handler"; - - try { - - Class<ContentUIHandler<E>> handlerClass = (Class<ContentUIHandler<E>>) Class.forName(modelName); - ContentUIHandler<E> handler = ConstructorUtils.invokeConstructor(handlerClass, ui); - return handler; - - } catch (Exception e) { - throw new ObserveSwingTechnicalException("Could not create handler for ui: " + ui, e); - } - - } - - public static ObserveTreeHelper getTreeHelper(JAXXContext context) { - return context.getContextValue(ObserveTreeHelper.class); - } - - /** - * @param ui the current ui to close - * @return {@code true} if ui can be safelty closed, {@code false} - * otherwise. - */ - public static boolean checkEdit(ObserveContentUI<?> ui) { - - ContentUIModel<? extends AbstractObserveDto> model = ui.getModel(); - - if (model.isCreatingMode()) { - - // on peut quitter le mode creation si le modele est non modifie et valide - if (!(model.isEnabled() && model.isEditing() && (model.isModified() || !model.isValid()))) { - if (model.isEditing()) { - ui.stopEdit(); - } - // ui was not in edit mode, nor modified in edit mode, so can - // safely quit - return true; - } - } else { - - // on peut quiiter le mode mise a jour si le modele est non modifie - if (!(model.isEnabled() && model.isEditing() && model.isModified())) { - if (model.isEditing()) { - ui.stopEdit(); - } - // ui was not in edit mode, nor modified in edit mode, so can - // safely quit - return true; - } - } - - if (log.isDebugEnabled()) { - log.debug("previousUI is in edit mode"); - } - - boolean wasClosed = true; - - if (! ui.getDataSource().isExpired()) { - if (model.isValid()) { - // ask user if wants to save - int reponse = UIHelper.askUser( - (JComponent) ui, - t("observe.title.need.confirm"), - t("observe.message.quit.valid.edit"), - JOptionPane.WARNING_MESSAGE, - new Object[]{ - t("observe.choice.save"), - t("observe.choice.doNotSave"), - t("observe.choice.cancel")}, - 0); - if (log.isDebugEnabled()) { - log.debug("response : " + reponse); - } - - switch (reponse) { - case JOptionPane.CLOSED_OPTION: - case 2: - wasClosed = false; - break; - case 0: - // will save ui - ui.save(false); - break; - case 1: - // wil reset ui - ui.resetEdit(); - break; - } - - } else { - // ask user if wants to quit without saving since edit is not valid - int reponse = UIHelper.askUser( - (JComponent) ui, - t("observe.title.need.confirm"), - t("observe.message.quit.invalid.edit"), - JOptionPane.ERROR_MESSAGE, - new Object[]{ - t("observe.choice.continue"), - t("observe.choice.cancel")}, - 0); - if (log.isDebugEnabled()) { - log.debug("response : " + reponse); - } - switch (reponse) { - case JOptionPane.CLOSED_OPTION: - case 1: - wasClosed = false; - break; - case 0: - // wil reset ui - ui.resetEdit(); - break; - } - } - } - if (wasClosed) { - ui.stopEdit(); - } - return wasClosed; - } - - public static void addMessage(ObserveContentUI<?> ui, NuitonValidatorScope scope, String fieldName, String message) { - SwingValidatorMessageTableModel model = ui.getErrorTableModel(); - model.addMessages((JComponent) ui, fieldName, scope, message); - } - - public static void removeAllMessages(ContentUI<?> ui, NuitonValidatorScope scope, String fieldName) { - SwingValidatorMessageTableModel model = ui.getErrorTableModel(); - model.removeMessages(ui, fieldName, scope); - } - - public static void removeAllMessages(ObserveContentUI<?> ui) { - SwingValidatorMessageTableModel model = ui.getErrorTableModel(); - model.removeMessages((JComponent) ui, null); - } - - public ContentUIHandler(ObserveContentUI<E> ui, DataContextType parentType, DataContextType type) { - this.ui = ui; - this.parentType = parentType; - this.type = type; - prefix = "[" + ui.getClass().getSimpleName() + "] "; - if (log.isDebugEnabled()) { - log.debug("New handler [" + this + "] for ui " + prefix); - } - errorIcon = UIManager.getIcon("action.error"); - } - - public ObserveContentUI<E> getUi() { - return ui; - } - - public ContentUIModel<E> getModel() { - return getUi().getModel(); - } - - public Class<E> getBeanType() { - Class<E> mainEntityClass = getModel().getBeanType(); - return mainEntityClass; - } - - public E getBean() { - ContentUIModel<E> model = getModel(); - E bean = model.getBean(); - return bean; - } - - public DecoratorService getDecoratorService() { - DecoratorService result = ObserveSwingApplicationContext.get().getDecoratorService(); - return result; - } - - public void initUI() { - - final ContentUIInitializer<E, ObserveContentUI<E>> uiInitializer = new ContentUIInitializer<>(ui); - uiInitializer.initUI(); - - getModel().addPropertyChangeListener(ContentUIModel.PROPERTY_FORM, evt -> updateUiWithReferenceSetsFromModel()); - - } - - public void openUI() { - - boolean canWrite = computeCanWrite(getDataSource()); - - getModel().setCanWrite(canWrite); - - //FIXME chemit 20100913 : il vaudrait le faire uniquement lors de l'édition - // chaque arrive sur un ecran invalide le cache de validation - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ValidationContext context = applicationContext.getValidationContext(); - context.cleanCache(); - - if (log.isDebugEnabled()) { - log.debug("ui " + ui.getClass()); - } - // suppression des messages de validation - removeAllMessages(ui); - ObserveTreeHelper treeHelper = getTreeHelper(ui); - AbstractObserveTreeCellRenderer render = - treeHelper.getTreeCellRenderer(); - ObserveNode node = treeHelper.getSelectedNode(); - if (ContentReferenceUIHandler.class.isAssignableFrom(getClass())) { - node = node.getParent(); - } - ui.setContentIcon(render.getNavigationIcon(node)); - - updateActions(); - } - - public Icon getErrorIconIfFalse(boolean valid) { - Icon icon = null; - if (!valid) { - icon = errorIcon; - } - return icon; - } - - public void startEditUI(String... binding) { - - E editBean = getBean(); - - prepareValidationContext(); - - // reset all validators - SwingValidatorUtil.setValidatorBean(ui, null); - // mark ui as editing - getModel().setEditing(true); - - // attach validators - SwingValidatorUtil.setValidatorBean(ui, editBean); - if (binding.length > 0) { - - // force widget binding - UIHelper.processDataBinding(ui, binding); - } - UIHelper.processDataBinding(ui, "reset.enabled", "save.enabled"); - } - - public void stopEditUI() { - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ValidationContext context = applicationContext.getValidationContext(); - context.cleanCache(); - - ContentUIModel<E> model = getModel(); - - // mark ui as not editing - model.setEditing(false); - - // mark ui as valid while not editing - model.setValid(true); - - // mark ui as not modified - model.setModified(false); - - // removed initial edit object from context - ui.removeContextValue(model.getBeanType(), "edit"); - - // dettach all validators - SwingValidatorUtil.setValidatorBean(ui, null); - } - - public void resetEditUI() { - - // on arrete l'edition - stopEditUI(); - - // suppression des messages de validation - removeAllMessages(ui); - - // on re-ouvre l'écran d'édition - try { - openUI(); - } catch (Exception ex) { - UIHelper.handlingError(ex); - stopEditUI(); - } - } - - public void restartEditUI() { - - ContentUIModel<E> model = getModel(); - - if (!model.isEditable()) { - - // l'ecran n'est pas éditable, on ne re-ouvre pas - // on quite de suite - return; - } - if (log.isInfoEnabled()) { - log.info(prefix + "Will restart edit " + getUi().getClass().getName()); - } - - // on ne peut redemarrer une edition que si la donnee - // est exactement une entites (pas possible sur une liste) - ObserveTreeHelper treeHelper = getTreeHelper(ui); -// ObserveNode node = treeHelper.getSelectedNode(); - - removeAllMessages(ui); - -// treeHelper.refreshNode(node, true); - treeHelper.reloadSelectedNode(false, true); - - model.setMode(ContentMode.UPDATE); - - // redemarrage de l'édition - ui.startEdit(null); - - updateActions(); - } - - public final void saveUI(boolean refresh) { - boolean ok = false; - try { - ok = doSave(getBean()); - - } catch (Exception e) { - UIHelper.handlingError(e); - } finally { - if (ok) { - afterSave(refresh); - } - } - } - - public final boolean closeUI() { - boolean b = checkEdit(ui); - if (log.isDebugEnabled()) { - log.debug("Can close " + ui.getClass() + " : " + b); - } - if (b) { - closeSafeUI(); - } - return b; - } - - public final void deleteUI() { - boolean ok = false; - ui.stopEdit(); - removeAllMessages(ui); - - try { - ok = doDelete(getBean()); - - } catch (Exception e) { - UIHelper.handlingError(e); - } finally { - if (ok) { - afterDelete(); - } - } - } - - public <C extends DataDto> void gotoChild(DataReference<C> entity) { - if (entity == null) { - - // rien a faire - return; - } - ObserveTreeHelper treeHelper = getTreeHelper(ui); - ObserveNode parentNode = treeHelper.getSelectedNode(); - String id = entity.getId(); - ObserveNode node = treeHelper.findNode(parentNode, id); - if (log.isInfoEnabled()) { - log.info("will go to node " + node + " for " + id); - } - treeHelper.selectNode(node); - } - - public void addChild(Class<?> type) { - ObserveTreeHelper treeHelper = getTreeHelper(ui); - ObserveNode parentNode = treeHelper.getSelectedNode(); - treeHelper.addUnsavedNode(parentNode, type); - } - - public <E> List<E> updateList(BeanListHeader<E> list, List<E> data, String message) { - if (data != null && !data.isEmpty()) { - if (log.isDebugEnabled()) { - log.debug(list.getName() + " - " + data.size()); - } - Decorator<E> decorator = list.getHandler().getDecorator(); - DecoratorUtil.sort((JXPathDecorator<E>) decorator, data, 0); - return data; - } else { - List<E> result = new ArrayList<>(); - return result; - } - } - - public void openLink(String url) { - - try { - - UIHelper.openLink(url); - } catch (Exception e) { - UIHelper.handlingError(e); - } - } - - public String updateTitle(String title) { - if (ContentReferenceUIHandler.class.isAssignableFrom(getClass())) { - return DecoratorService.getEntityLabel(getBeanType()); - } - return title; - } - - protected void loadReferentialReferenceSetsInModel(Form<E> form) { - - String requestName = form.getReferentialReferenceSetsRequestName(); - - if (requestName != null) { - - loadReferentialReferenceSetsInModel(requestName); - - } - - } - - protected void loadReferentialReferenceSetsInModel(String requestName) { - - ImmutableMap.Builder<String, ReferentialReferenceSet<?>> modelReferentialReferenceSets = ImmutableMap.builder(); - - if (log.isInfoEnabled()) { - log.info("Update referential reference sets for: " + requestName); - } - - // mettre à jour le cache de référentiel - ImmutableMap<Class<?>, ReferentialReferenceSet<?>> referentialReferenceSetsByType = getDataSource().updateReferentialReferenceSetsCache(requestName); - - // calculer les listes de référentiels à utiliser dans le modèle - - ReferenceSetRequestDefinition requestDefinition = ReferenceSetRequestDefinitions.get(requestName); - - for (ReferenceSetRequestKeyDefinition propertyDefinition : requestDefinition.getPropertyDefinitions()) { - - if (!propertyDefinition.isReferential()) { - continue; - } - - String propertyName = propertyDefinition.getName(); - ReferentialReferenceSet referentialReferenceSet = referentialReferenceSetsByType.get(propertyDefinition.getType()); - ReferentialReferenceSet filteredReferentialReferenceSet = filterReferentialReferenceSet(propertyDefinition, referentialReferenceSet); - - modelReferentialReferenceSets.put(propertyName, filteredReferentialReferenceSet); - - } - - getModel().setReferentialReferenceSets(modelReferentialReferenceSets.build()); - - } - - protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { - - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), original size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - // by default always remove obsolete references - List<ReferentialReference<D>> referentialReferences = ReferentialReferences.filterEnabled(incomingReferences); - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), without diabled size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - return referentialReferences; - - } - - /** - * Calcule le mode de l'écran. - * - * @param dataContext le context de données - * @return {@code null} si l'écran est éditable, autrement le mode - * restreint READ @param dataContext le context de données - */ - protected abstract ContentMode getContentMode(DataContext dataContext); - - /** - * Pour calculer la propriete {@code canWrite} du modèle. - * - * @param dataSsource la base source de l'ui - * @return {@code true} si on peut écrire (donc éditer), {@code false} autrement. - */ - protected abstract boolean computeCanWrite(ObserveSwingDataSource dataSsource); - - protected final String getSelectedParentId() { - String s = null; - if (parentType != null) { - s = parentType.getSelectedId(getDataContext()); - } - return s; - } - - protected final String getSelectedId() { - String s = null; - if (type != null) { - s = type.getSelectedId(getDataContext()); - } - return s; - } - - protected DataContext getDataContext() { - DataContext dataContext = ui.getDataContext(); - return dataContext; - } - - protected ObserveSwingDataSource getDataSource() { - return ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); - } - - protected ObserveOpenDataManager getOpenDataManager() { - ObserveOpenDataManager openDataManager = ObserveSwingApplicationContext.get().getOpenDataManager(); - return openDataManager; - } - - protected boolean doSave(E bean) throws Exception { - return false; - } - - protected void afterSave(boolean refresh) { - - // mettre les validateurs en mode non modifié - SwingValidatorUtil.setValidatorChanged(ui, false); - } - - protected void closeSafeUI() { - - removeAllMessages(ui); - ContentUIModel<E> model = getModel(); - - boolean create = model.isCreatingMode(); - if (create && model.isEditable()) { - // remove node - ObserveTreeHelper treehelper = getTreeHelper(ui); - ObserveNode node = treehelper.getSelectedNode(); - - ObserveNode parentNode = node.getParent(); - if (parentNode != null) { - // node still attached, so remove it - treehelper.removeNode(node); - treehelper.selectNode(parentNode); - } - } - - } - - protected boolean doDelete(E bean) { - return false; - } - - protected boolean askToDelete(E bean) { - boolean accept = - UIHelper.confirmForEntityDelete(ui, getBeanType(), bean); - - return !accept; - } - - protected void afterDelete() { - ui.stopEdit(); - removeAllMessages(ui); - if (!(getBean() instanceof ReferentialDto)) { - - ObserveTreeHelper treeHelper = getTreeHelper(ui); - ObserveNode node = treeHelper.getSelectedNode(); - ObserveNode parentNode = treeHelper.removeNode(node); - treeHelper.selectNode(parentNode); - } - } - - protected void addInfoMessage(String message) { - addMessage(ui, - NuitonValidatorScope.INFO, - getEntityLabel(getModel().getBeanType()), - t(message) - ); - } - - protected String getEntityLabel(Class<?> klass) { - String result = DecoratorService.getEntityLabel(klass); - return result; - } - - protected void prepareValidationContext() { - - // reset validation cache - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ValidationContext context = applicationContext.getValidationContext(); - context.cleanCache(); - } - - protected final ContentMode computeContentMode() { - ContentMode mode; - - if (!getModel().isCanWrite()) { - if (ReferentialDto.class.isAssignableFrom(getBeanType())) { - addInfoMessage(t("observe.message.referentiel.no.editable")); - } else { - addInfoMessage(t("observe.message.can.not.write.data")); - } - mode = ContentMode.READ; - } else { - - // ask specified handler which mode to use - mode = getContentMode(getDataContext()); - } - return mode; - } - - protected final String getValidatorContextName(ContentMode mode) { - String contextName = - mode == ContentMode.CREATE ? "ui-create" : "ui-update"; - return contextName; - } - - protected void updateActions() { - - updateToolbarActions(); - - ActionMap actionMap = ObserveSwingApplicationContext.get().getActionMap(); - - for (String name : ui.get$objectMap().keySet()) { - Object o = ui.getObjectById(name); - - if (o instanceof AbstractButton) { - - AbstractButton button = (AbstractButton) o; - - String actionId = (String) button.getClientProperty(ContentUIInitializer.OBSERVE_ACTION); - - if (actionId == null) { - continue; - } - AbstractUIAction action = (AbstractUIAction) actionMap.get(actionId); - - if (log.isDebugEnabled()) { - log.debug("update common action " + actionId); - } - - action.updateAction(ui, button); - } - } - } - - protected void updateToolbarActions() { - ObserveContentUI<E> ui = getUi(); - JToolBar toolBar = ui.getTitleRightToolBar(); - Component[] components = toolBar.getComponents(); - for (Component component : components) { - if (component instanceof JComponent) { - JComponent jcompo = (JComponent) component; - if (jcompo.getClientProperty("original") != null) { - - // on conserve ce component - continue; - } - } - - toolBar.remove(component); - } - } - - protected Icon updateModeIcon(ContentMode mode) { - Icon icon = null; - if (mode != null) { - icon = (Icon) ((JComponent) ui).getClientProperty(mode.name() + "Icon"); - } - return icon; - } - - protected String updateModeTip(ContentMode mode) { - String tip = null; - if (mode != null) { - tip = (String) ((JComponent) ui).getClientProperty(mode.name() + "Tip"); - } - return tip; - } - - protected void setContentMode(ContentMode newMode) { - // pour reforcer le binding sur le mode - // cela est nécessaire car le mode peut-être positionné avant d'arriver - // sur le bon noeud et donc les calculs d'accessibilité de certaines - // actions ne sont pas corrects (par exemple action goDown) - getModel().setMode(null); - getModel().setMode(newMode); - } - - //FIXME Do it in jaxx - protected void resetQuadrant(CoordinatesEditor editor) { - - editor.setQuadrant(null); - JAXXButtonGroup quadrantBG = editor.getQuadrantBG(); - - quadrantBG.setSelectedValue(null); - quadrantBG.setSelectedButton(null); - - quadrantBG.remove(editor.getQuadrant1()); - quadrantBG.remove(editor.getQuadrant2()); - quadrantBG.remove(editor.getQuadrant3()); - quadrantBG.remove(editor.getQuadrant4()); - - editor.getQuadrant1().setSelected(false); - editor.getQuadrant2().setSelected(false); - editor.getQuadrant3().setSelected(false); - editor.getQuadrant4().setSelected(false); - - quadrantBG.add(editor.getQuadrant1()); - quadrantBG.add(editor.getQuadrant2()); - quadrantBG.add(editor.getQuadrant3()); - quadrantBG.add(editor.getQuadrant4()); - - } - - /** - * Pour mettre à jour les composants graphiques avec les référentiels chargés dans le modèle - */ - protected void updateUiWithReferenceSetsFromModel() { - - for (String name : ui.get$objectMap().keySet()) { - Object o = ui.getObjectById(name); - - if (o == null) { - continue; - } - - if (o instanceof BeanComboBox) { - - BeanComboBox beanComboBox = (BeanComboBox) o; - - Class dtoClass = getDtoClass(beanComboBox); - if (ReferentialDto.class.isAssignableFrom(dtoClass)) { - updateReferentialBeanComboBox(dtoClass, beanComboBox); - } else { - updateDataBeanComboBox(dtoClass, beanComboBox); - } - - continue; - } - - if (o instanceof BeanListHeader) { - - BeanListHeader beanListHeader = (BeanListHeader) o; - - Class dtoClass = getDtoClass(beanListHeader); - if (ReferentialDto.class.isAssignableFrom(dtoClass)) { - updateReferentialBeanListHeader(dtoClass, beanListHeader); - } else { - updateDataBeanListHeader(dtoClass, beanListHeader); - } - - continue; - } - - if (o instanceof FilterableDoubleList) { - - FilterableDoubleList filterableDoubleList = (FilterableDoubleList) o; - - Class dtoClass = getDtoClass(filterableDoubleList); - if (ReferentialDto.class.isAssignableFrom(dtoClass)) { - updateReferentialFilterableDoubleList(dtoClass, filterableDoubleList); - } else { - updateDataFilterableDoubleList(dtoClass, filterableDoubleList); - } - - } - - } - - } - - protected <R extends DataDto> void updateDataFilterableDoubleList(Class<R> dtoClass, FilterableDoubleList<DataReference<R>> list) { - - List<DataReference<R>> data; - - if (getModel().getForm() == null) { - data = Collections.emptyList(); - } else { - - Set<DataReference<R>> referenceSetDto = getModel().getDataReferences(list.getModel().getProperty()); - data = new ArrayList<>(referenceSetDto); - - } - - // sort data from first decorator context - DataReferenceDecorator<R> decorator = getDataReferenceDecorator(dtoClass); - DecoratorUtil.sort(decorator, data, 0); - - //FIXME A finir (bien vérifier que la sélection n'est plus dans l'univers) - List<DataReference<R>> selected = list.getModel().getSelected(); - list.setUniverse(data); - list.setSelected(selected); - - list.putClientProperty("data", data); - } - - protected <R extends ReferentialDto> void updateReferentialFilterableDoubleList(Class<R> dtoClass, FilterableDoubleList<ReferentialReference<R>> list) { - - Boolean forceLoadComboBox = (Boolean) list.getClientProperty(ObserveContentUI.CLIENT_PROPERTY_FORCE_LOAD); - - List<ReferentialReference<R>> data; - - if (BooleanUtils.isNotTrue(forceLoadComboBox) && getModel().getForm() == null) { - data = Collections.emptyList(); - } else { - - Set<ReferentialReference<R>> referenceSetDto = getModel().getReferentialReferences(list.getModel().getProperty()); - data = new ArrayList<>(referenceSetDto); - - } - - // sort data from first decorator context - ReferentialReferenceDecorator<R> decorator = getReferentialReferenceDecorator(dtoClass); - DecoratorUtil.sort(decorator, data, 0); - - //FIXME A finir (bien vérifier que la sélection n'est plus dans l'univers) - List<ReferentialReference<R>> selected = list.getModel().getSelected(); - list.setUniverse(data); - list.setSelected(selected); - - list.putClientProperty("data", data); - } - - protected <R extends ReferentialDto> void updateReferentialBeanListHeader(Class<R> dtoClass, BeanListHeader<ReferentialReference<R>> list) { - - Boolean noLoad = (Boolean) list.getClientProperty(ObserveContentUI.CLIENT_PROPERTY_LIST_NO_LOAD); - - List<ReferentialReference<R>> data; - - String propertyName = list.getName(); - - if (!"referentialListHeader".equals(propertyName) && (BooleanUtils.isTrue(noLoad) || getModel().getForm() == null)) { - - if (log.isInfoEnabled()) { - log.info(String.format("Skip loading of BeanListHeader [%s-%s] (listNoLoad property found or form is null)", dtoClass.getSimpleName(), propertyName)); - } - data = Collections.emptyList(); - - } else { - - Set<ReferentialReference<R>> referenceSetDto = getModel().getReferentialReferences(propertyName); - data = new ArrayList<>(referenceSetDto); - - } - - // sort data from first decorator context - ReferentialReferenceDecorator<R> decorator = getReferentialReferenceDecorator(dtoClass); - DecoratorUtil.sort(decorator, data, 0); - - list.setData(data); - list.putClientProperty("data", data); - list.getList().setListData(data.toArray()); - - } - - protected <R extends DataDto> void updateDataBeanListHeader(Class<R> dtoClass, BeanListHeader<DataReference<R>> list) { - - Boolean noLoad = (Boolean) list.getClientProperty(ObserveContentUI.CLIENT_PROPERTY_LIST_NO_LOAD); - - List<DataReference<R>> data; - - String propertyName = list.getName(); - - if (BooleanUtils.isTrue(noLoad) || getModel().getForm() == null) { - - if (log.isInfoEnabled()) { - log.info(String.format("Skip loading of BeanListHeader [%s-%s] (listNoLoad property found or form is null)", dtoClass.getSimpleName(), propertyName)); - } - data = Collections.emptyList(); - - } else { - - Set<DataReference<R>> referenceSetDto = getModel().getDataReferences(propertyName); - data = new ArrayList<>(referenceSetDto); - - } - - // sort data from first decorator context - DataReferenceDecorator<R> decorator = getDataReferenceDecorator(dtoClass); - DecoratorUtil.sort(decorator, data, 0); - - list.setData(data); - list.putClientProperty("data", data); - - } - - protected <R extends ReferentialDto> void updateReferentialBeanComboBox(Class<R> dtoClass, BeanComboBox<ReferentialReference<R>> comboBox) { - - Boolean noLoad = (Boolean) comboBox.getClientProperty(ObserveContentUI.CLIENT_PROPERTY_LIST_NO_LOAD); - Boolean forceLoadComboBox = (Boolean) comboBox.getClientProperty(ObserveContentUI.CLIENT_PROPERTY_FORCE_LOAD); - String propertyName = comboBox.getProperty(); - - List<ReferentialReference<R>> data; - - if (BooleanUtils.isNotTrue(forceLoadComboBox) && (BooleanUtils.isTrue(noLoad) || getModel().getForm() == null ) ) { - - if (log.isInfoEnabled()) { - log.info(String.format("Skip loading of comboBox [%s-%s] (listNoLoad property found or form is null)", dtoClass.getSimpleName(), propertyName)); - } - data = Collections.emptyList(); - - } else { - - Optional<Set<ReferentialReference<R>>> optionalReferenceSetDto = getModel().tryToGetReferentialReferenceSet(propertyName); - - if (optionalReferenceSetDto.isPresent()) { - - Set<ReferentialReference<R>> references = optionalReferenceSetDto.get(); - data = Lists.newArrayList(references); - - } else { - - data = Collections.emptyList(); - - } - - } - - if (log.isInfoEnabled()) { - log.info(String.format("comboBox [%s-%s] : %d", dtoClass.getSimpleName(), propertyName, data.size())); - } - - comboBox.setData(data); - - } - - protected <R extends DataDto> void updateDataBeanComboBox(Class<R> dtoClass, BeanComboBox<DataReference<R>> comboBox) { - - Boolean noLoad = (Boolean) comboBox.getClientProperty(ObserveContentUI.CLIENT_PROPERTY_LIST_NO_LOAD); - String propertyName = comboBox.getProperty(); - - List<DataReference<R>> data; - - if (BooleanUtils.isTrue(noLoad) || getModel().getForm() == null) { - - if (log.isInfoEnabled()) { - log.info(String.format("Skip loading of comboBox [%s-%s] (listNoLoad property found or form is null)", dtoClass.getSimpleName(), propertyName)); - } - data = Collections.emptyList(); - - } else { - - Optional<Set<DataReference<R>>> optionalReferenceSetDto = getModel().tryToGetDataReferenceSet(propertyName); - - if (optionalReferenceSetDto.isPresent()) { - - Set<DataReference<R>> references = optionalReferenceSetDto.get(); - data = Lists.newArrayList(references); - - } else { - data = Collections.emptyList(); - } - - } - - if (log.isInfoEnabled()) { - log.info(String.format("entity comboBox [%s-%s] : %d", dtoClass.getSimpleName(), propertyName, data.size())); - } - - comboBox.setData(data); - } - - protected <R extends IdDto> Class<R> getDtoClass(JComponent list) { - Object clientProperty = list.getClientProperty(ObserveContentUI.CLIENT_PROPERTY_ENTITY_CLASS); - return (Class<R>) clientProperty; - } - - protected <R extends DataDto> DataReferenceDecorator<R> getDataReferenceDecorator(Class<R> dtoType) { - return getDecoratorService().getDataReferenceDecorator(dtoType); - } - - protected <R extends ReferentialDto> ReferentialReferenceDecorator<R> getReferentialReferenceDecorator(Class<R> dtoType) { - return getDecoratorService().getReferentialReferenceDecorator(dtoType); - } - - private <D extends ReferentialDto> ReferentialReferenceSet<D> filterReferentialReferenceSet(ReferenceSetRequestKeyDefinition<D> propertyDefinition, - ReferentialReferenceSet<D> incomingReferentialReferenceSet) { - - Class<D> dtoType = propertyDefinition.getType(); - String propertyName = propertyDefinition.getName(); - - LinkedList<ReferentialReference<D>> incomingReferences = Lists.newLinkedList(incomingReferentialReferenceSet.getReferences()); - - Iterable<ReferentialReference<D>> filtredReferentialReferences = filterReferentialReferences(dtoType, propertyName, incomingReferences); - - ImmutableSet<ReferentialReference<D>> references1 = ImmutableSet.copyOf(filtredReferentialReferences); - ReferentialReferenceSet<D> filtredReferentialReferenceSet = ReferentialReferenceSet.of(dtoType, references1, incomingReferentialReferenceSet.getLastUpdate()); - return filtredReferentialReferenceSet; - - } - - -// protected static class LogPropertyChanges implements PropertyChangeListener { -// -// private final ImmutableSet<String> propertyNames; -// -// public LogPropertyChanges(ImmutableSet<String> propertyNames) { -// this.propertyNames = propertyNames; -// } -// -// @Override -// public void propertyChange(PropertyChangeEvent evt) { -// -// if (propertyNames.contains(evt.getPropertyName())) { -// if (log.isInfoEnabled()) { -// log.info(String.format("Property %s changed (%s → %s)", evt.getPropertyName(), evt.getOldValue(), evt.getNewValue())); -// } -// -// } -// -// } -// -// } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ContentUIInitializer.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ContentUIInitializer.java deleted file mode 100644 index b0c0735..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ContentUIInitializer.java +++ /dev/null @@ -1,853 +0,0 @@ -package fr.ird.observe.ui.content; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.Lists; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.application.swing.decoration.decorators.DataReferenceDecorator; -import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; -import fr.ird.observe.services.dto.AbstractReference; -import fr.ird.observe.services.dto.DataDto; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.util.I18nEnumUtil; -import fr.ird.observe.ui.actions.shared.AbstractUIAction; -import fr.ird.observe.ui.util.BooleanEditor; -import fr.ird.observe.ui.util.tripMap.ObserveMapPane; -import fr.ird.observe.validation.ObserveSwingValidator; -import jaxx.runtime.JAXXValidator; -import jaxx.runtime.SwingUtil; -import jaxx.runtime.swing.JAXXWidgetUtil; -import jaxx.runtime.swing.OneClicListSelectionModel; -import jaxx.runtime.swing.editor.EnumEditor; -import jaxx.runtime.swing.editor.NumberEditor; -import jaxx.runtime.swing.editor.bean.BeanComboBox; -import jaxx.runtime.swing.editor.bean.BeanListHeader; -import jaxx.runtime.swing.editor.bean.BeanUIUtil; -import jaxx.runtime.swing.editor.cell.NumberCellEditor; -import jaxx.runtime.swing.renderer.DecoratorListCellRenderer; -import jaxx.runtime.swing.renderer.EnumEditorRenderer; -import jaxx.runtime.validator.swing.SwingValidatorUtil; -import org.apache.commons.lang3.BooleanUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.jdesktop.swingx.JXDatePicker; -import org.jdesktop.swingx.JXMonthView; -import org.jdesktop.swingx.autocomplete.ComboBoxCellEditor; -import org.jdesktop.swingx.autocomplete.ObjectToStringConverter; -import org.nuiton.decorator.Decorator; -import org.nuiton.jaxx.application.bean.JavaBeanObjectUtil; -import org.nuiton.jaxx.widgets.datetime.DateTimeEditor; -import org.nuiton.jaxx.widgets.datetime.TimeEditor; -import org.nuiton.jaxx.widgets.gis.absolute.CoordinatesEditor; -import org.nuiton.jaxx.widgets.select.FilterableDoubleList; -import org.nuiton.util.DateUtil; - -import javax.swing.AbstractButton; -import javax.swing.ActionMap; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JScrollBar; -import javax.swing.JSpinner; -import javax.swing.JTable; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.ListCellRenderer; -import javax.swing.SwingUtilities; -import javax.swing.border.LineBorder; -import javax.swing.table.TableCellEditor; -import java.awt.Color; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.event.FocusAdapter; -import java.awt.event.FocusEvent; -import java.awt.event.ItemEvent; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Date; -import java.util.EnumSet; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -import static org.nuiton.i18n.I18n.t; - -/** - * To initialize ui. - * - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class ContentUIInitializer<E extends IdDto, UI extends ObserveContentUI<E>> { - - public static final String OBSERVE_ACTION = "observeAction"; - - public static final String CLIENT_PROPERTY_PROPERTY_NAME = "propertyName"; - - public static final String CLIENT_PROPERTY_RESET_PROPERTY_NAME = "resetPropertyName"; - - public static final String CLIENT_PROPERTY_NOT_BLOCKING = "notBlocking"; - - /** Logger. */ - private static final Log log = LogFactory.getLog(ContentUIInitializer.class); - - protected final UI ui; - - protected final DecoratorService decoratorService; - - public ContentUIInitializer(UI ui) { - this.ui = ui; - this.decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); - } - - public static TableCellEditor newFloatColumnEditor(JTable table) { - - NumberCellEditor<Float> editor = JAXXWidgetUtil.newNumberTableCellEditor(Float.class, false); - editor.getNumberEditor().setSelectAllTextOnError(true); - editor.getNumberEditor().getTextField().setBorder(new LineBorder(Color.GRAY, 2)); - editor.getNumberEditor().setNumberPattern("\\d{0,6}(\\.\\d{0,4})?"); - return editor; - - } - - public static TableCellEditor newIntegerColumnEditor(JTable table) { - - NumberCellEditor<Integer> editor = JAXXWidgetUtil.newNumberTableCellEditor(Integer.class, false); - editor.getNumberEditor().setSelectAllTextOnError(true); - editor.getNumberEditor().getTextField().setBorder(new LineBorder(Color.GRAY, 2)); - editor.getNumberEditor().setNumberPattern("\\d{0,4}?"); - return editor; - - } - - public static <B> ComboBoxCellEditor newDataColumnEditor(List<B> data, Decorator<B> decorator) { - - JComboBox<B> comboBox = new JComboBox<>(); - - return newDataColumnEditor(comboBox, data, decorator); - - } - - public static <B> ComboBoxCellEditor newDataColumnEditor(JComboBox<B> comboBox, List<B> data, Decorator<B> decorator) { - - ListCellRenderer<B> renderer = new DecoratorListCellRenderer(decorator); - comboBox.setRenderer(renderer); - - prepareComboBoxData(comboBox, data); - - ObjectToStringConverter converter = BeanUIUtil.newDecoratedObjectToStringConverter(decorator); - BeanUIUtil.decorate(comboBox, converter); - ComboBoxCellEditor editor = new ComboBoxCellEditor(comboBox); - return editor; - - } - - public static <B> void prepareComboBoxData(JComboBox comboBox, List<B> data) { - List<B> dataToList = Lists.newArrayList(data); - - // add a null value at first position - if (!dataToList.isEmpty() && dataToList.get(0) != null) { - dataToList.add(0, null); - } - SwingUtil.fillComboBox(comboBox, dataToList, null); - } - - protected E getBean() { - - E bean = ui.getModel().getBean(); - return bean; - - } - - protected Form<E> getFormDto() { - return ui.getModel().getForm(); - } - - public void initUI() { - - if (log.isDebugEnabled()) { - log.debug("ui " + getClass()); - } - - ActionMap actionMap = ObserveSwingApplicationContext.get().getActionMap(); - - // initialisation des éditeurs - - Set<String> doNotBlockComponentIds = new HashSet<>(); - - for (String name : ui.get$objectMap().keySet()) { - Object o = ui.getObjectById(name); - - if (o == null) { - continue; - } - - if (o instanceof JComponent) { - - init((JComponent) o, doNotBlockComponentIds); - } - - if (o instanceof JCheckBox) { - init((JCheckBox) o); - } - - if (o instanceof AbstractButton) { - init(actionMap, (AbstractButton) o); - continue; - } - - if (o instanceof NumberEditor) { - init((NumberEditor) o); - continue; - } - - if (o instanceof BeanComboBox<?>) { - init((BeanComboBox<?>) o); - continue; - } - - if (o instanceof BeanListHeader<?>) { - init((BeanListHeader) o); - continue; - } - - if (o instanceof FilterableDoubleList<?>) { - init((FilterableDoubleList<?>) o); - continue; - } - - if (o instanceof JXDatePicker) { - init((JXDatePicker) o); - continue; - } - - if (o instanceof TimeEditor) { - init((TimeEditor) o); - continue; - } - - if (o instanceof DateTimeEditor) { - init((DateTimeEditor) o); - continue; - } - - if (o instanceof CoordinatesEditor) { - init((CoordinatesEditor) o); - continue; - } - - if (o instanceof BooleanEditor) { - init((BooleanEditor) o); - continue; - } - - if (o instanceof EnumEditor) { - init((EnumEditor) o); - continue; - } - - if (o instanceof ObserveSwingValidator<?>) { - init(ui, (ObserveSwingValidator<?>) o); - continue; - } - - if (o instanceof JTextField) { - init((JTextField) o); - continue; - } - - if (o instanceof JTextArea) { - init((JTextArea) o); - } - - } - - if (!doNotBlockComponentIds.isEmpty()) { - - String[] acceptedComponentNames = doNotBlockComponentIds.toArray(new String[doNotBlockComponentIds.size()]); - - initBlockLayerUI(acceptedComponentNames); - - } - } - - protected void initBlockLayerUI(String... doNotBlockComponentIds) { - ui.getBlockLayerUI().setAcceptedComponentTypes(ObserveMapPane.class, JScrollBar.class); - ui.getBlockLayerUI().setAcceptedComponentNames(doNotBlockComponentIds); - - } - - protected void init(UI ui, ObserveSwingValidator<?> validator) { - SwingValidatorUtil.listenValidatorContextNameAndRefreshFields( - validator, - (JAXXValidator) ui - ); - } - - protected void init(ActionMap actionMap, AbstractButton editor) { - String actionId = (String) editor.getClientProperty(OBSERVE_ACTION); - if (actionId == null) { - // le boutton n'est pas commun - - final String propertyName = (String) editor.getClientProperty(CLIENT_PROPERTY_RESET_PROPERTY_NAME); - if (propertyName != null) { - editor.addActionListener(e -> JavaBeanObjectUtil.setProperty(getBean(), propertyName, null)); - } - - return; - } - - // on a trouve une action commune - AbstractUIAction action = (AbstractUIAction) actionMap.get(actionId); - - if (action == null) { - - // l'action n'est pas enregistrée - throw new IllegalStateException( - "action [" + actionId + "] not found for ui " + - ui.getClass().getName()); - } - - if (log.isDebugEnabled()) { - log.debug("init common action " + actionId); - } - - action.initAction(null, editor); - } - - protected void init(NumberEditor editor) { - if (log.isDebugEnabled()) { - log.debug("init number editor " + editor.getName()); - } - editor.init(); - } - - protected void init(BeanComboBox beanComboBox) { - if (log.isDebugEnabled()) { - log.debug("init combobox for " + beanComboBox.getBeanType()); - } - beanComboBox.setI18nPrefix("observe.common."); - beanComboBox.setMinimumSize(new Dimension(0, 24)); - - Class dtoClass = getDtoClass(beanComboBox); - - if (ReferentialDto.class.isAssignableFrom(dtoClass)) { - prepareReferentialBeanComboBox(dtoClass, beanComboBox); - } else { - prepareDataBeanComboBox(dtoClass, beanComboBox); - } - - } - - protected void init(BeanListHeader beanList) { - - beanList.setI18nPrefix("observe.common."); - - if (log.isInfoEnabled()) { - log.info("init list for " + beanList.getBeanType()); - } - - Class dtoClass = getDtoClass(beanList); - - if (ReferentialDto.class.isAssignableFrom(dtoClass)) { - prepareReferentialEntityList(dtoClass, beanList); - } else { - prepareDataEntityList(dtoClass, beanList); - } - - } - - protected void init(FilterableDoubleList beanList) { - - beanList.setI18nPrefix("observe.common."); - - if (log.isInfoEnabled()) { - log.info("init list for " + beanList.getBeanType()); - } - - Class dtoClass = getDtoClass(beanList); - - if (ReferentialDto.class.isAssignableFrom(dtoClass)) { - prepareReferentialFilterableDoubleList(dtoClass, beanList); - } else { - prepareDataFilterableDoubleList(dtoClass, beanList); - } - - } - - protected void init(TimeEditor editor) { - if (log.isDebugEnabled()) { - log.debug("init time editor " + editor.getName()); - } - editor.init(); - if (isAutoSelectOnFocus(editor)) { - - addAutoSelectOnFocus((JSpinner.DateEditor) editor.getHourEditor().getEditor()); - addAutoSelectOnFocus((JSpinner.DateEditor) editor.getMinuteEditor().getEditor()); - - } - } - - protected void init(DateTimeEditor editor) { - if (log.isDebugEnabled()) { - log.debug("init date time editor " + editor.getName()); - } - editor.init(); - if (isAutoSelectOnFocus(editor)) { - - addAutoSelectOnFocus((JSpinner.DateEditor) editor.getHourEditor().getEditor()); - addAutoSelectOnFocus((JSpinner.DateEditor) editor.getMinuteEditor().getEditor()); - - } - } - - private void addAutoSelectOnFocus(JSpinner.DateEditor hourEditor) { - addAutoSelectOnFocus(hourEditor.getTextField()); - } - - protected void init(CoordinatesEditor editor) { - if (log.isDebugEnabled()) { - log.debug("init coordinates editor " + editor.getName()); - } - editor.init(); - } - - protected void init(JTextField editor) { - - final String propertyName = (String) editor.getClientProperty(CLIENT_PROPERTY_PROPERTY_NAME); - if (propertyName != null) { - editor.addKeyListener(new KeyAdapter() { - - @Override - public void keyReleased(KeyEvent e) { - JTextField source = (JTextField) e.getSource(); - String text = source.getText(); - JavaBeanObjectUtil.setProperty(getBean(), propertyName, text); - } - }); - } - } - - protected void init(JTextArea editor) { - - final String propertyName = (String) editor.getClientProperty(CLIENT_PROPERTY_PROPERTY_NAME); - if (propertyName != null) { - editor.addKeyListener(new KeyAdapter() { - - @Override - public void keyReleased(KeyEvent e) { - JTextArea source = (JTextArea) e.getSource(); - String text = source.getText(); - JavaBeanObjectUtil.setProperty(getBean(), propertyName, text); - } - }); - } - } - - protected void init(BooleanEditor editor) { - if (log.isDebugEnabled()) { - log.debug("init boolean editor " + editor.getName()); - } - final String propertyName = (String) editor.getClientProperty(CLIENT_PROPERTY_PROPERTY_NAME); - if (propertyName != null) { - editor.addItemListener(event -> { - if (event.getStateChange() == ItemEvent.SELECTED) { - - Boolean newValue = ((BooleanEditor) event.getSource()).getBooleanValue(); - JavaBeanObjectUtil.setProperty(getBean(), propertyName, newValue); - } - }); - } - } - - protected void init(JComponent editor, Set<String> notBlockingComponents) { - final Boolean propertyName = (Boolean) editor.getClientProperty(CLIENT_PROPERTY_NOT_BLOCKING); - if (propertyName != null) { - - if (editor instanceof FilterableDoubleList) { - - notBlockingComponents.add("universeListPane"); - notBlockingComponents.add("selectedListPane"); - - } else { - - notBlockingComponents.add(editor.getName()); - - } - } - } - - protected void init(JCheckBox editor) { - if (log.isDebugEnabled()) { - log.debug("init simple boolean editor " + editor.getName()); - } - final String propertyName = (String) editor.getClientProperty(CLIENT_PROPERTY_PROPERTY_NAME); - if (propertyName != null) { - editor.addItemListener(event -> { - Boolean newValue = ((JCheckBox) event.getSource()).isSelected(); - JavaBeanObjectUtil.setProperty(getBean(), propertyName, newValue); - }); - } - } - - protected void init(JXDatePicker picker) { - - if (log.isDebugEnabled()) { - log.debug("disable JXDatePicker editor" + picker.getName()); - } - picker.getEditor().setEditable(false); - JXMonthView monthView = new JXMonthView(); - monthView.setLowerBound(DateUtil.createDate(1, 1, 1970)); - monthView.setTraversable(true); - monthView.setZoomable(true); - picker.setMonthView(monthView); - - final String propertyName = (String) picker.getClientProperty(CLIENT_PROPERTY_PROPERTY_NAME); - if (propertyName != null) { - picker.addActionListener(e -> { - JXDatePicker source = (JXDatePicker) e.getSource(); - Date date = source.getDate(); - JavaBeanObjectUtil.setProperty(getBean(), propertyName, date); - }); - } - - } - - protected <B extends Enum<B>> void init(EnumEditor<B> editor) { - if (log.isDebugEnabled()) { - log.debug("init enumEditor editor " + editor.getName()); - } - ImmutableMap.Builder<B, String> labelsBuilder = ImmutableMap.builder(); - for (B e : EnumSet.allOf(editor.getType())) { - String label = I18nEnumUtil.getLabel(e); - labelsBuilder.put(e, label); - } - editor.setRenderer(new EnumEditorRenderer<>(labelsBuilder.build())); - } - - protected boolean isAutoSelectOnFocus(JComponent comp) { - Boolean selectOnFocus = (Boolean) comp.getClientProperty("selectOnFocus"); - return BooleanUtils.isTrue(selectOnFocus); - } - - protected void addAutoSelectOnFocus(JTextField jTextField) { - jTextField.addFocusListener(new FocusAdapter() { - - @Override - public void focusGained(final FocusEvent e) { - SwingUtilities.invokeLater(() -> { - JTextField source = (JTextField) e.getSource(); - source.selectAll(); - }); - - } - }); - } - - /** - * Ajoute à une liste graphique donnée le comportement de - * sélection-déselection en un seul click. - * - * TODO: il faudrait que cela ne perturbe pas le comportement des raccourcis clavier. - * - * @param list la liste graphique à traiter - */ - protected void prepareToogleListSelectionModel(JList list) { - - OneClicListSelectionModel model = new OneClicListSelectionModel(list.getSelectionModel(), list.getModel()); - list.setSelectionModel(model); - - } - - /** - * Remplit le modèle d'une liste graphique avec la liste des entités d'un - * type donné sur un service de persistance donné. - * - * @param list le component graphique à initialiser - * @since 1.5 - */ - protected <D extends DataDto> void prepareDataFilterableDoubleList(Class<D> dtoClass, FilterableDoubleList<DataReference<D>> list) { - - DataReferenceDecorator<D> decorator = decoratorService.getDataReferenceDecorator(dtoClass); - if (log.isDebugEnabled()) { - log.debug("Will use decorator " + decorator); - } - - String entityLabel = t(DecoratorService.getEntityLabel(dtoClass)); - list.getPopupSortLabel().setText(t("observe.content.type.data", entityLabel)); - - list.putClientProperty("decorator", decorator); - - list.init(decorator, new ArrayList<>(), new ArrayList<>()); - - JList<AbstractReference<D>> selectedList = list.getSelectedList(); - ListCellRenderer<? super AbstractReference<D>> renderer = selectedList.getCellRenderer(); - - selectedList.setCellRenderer(new ReferentielListCellRenderer<>(renderer)); - list.getUniverseList().setCellRenderer(new ReferentielListCellRenderer<>((ListCellRenderer<? super AbstractReference<IdDto>>) renderer)); - - } - - /** - * Remplit le modèle d'une liste graphique avec la liste des entités d'un - * type donné sur un service de persistance donné. - * - * @param list le component graphique à initialiser - * @since 1.5 - */ - protected <D extends ReferentialDto> void prepareReferentialFilterableDoubleList(Class<D> dtoClass, FilterableDoubleList<ReferentialReference<D>> list) { - - ReferentialReferenceDecorator<D> decorator = decoratorService.getReferentialReferenceDecorator(dtoClass); - if (log.isDebugEnabled()) { - log.debug("Will use decorator " + decorator); - } - - String entityLabel = t(DecoratorService.getEntityLabel(dtoClass)); - list.getPopupSortLabel().setText(t("observe.content.type.referential", entityLabel)); - - list.putClientProperty("decorator", decorator); - - list.init(decorator, new ArrayList<>(), new ArrayList<>()); - - JList<AbstractReference<D>> selectedList = list.getSelectedList(); - ListCellRenderer<? super AbstractReference<D>> renderer = selectedList.getCellRenderer(); - - selectedList.setCellRenderer(new ReferentielListCellRenderer<>(renderer)); - list.getUniverseList().setCellRenderer(new ReferentielListCellRenderer<>((ListCellRenderer<? super AbstractReference<IdDto>>) renderer)); - - } - - /** - * Remplit le modèle d'une liste graphique avec la liste des entités d'un - * type donné sur un service de persistance donné. - * - * @param list le component graphique à initialiser - * @since 1.5 - */ - protected <D extends DataDto> void prepareDataEntityList(Class<D> dtoClass, BeanListHeader<DataReference<D>> list) { - - DataReferenceDecorator<D> decorator = decoratorService.getDataReferenceDecorator(dtoClass); - if (log.isDebugEnabled()) { - log.debug("Will use decorator " + decorator); - } - - String entityLabel = t(DecoratorService.getEntityLabel(dtoClass)); - list.setPopupTitleText(t("observe.content.type.data", entityLabel)); - - list.putClientProperty("decorator", decorator); - - list.init(decorator, Collections.emptyList()); - - JList<AbstractReference<D>> list1 = list.getList(); - ListCellRenderer<? super AbstractReference<D>> renderer = list1.getCellRenderer(); - list1.setCellRenderer(new ReferentielListCellRenderer<>(renderer)); - - } - - /** - * Remplit le modèle d'une liste graphique avec la liste des entités d'un - * type donné sur un service de persistance donné. - * - * @param list le component graphique à initialiser - * @since 1.5 - */ - protected <D extends ReferentialDto> void prepareReferentialEntityList(Class<D> dtoClass, BeanListHeader<ReferentialReference<D>> list) { - - ReferentialReferenceDecorator<D> decorator = decoratorService.getReferentialReferenceDecorator(dtoClass); - if (log.isDebugEnabled()) { - log.debug("Will use decorator " + decorator); - } - - String entityLabel = t(DecoratorService.getEntityLabel(dtoClass)); - list.setPopupTitleText(t("observe.content.type.referential", entityLabel)); - - list.putClientProperty("decorator", decorator); - - list.init(decorator, Collections.emptyList()); - - JList<AbstractReference<D>> list1 = list.getList(); - ListCellRenderer<? super AbstractReference<D>> renderer = list1.getCellRenderer(); - list1.setCellRenderer(new ReferentielListCellRenderer<>(renderer)); - - } - - /** - * Prépare un component de choix d'entités pour un type d'entité donné et pour un service de persistance donné. - * - * @param <D> le type de l'entité - * @param comboBox le component graphique à initialiser - */ - protected <D extends DataDto> void prepareDataBeanComboBox(Class<D> dtoClass, BeanComboBox<DataReference<D>> comboBox) { - - DataReferenceDecorator<D> decorator = decoratorService.getDataReferenceDecorator(dtoClass); - - String entityLabel = t(DecoratorService.getEntityLabel(dtoClass)); - comboBox.setPopupTitleText(t("observe.content.type.data", entityLabel)); - - comboBox.init(decorator, Collections.emptyList()); - - JComboBox<DataReference<D>> combobox = comboBox.getCombobox(); - - ListCellRenderer<DataReference<D>> toolTipRenderer = new ComboBoxListCellRenderer<>(combobox.getRenderer()); - combobox.setRenderer(toolTipRenderer); - if (log.isDebugEnabled()) { - log.debug("combo list [" + dtoClass.getName() + "] : " + comboBox.getData().size()); - } - - } - - /** - * Prépare un component de choix d'entités pour un type d'entité donné et pour un service de persistance donné. - * - * @param <D> le type de l'entité - * @param comboBox le component graphique à initialiser - */ - protected <D extends ReferentialDto> void prepareReferentialBeanComboBox(Class<D> dtoClass, BeanComboBox<ReferentialReference<D>> comboBox) { - - ReferentialReferenceDecorator<D> decorator = decoratorService.getReferentialReferenceDecorator(dtoClass); - - String entityLabel = t(DecoratorService.getEntityLabel(dtoClass)); - comboBox.setPopupTitleText(t("observe.content.type.referential", entityLabel)); - - comboBox.init(decorator, Collections.emptyList()); - - JComboBox<ReferentialReference<D>> combobox = comboBox.getCombobox(); - - ListCellRenderer<ReferentialReference<D>> toolTipRenderer = new ComboBoxListCellRenderer<>(combobox.getRenderer()); - combobox.setRenderer(toolTipRenderer); - if (log.isDebugEnabled()) { - log.debug("combo list [" + dtoClass.getName() + "] : " + comboBox.getData().size()); - } - - } - - protected <D extends IdDto> Class<D> getDtoClass(JComponent list) { - Object clientProperty = list.getClientProperty(ObserveContentUI.CLIENT_PROPERTY_ENTITY_CLASS); - return (Class<D>) clientProperty; - } - - /** - * Un renderer de liste d'entites d'un referentiel dans le quel on veut - * differencier les entites qui sont desactivees. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.2 - */ - public static class ReferentielListCellRenderer<D extends IdDto> implements ListCellRenderer<AbstractReference<D>> { - - /** la couleur normal pour les entites non desactivees */ - protected Color normalColor; - - /** la couleur a utiliser pour les entites desactivees */ - protected Color disableColor = Color.LIGHT_GRAY; - - protected ListCellRenderer<? super AbstractReference<D>> delegate; - - public ReferentielListCellRenderer(ListCellRenderer<? super AbstractReference<D>> delegate) { - this.delegate = delegate; - } - - @Override - public Component getListCellRendererComponent(JList<? extends AbstractReference<D>> list, AbstractReference<D> value, int index, boolean isSelected, boolean cellHasFocus) { - JComponent comp; - comp = (JComponent) delegate.getListCellRendererComponent( - list, - value, - index, - isSelected, - cellHasFocus); - if (normalColor == null) { - // premiere fois, on intialise la couleur dite normale - normalColor = comp.getForeground(); - } - - String tip = null; - - // par defaut, on utilise la couleur normale - Color col = normalColor; - if (value != null) { - - boolean enabled = true; - - if (value instanceof ReferentialReference<?>) { - - ReferentialReference e = (ReferentialReference) value; - enabled = e.isEnabled(); - - } - - if (!enabled) { - // l'entite est desactivee - // on la grise pour bien la differencier - col = disableColor; - tip = t("observe.common.obsolete.entity", ((JLabel) comp).getText()); - } - } - comp.setForeground(col); - comp.setToolTipText(tip); - return comp; - } - - } - - private static class ComboBoxListCellRenderer<E> implements ListCellRenderer<E> { - - private final ListCellRenderer<? super E> renderer; - - public ComboBoxListCellRenderer(ListCellRenderer<? super E> renderer) { - this.renderer = renderer; - } - - @Override - public Component getListCellRendererComponent(JList<? extends E> list, - E value, - int index, - boolean isSelected, - boolean cellHasFocus) { - Component comp = renderer.getListCellRendererComponent( - list, - value, - index, - isSelected, - cellHasFocus - ); - if (comp instanceof JLabel) { - JLabel jcomp = (JLabel) comp; - jcomp.setToolTipText(jcomp.getText()); - } - return comp; - } - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ContentUIManager.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ContentUIManager.java deleted file mode 100644 index c431110..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ContentUIManager.java +++ /dev/null @@ -1,447 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.constants.GearType; -import fr.ird.observe.services.dto.longline.ActivityLonglineDto; -import fr.ird.observe.services.dto.longline.ActivityLonglineEncounterDto; -import fr.ird.observe.services.dto.longline.ActivityLonglineSensorUsedDto; -import fr.ird.observe.services.dto.longline.SetLonglineCatchDto; -import fr.ird.observe.services.dto.longline.SetLonglineDto; -import fr.ird.observe.services.dto.longline.SetLonglineTdrDto; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialDtos; -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.services.dto.seine.ActivitySeineObservedSystemDto; -import fr.ird.observe.services.dto.seine.FloatingObjectDto; -import fr.ird.observe.services.dto.seine.FloatingObjectObservedSpeciesDto; -import fr.ird.observe.services.dto.seine.FloatingObjectSchoolEstimateDto; -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.services.dto.seine.SetSeineDto; -import fr.ird.observe.services.dto.seine.SetSeineNonTargetCatchDto; -import fr.ird.observe.services.dto.seine.SetSeineSchoolEstimateDto; -import fr.ird.observe.services.dto.seine.SetSeineTargetCatchDto; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.impl.longline.LonglineDetailCompositionUI; -import fr.ird.observe.ui.content.impl.longline.LonglineGlobalCompositionUI; -import fr.ird.observe.ui.content.impl.longline.SetLonglineUI; -import fr.ird.observe.ui.content.impl.seine.ActivitySeineObservedSystemUI; -import fr.ird.observe.ui.content.impl.seine.FloatingObjectTransmittingBuoyOperationUI; -import fr.ird.observe.ui.content.impl.seine.FloatingObjectUI; -import fr.ird.observe.ui.content.impl.seine.SetSeineUI; -import fr.ird.observe.ui.content.list.impl.longline.ActivityLonglinesUI; -import fr.ird.observe.ui.content.list.impl.longline.TripLonglinesUI; -import fr.ird.observe.ui.content.list.impl.seine.ActivitySeinesUI; -import fr.ird.observe.ui.content.list.impl.seine.RoutesUI; -import fr.ird.observe.ui.content.list.impl.seine.TripSeinesUI; -import fr.ird.observe.ui.content.open.impl.longline.ActivityLonglineUI; -import fr.ird.observe.ui.content.open.impl.longline.TripLonglineUI; -import fr.ird.observe.ui.content.open.impl.seine.ActivitySeineUI; -import fr.ird.observe.ui.content.open.impl.seine.RouteUI; -import fr.ird.observe.ui.content.open.impl.seine.TripSeineUI; -import fr.ird.observe.ui.content.ref.ContentReferenceUI; -import fr.ird.observe.ui.content.ref.ReferenceHomeUI; -import fr.ird.observe.ui.content.table.impl.longline.CatchLonglineUI; -import fr.ird.observe.ui.content.table.impl.longline.EncounterUI; -import fr.ird.observe.ui.content.table.impl.longline.GearUseFeaturesLonglineUI; -import fr.ird.observe.ui.content.table.impl.longline.SensorUsedUI; -import fr.ird.observe.ui.content.table.impl.longline.TdrUI; -import fr.ird.observe.ui.content.table.impl.seine.GearUseFeaturesSeineUI; -import fr.ird.observe.ui.content.table.impl.seine.NonTargetCatchUI; -import fr.ird.observe.ui.content.table.impl.seine.NonTargetSampleUI; -import fr.ird.observe.ui.content.table.impl.seine.ObjectObservedSpeciesUI; -import fr.ird.observe.ui.content.table.impl.seine.ObjectSchoolEstimateUI; -import fr.ird.observe.ui.content.table.impl.seine.SchoolEstimateUI; -import fr.ird.observe.ui.content.table.impl.seine.TargetCatchUI; -import fr.ird.observe.ui.content.table.impl.seine.TargetDiscardCatchUI; -import fr.ird.observe.ui.content.table.impl.seine.TargetSampleCaptureUI; -import fr.ird.observe.ui.content.table.impl.seine.TargetSampleRejeteUI; -import fr.ird.observe.ui.tree.ObserveNode; -import jaxx.runtime.JAXXContext; -import jaxx.runtime.context.JAXXInitialContext; -import jaxx.runtime.swing.CardLayout2; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JComponent; -import javax.swing.JPanel; -import java.awt.Component; -import java.lang.reflect.Constructor; -import java.util.Map; -import java.util.TreeMap; - -import static org.nuiton.i18n.I18n.n; - -/** - * Manager des ecrans d'editions - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ContentUIManager { - - public static final String REFERENCE = "reference"; - - public static final String DATA = "data"; - - /** Logger */ - static private final Log log = LogFactory.getLog(ContentUIManager.class); - -// /** L'ui qui utilise le manager */ -// protected final ObserveMainUI ui; - - protected final Map<String, Class<? extends ObserveContentUI<?>>> mapping; - - protected ObserveMainUI getMainUI() { - return ObserveSwingApplicationContext.get().getMainUI(); - } - - public ContentUIManager() { - -// this.ui = ui; - mapping = new TreeMap<>(); - - // --- Seine data --- // - addMapping(DATA, ProgramDto.class, GearType.seine.name(), TripSeinesUI.class); - - addMapping(DATA, TripSeineDto.class, TripSeineUI.class); - addMapping(DATA, TripSeineDto.class, n("observe.tree.tripSeine.unsaved"), TripSeineUI.class); - addMapping(DATA, TripSeineDto.class, "gearUseFeaturesSeine", GearUseFeaturesSeineUI.class); - addMapping(DATA, TripSeineDto.class, TripSeineDto.PROPERTY_ROUTE, RoutesUI.class); - - addMapping(DATA, RouteDto.class, RouteUI.class); - addMapping(DATA, RouteDto.class, n("observe.tree.route.unsaved"), RouteUI.class); - addMapping(DATA, RouteDto.class, RouteDto.PROPERTY_ACTIVITY_SEINE, ActivitySeinesUI.class); - - addMapping(DATA, ActivitySeineDto.class, ActivitySeineUI.class); - addMapping(DATA, ActivitySeineDto.class, n("observe.tree.activitySeine.unsaved"), ActivitySeineUI.class); - addMapping(DATA, ActivitySeineDto.class, ActivitySeineObservedSystemDto.PROPERTY_OBSERVED_SYSTEM, ActivitySeineObservedSystemUI.class); - - addMapping(DATA, SetSeineDto.class, SetSeineUI.class); - addMapping(DATA, SetSeineDto.class, n("observe.tree.setSeine.unsaved"), SetSeineUI.class); - addMapping(DATA, SetSeineDto.class, SetSeineSchoolEstimateDto.PROPERTY_SCHOOL_ESTIMATE, SchoolEstimateUI.class); - addMapping(DATA, SetSeineDto.class, SetSeineTargetCatchDto.PROPERTY_TARGET_CATCH, TargetCatchUI.class); - addMapping(DATA, SetSeineDto.class, SetSeineDto.PROPERTY_TARGET_DISCARDED, TargetDiscardCatchUI.class); - addMapping(DATA, SetSeineDto.class, SetSeineDto.PROPERTY_TARGET_SAMPLE_CAPTURE, TargetSampleCaptureUI.class); - addMapping(DATA, SetSeineDto.class, SetSeineNonTargetCatchDto.PROPERTY_NON_TARGET_CATCH, NonTargetCatchUI.class); - - addMapping(DATA, SetSeineDto.class, "targetSample", TargetSampleRejeteUI.class); - addMapping(DATA, SetSeineDto.class, "nonTargetSample", NonTargetSampleUI.class); - - addMapping(DATA, FloatingObjectDto.class, FloatingObjectUI.class); - addMapping(DATA, FloatingObjectDto.class, n("observe.tree.floatingObject.unsaved"), FloatingObjectUI.class); - addMapping(DATA, FloatingObjectDto.class, FloatingObjectDto.PROPERTY_OBJECT_OPERATION, FloatingObjectTransmittingBuoyOperationUI.class); - addMapping(DATA, FloatingObjectDto.class, FloatingObjectObservedSpeciesDto.PROPERTY_OBJECT_OBSERVED_SPECIES, ObjectObservedSpeciesUI.class); - addMapping(DATA, FloatingObjectDto.class, FloatingObjectSchoolEstimateDto.PROPERTY_OBJECT_SCHOOL_ESTIMATE, ObjectSchoolEstimateUI.class); - - // --- Longline data --- // - - addMapping(DATA, ProgramDto.class, GearType.longline.name(), TripLonglinesUI.class); - - addMapping(DATA, TripLonglineDto.class, TripLonglineUI.class); - addMapping(DATA, TripLonglineDto.class, n("observe.tree.tripLongline.unsaved"), TripLonglineUI.class); - addMapping(DATA, TripLonglineDto.class, "gearUseFeaturesLongline", GearUseFeaturesLonglineUI.class); - addMapping(DATA, TripLonglineDto.class, TripLonglineDto.PROPERTY_ACTIVITY_LONGLINE, ActivityLonglinesUI.class); - - addMapping(DATA, ActivityLonglineDto.class, ActivityLonglineUI.class); - addMapping(DATA, ActivityLonglineDto.class, n("observe.tree.activityLongline.unsaved"), ActivityLonglineUI.class); - addMapping(DATA, ActivityLonglineDto.class, ActivityLonglineEncounterDto.PROPERTY_ENCOUNTER, EncounterUI.class); - addMapping(DATA, ActivityLonglineDto.class, ActivityLonglineSensorUsedDto.PROPERTY_SENSOR_USED, SensorUsedUI.class); - - addMapping(DATA, SetLonglineDto.class, SetLonglineUI.class); - addMapping(DATA, SetLonglineDto.class, n("observe.tree.setLongline.unsaved"), SetLonglineUI.class); - addMapping(DATA, SetLonglineDto.class, "longlineGlobalComposition", LonglineGlobalCompositionUI.class); - addMapping(DATA, SetLonglineDto.class, "longlineDetailComposition", LonglineDetailCompositionUI.class); - - addMapping(DATA, SetLonglineDto.class, SetLonglineCatchDto.PROPERTY_CATCH_LONGLINE, CatchLonglineUI.class); - addMapping(DATA, SetLonglineDto.class, SetLonglineTdrDto.PROPERTY_TDR, TdrUI.class); - - // --- Referential --- // - - for (Class<? extends ReferentialDto> editType : ReferentialDtos.REFERENCE_COMMON_DTOS) { - String simpleName = StringUtils.removeEnd(editType.getSimpleName(), "Dto"); - String fqn = ContentReferenceUI.class.getPackage().getName() + ".impl." + simpleName + "UI"; - Class<?> result; - try { - result = Class.forName(fqn); - addMapping(REFERENCE, editType, null, result); - } catch (ClassNotFoundException e) { - throw new IllegalStateException("Could not find " + fqn); - } - } - - for (Class<? extends ReferentialDto> editType : ReferentialDtos.REFERENCE_SEINE_DTOS) { - String simpleName = StringUtils.removeEnd(editType.getSimpleName(), "Dto"); - String fqn = ContentReferenceUI.class.getPackage().getName() + ".impl.seine." + simpleName + "UI"; - Class<?> result; - try { - result = Class.forName(fqn); - addMapping(REFERENCE, editType, null, result); - } catch (ClassNotFoundException e) { - throw new IllegalStateException("Could not find " + fqn); - } - } - - for (Class<? extends ReferentialDto> editType : ReferentialDtos.REFERENCE_LONGLINE_DTOS) { - String simpleName = StringUtils.removeEnd(editType.getSimpleName(), "Dto"); - String fqn = ContentReferenceUI.class.getPackage().getName() + ".impl.longline." + simpleName + "UI"; - Class<?> result; - try { - result = Class.forName(fqn); - addMapping(REFERENCE, editType, null, result); - } catch (ClassNotFoundException e) { - throw new IllegalStateException("Could not find " + fqn); - } - } - - addMapping(REFERENCE, null, ReferenceHomeUI.class); - - } - - public Class<? extends ObserveContentUI<?>> convertNodeToContentUI(ObserveNode node) { - if (log.isDebugEnabled()) { - log.debug("Entrer for node = " + node); - } - if (node.isRoot()) { - return null; - } - - Class<?> editType = node.getInternalClass(); - String prefix = node.isReferentielNode() ? REFERENCE : DATA; - String context = node.getContext(); - - String mappingKey; - - if (node.isReferentielNode()) { - - if (String.class.equals(editType)) { - editType = null; - } - - } else { - - // noeud de donnee - if (String.class.equals(editType)) { - editType = node.getContainerNode().getInternalClass(); - } - } - - mappingKey = getMappingKey(prefix, editType, context); - if (mappingKey == null) { - throw new NullPointerException("Could not find mappingKey for node " + node); - } - if (log.isDebugEnabled()) { - log.debug("mappingKey = [" + mappingKey + "] for node " + node); - } - Class<? extends ObserveContentUI<?>> result = mapping.get(mappingKey); - - return result; - } - - @SuppressWarnings({"unchecked"}) - public <U extends ObserveContentUI<?>> U getContent(Class<U> uiClass) { - - CardLayout2 layout = getLayout(); - JPanel layoutContent = getLayoutContent(); - String constraints = uiClass.getName(); - - if (!layout.contains(constraints)) { - - // pas trouvé - return null; - } - - U content = (U) layout.getComponent(layoutContent, constraints); - - if (log.isDebugEnabled()) { - log.debug("Will use existing content [" + constraints + "] : " + content.getClass().getName()); - } - return content; - } - - public <U extends ObserveContentUI<?>> U createContent(Class<U> uiClass) { - - String constraints = uiClass.getName(); - - if (getLayout().contains(constraints)) { - throw new IllegalStateException("Already existing constrainst [" + constraints + "]"); - } - U result; - try { - Constructor<U> constructor = uiClass.getConstructor(JAXXContext.class); - if (log.isDebugEnabled()) { - log.debug("create new content : " + uiClass); - } - result = constructor.newInstance(new JAXXInitialContext().add(getMainUI())); - } catch (Exception e) { - throw new IllegalStateException("Could not create content ui " + uiClass, e); - } - - try { - - // ajout du content dans son parent - getLayoutContent().add((JComponent) result, constraints); - - if (log.isDebugEnabled()) { - log.debug("Add new content [" + constraints + "] : " + result.getClass().getName()); - } - - // initialisation du content - result.init(); - - return result; - } catch (Exception e) { - throw new IllegalStateException("Could not init content ui " + uiClass, e); - } - } - - public ObserveContentUI<?> getCurrentContent() { - ObserveContentUI<?> component = (ObserveContentUI<?>) - getLayout().getVisibleComponent(getLayoutContent()); - return component; - } - - public void openContent(ObserveContentUI<?> content) { - - String constraints = content.getClass().getName(); - - if (log.isDebugEnabled()) { - log.debug("Will open ui [" + constraints + "] : " + content.getClass()); - } - - // on ouvre l'ui - try { - content.open(); - - } catch (Exception e) { - UIHelper.handlingError(e); - } finally { - - // on affiche l'ui quoi qu'il arrive ? - getLayout().show(getLayoutContent(), constraints); - } - } - - public void close() { - getLayout().reset(getLayoutContent()); - } - - public ContentUI<?> getSelectedContentUI() { - - ObserveMainUI ui = getMainUI(); - return getSelectedContentUI(ui); - } - - public boolean closeSelectedContentUI() { - ObserveMainUI ui = getMainUI(); - return closeSelectedContentUI(ui); - } - - public ContentUI<?> getSelectedContentUI(ObserveMainUI ui) { - - ContentUI<?> result = null; - - if (ui == null) { - // no ui, so no modification - return result; - } - - CardLayout2 layout = ui.getContentLayout(); - JPanel container = ui.getContent(); - Component currentContent = layout.getVisibleComponent(container); - if (currentContent != null && - currentContent instanceof ContentUI<?>) { - - result = (ContentUI<?>) currentContent; - } - return result; - } - - /** - * Essaye de fermer l'écran d'édition s'il existe. - * - * @param mainUI l'ui principale - * @return {@code true} si le contenu a bien été fermé, {@code false} si on - * ne peut pas fermer l'écran - * @since 1.5 - */ - public boolean closeSelectedContentUI(ObserveMainUI mainUI) { - ContentUI<?> ui = getSelectedContentUI(mainUI); - if (ui == null) { - // no content ui - return true; - } - boolean closed = false; - try { - closed = ui.close(); - } catch (Exception e) { - UIHelper.handlingError(e); - } - return closed; - } - - protected JPanel getLayoutContent() { - JPanel content = getMainUI().getContent(); - return content; - } - - protected CardLayout2 getLayout() { - CardLayout2 layout = getMainUI().getContentLayout(); - return layout; - } - - @Override - protected void finalize() throws Throwable { - super.finalize(); - close(); - } - - protected void addMapping(String prefix, Class<?> klass, Class<? extends ObserveContentUI<?>> contentClass) { - addMapping(prefix, klass, null, contentClass); - } - - @SuppressWarnings({"unchecked"}) - protected void addMapping(String prefix, Class<?> klass, String context, Class<?> contentClass) { - String key = getMappingKey(prefix, klass, context); - mapping.put(key, (Class<? extends ContentUI<?>>) contentClass); - } - - protected String getMappingKey(String prefix, Class<?> klass, String context) { - String key = prefix + "."; - if (klass != null) { - key += klass.getName(); - } - if (context != null) { - if (klass != null) { - key += "#"; - } - key += context; - } - return key; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ContentUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ContentUIModel.java deleted file mode 100644 index 0ea3c04..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ContentUIModel.java +++ /dev/null @@ -1,335 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content; - -import com.google.common.collect.ImmutableMap; -import fr.ird.observe.ObserveSwingTechnicalException; -import fr.ird.observe.services.dto.DataDto; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.DataReferenceSet; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.ReferentialReferenceSet; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.jdesktop.beans.AbstractSerializableBean; - -import java.util.Objects; -import java.util.Optional; -import java.util.Set; - -/** - * Le modèle d'un écran d'édition - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public abstract class ContentUIModel<E extends IdDto> extends AbstractSerializableBean { - - public static final String PROPERTY_EDIT_BEAN = "editBean"; - - public static final String PROPERTY_MODE = "mode"; - - public static final String PROPERTY_READING_MODE = "readingMode"; - - public static final String PROPERTY_CREATING_MODE = "creatingMode"; - - public static final String PROPERTY_UPDATING_MODE = "updatingMode"; - - public static final String PROPERTY_ENABLED = "enabled"; - - public static final String PROPERTY_MODIFIED = "modified"; - - public static final String PROPERTY_EDITING = "editing"; - - public static final String PROPERTY_EDITABLE = "editable"; - - public static final String PROPERTY_VALID = "valid"; - - public static final String PROPERTY_CAN_WRITE = "canWrite"; - - public static final String PROPERTY_FORM = "form"; - - /** Logger */ - static private final Log log = LogFactory.getLog(ContentUIModel.class); - - private static final long serialVersionUID = 1L; - - protected final Class<E> beanType; - - protected Form<E> form; - - protected E bean; - - protected ContentMode mode = ContentMode.READ; - - protected boolean enabled; - - protected boolean editing; - - protected boolean valid; - - protected boolean modified; - - protected boolean editable; - - protected boolean canWrite; - - /** - * Les référentiels qu'on peut utiliser, ils sont chargés depuis le cache des référentiels et peuvent être filtrés. - */ - protected ImmutableMap<String, ReferentialReferenceSet<?>> referentialReferenceSetsByPropertyName = ImmutableMap.of(); - - /** - * Les données métier qu'on peut utiliser. - */ - protected ImmutableMap<String, DataReferenceSet<?>> dataReferenceSetsByPropertyName = ImmutableMap.of(); - - public static <E extends IdDto> ContentUIModel<E> newModel(ObserveContentUI<E> ui) { - - String uiName = ui.getClass().getName(); - String modelName = uiName + "Model"; - - try { - - Class<ContentUIModel<E>> modelClass = (Class<ContentUIModel<E>>) Class.forName(modelName); - ContentUIModel<E> model = modelClass.newInstance(); - return model; - - } catch (Exception e) { - throw new ObserveSwingTechnicalException("Could not create model for ui: " + ui, e); - } - - } - - public ContentUIModel(Class<E> beanType) { - this.beanType = beanType; - try { - setBean(beanType.newInstance()); - - } catch (Exception e) { - // ne devrait jamain arrive - if (log.isErrorEnabled()) { - log.error(e); - } - } - - } - - public E getBean() { - return bean; - } - - public void setBean(E bean) { - Object oldValue = this.bean; - this.bean = bean; - firePropertyChange(PROPERTY_EDIT_BEAN, oldValue, bean); - } - - public Form<E> getForm() { - return form; - } - - public void setForm(Form<E> form) { - Object oldValue = getForm(); - this.form = form; - firePropertyChange(PROPERTY_FORM, oldValue, form); - } - - public ContentMode getMode() { - return mode; - } - - public void setMode(ContentMode mode) { - ContentMode oldValue = this.mode; - this.mode = mode; - firePropertyChange(PROPERTY_MODE, oldValue, mode); - firePropertyChange(PROPERTY_READING_MODE, ContentMode.READ.equals(oldValue), isReadingMode()); - firePropertyChange(PROPERTY_CREATING_MODE, ContentMode.CREATE.equals(oldValue), isCreatingMode()); - firePropertyChange(PROPERTY_UPDATING_MODE, ContentMode.UPDATE.equals(oldValue), isUpdatingMode()); - } - - /** - * @return {@code true} si l'écran est en mode creation - * @see ContentMode#CREATE - */ - public boolean isCreatingMode() { - return ContentMode.CREATE.equals(getMode()); - } - - /** - * @return {@code true} si l'écran est en mode mise a jour - * @see ContentMode#UPDATE - */ - public boolean isUpdatingMode() { - return ContentMode.UPDATE.equals(getMode()); - } - - /** - * @return {@code true} si l'écran est en mode lecture - * @see ContentMode#READ - */ - public boolean isReadingMode() { - return ContentMode.READ.equals(getMode()); - } - - public Class<E> getBeanType() { - return beanType; - } - - public boolean isEnabled() { - return enabled; - } - - public void setEnabled(boolean enabled) { - Object oldValue = this.enabled; - this.enabled = enabled; - firePropertyChange(PROPERTY_ENABLED, oldValue, enabled); - } - - public boolean isEditable() { - return editable; - } - - public void setEditable(boolean editable) { - Object oldValue = this.editable; - this.editable = editable; - firePropertyChange(PROPERTY_EDITABLE, oldValue, editable); - } - - public boolean isEditing() { - return editing; - } - - public void setEditing(boolean editing) { - Object oldValue = this.editing; - this.editing = editing; - firePropertyChange(PROPERTY_EDITING, oldValue, editing); - } - - public boolean isValid() { - return valid; - } - - public void setValid(boolean valid) { - Object oldValue = this.valid; - this.valid = valid; - firePropertyChange(PROPERTY_VALID, oldValue, valid); - } - - public boolean isModified() { - return modified; - } - - public void setModified(boolean modified) { - Object oldValue = this.modified; - this.modified = modified; - firePropertyChange(PROPERTY_MODIFIED, oldValue, modified); - } - - public boolean isCanWrite() { - return canWrite; - } - - public void setCanWrite(boolean canWrite) { - boolean oldValue = isCanWrite(); - this.canWrite = canWrite; - firePropertyChange(PROPERTY_CAN_WRITE, oldValue, canWrite); - } - - public <D extends ReferentialDto> Set<ReferentialReference<D>> getReferentialReferences(String name) { - - ReferentialReferenceSet<D> referentialReferenceSet = getReferentialReferenceSet(name); - Set<ReferentialReference<D>> references = referentialReferenceSet.getReferences(); - return references; - - } - - public <D extends DataDto> Set<DataReference<D>> getDataReferences(String name) { - - DataReferenceSet<D> referentialReferenceSet = getDataReferenceSet(name); - Set<DataReference<D>> references = referentialReferenceSet.getReferences(); - return references; - - } - - public <D extends ReferentialDto> Optional<ReferentialReference<D>> tryGetReferentialReferenceById(String name, String id) { - - ReferentialReferenceSet<D> referenceSet = getReferentialReferenceSet(name); - Optional<ReferentialReference<D>> optionalReference = referenceSet.tryGetReferenceById(id); - return optionalReference; - - } - - public void setReferentialReferenceSets(ImmutableMap<String, ReferentialReferenceSet<?>> referentialReferenceSetsByPropertyName) { - this.referentialReferenceSetsByPropertyName = referentialReferenceSetsByPropertyName; - } - - public void setDataReferenceSetsByPropertyName(ImmutableMap<String, DataReferenceSet<?>> dataReferenceSetsByPropertyName) { - this.dataReferenceSetsByPropertyName = dataReferenceSetsByPropertyName; - } - - public ImmutableMap<String, ReferentialReferenceSet<?>> getReferentialReferenceSets() { - return referentialReferenceSetsByPropertyName; - } - - public ImmutableMap<String, DataReferenceSet<?>> getDataReferenceSets() { - return dataReferenceSetsByPropertyName; - } - - protected <R extends DataDto> Optional<Set<DataReference<R>>> tryToGetDataReferenceSet(String propertyName) { - DataReferenceSet<R> referenceSet = getDataReferenceSet(propertyName); - Set<DataReference<R>> references = null; - if (referenceSet != null) { - references = referenceSet.getReferences(); - } - return Optional.ofNullable(references); - } - - protected <R extends ReferentialDto> Optional<Set<ReferentialReference<R>>> tryToGetReferentialReferenceSet(String propertyName) { - ReferentialReferenceSet<R> referenceSet = getReferentialReferenceSet(propertyName); - Set<ReferentialReference<R>> references = null; - if (referenceSet != null) { - references = referenceSet.getReferences(); - } - return Optional.ofNullable(references); - } - - protected void firePropertyChange(String propertyName, Object newValue) { - firePropertyChange(propertyName, null, newValue); - } - - private <R extends ReferentialDto> ReferentialReferenceSet<R> getReferentialReferenceSet(String propertyName) { - ImmutableMap<String, ReferentialReferenceSet<?>> referenceSet = this.referentialReferenceSetsByPropertyName; - Objects.requireNonNull(referenceSet, "Could not find referantialRefenceSet named " + propertyName); - return (ReferentialReferenceSet<R>) referenceSet.get(propertyName); - } - - public <R extends DataDto> DataReferenceSet<R> getDataReferenceSet(String propertyName) { - DataReferenceSet<?> referenceSet = dataReferenceSetsByPropertyName.get(propertyName); - Objects.requireNonNull(referenceSet, "Could not find dataReferenceSet named " + propertyName); - return (DataReferenceSet<R>) referenceSet; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ObserveContentUI.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ObserveContentUI.java deleted file mode 100644 index cd56aea..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ObserveContentUI.java +++ /dev/null @@ -1,81 +0,0 @@ -package fr.ird.observe.ui.content; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.IdDto; -import jaxx.runtime.JAXXObject; -import jaxx.runtime.swing.BlockingLayerUI; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; - -import javax.swing.Icon; -import javax.swing.JToolBar; - -/** - * Created on 10/5/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public interface ObserveContentUI<E extends IdDto> extends JAXXObject { - - String CLIENT_PROPERTY_FORCE_LOAD = "forceLoad"; - - String CLIENT_PROPERTY_LIST_NO_LOAD = "listNoLoad"; - - String CLIENT_PROPERTY_ENTITY_CLASS = "entityClass"; - - ContentUIModel<E> getModel(); - - DataContext getDataContext(); - - ObserveSwingDataSource getDataSource(); - - SwingValidatorMessageTableModel getErrorTableModel(); - - void setContentIcon(Icon icon); - - void init(); - - void open(); - - boolean close(); - - void stopEdit(); - - void startEdit(E bean); - - void restartEdit(); - - void resetEdit(); - - void save(boolean refresh); - - void delete(); - - JToolBar getTitleRightToolBar(); - - BlockingLayerUI getBlockLayerUI(); - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/BasketsTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/BasketsTableModel.java deleted file mode 100644 index bff777c..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/BasketsTableModel.java +++ /dev/null @@ -1,168 +0,0 @@ -package fr.ird.observe.ui.content.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.longline.SectionTemplate; -import fr.ird.observe.services.dto.longline.BasketDto; - -/** - * Created on 12/11/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.10 - */ -public class BasketsTableModel extends LonglineCompositionTableModelSupport<BasketDto> { - - private static final long serialVersionUID = 1L; - - public BasketsTableModel(LonglineDetailCompositionUIModel model) { - super(model); - } - - @Override - protected BasketDto createNewRow() { - return new BasketDto(); - } - - @Override - public int getColumnCount() { - return 4; - } - - @Override - public boolean isCellEditable(int rowIndex, int columnIndex) { - - boolean result; - - switch (columnIndex) { - - case 0: - - // can never edit setting id - result = false; - break; - - case 1: - - // can edit hauling id if and only if set has hauling breaks - result = !isGenerateHaulingIds(); - break; - - case 2: - - // can always change length ? - result = true; - break; - - case 3: - - // can always change length ? - result = true; - break; - - default: - throw new IllegalStateException("Can't come here"); - - } - - return result; - - } - - @Override - public Object getValueAt(int rowIndex, int columnIndex) { - - BasketDto row = data.get(rowIndex); - Object result; - - switch (columnIndex) { - case 0: - - result = row.getSettingIdentifier(); - break; - - case 1: - - result = row.getHaulingIdentifier(); - break; - - case 2: - - result = row.getFloatline1Length(); - break; - - case 3: - - result = row.getFloatline2Length(); - break; - - default: - throw new IllegalStateException("Can't come here"); - } - - return result; - - } - - @Override - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - - BasketDto row = data.get(rowIndex); - - switch (columnIndex) { - case 0: - - row.setSettingIdentifier((Integer) aValue); - break; - - case 1: - - row.setHaulingIdentifier((Integer) aValue); - break; - - case 2: - - row.setFloatline1Length((Float) aValue); - break; - - case 3: - - row.setFloatline2Length((Float) aValue); - break; - - default: - throw new IllegalStateException("Can't come here"); - } - - setModified(true); - - } - - public void applySectionTemplate(SectionTemplate newTemplate) { - - newTemplate.applyToBaskets(data); - fireTableRowsUpdated(0, getRowCount() - 1); - setModified(true); - - } -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/BranchlineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/BranchlineUI.jaxx deleted file mode 100644 index 9dd30c3..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/BranchlineUI.jaxx +++ /dev/null @@ -1,254 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ContentUI superGenericType='BranchlineDto' contentTitle='{n("observe.content.branchline.title")}'> - - <import> - fr.ird.observe.services.dto.CommentableDto - fr.ird.observe.services.dto.longline.BranchlineDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.longline.LineTypeDto - fr.ird.observe.services.dto.referential.longline.BaitTypeDto - fr.ird.observe.services.dto.referential.longline.BaitHaulingStatusDto - fr.ird.observe.services.dto.referential.longline.BaitSettingStatusDto - fr.ird.observe.services.dto.referential.longline.HookSizeDto - fr.ird.observe.services.dto.referential.longline.HookTypeDto - - fr.ird.observe.ui.actions.shared.ResetEditUIAction - fr.ird.observe.ui.actions.shared.SaveEditUIAction - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - org.nuiton.jaxx.widgets.datetime.DateTimeEditor - - org.apache.commons.lang3.BooleanUtils - - java.awt.Dimension - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <style source="../../Common.jcss"/> - - <!-- handler --> - <BranchlineUIHandler id='handler'/> - - <!-- model --> - <BranchlineUIModel id='model'/> - - <!-- edit bean --> - <BranchlineDto id='bean'/> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' context='ui-update' - beanClass='fr.ird.observe.services.dto.longline.BranchlineDto' - errorTableModel='{getErrorTableModel()}'> - </BeanValidator> - - - <script><![CDATA[ -public void edit(BranchlineDto branchline) { getHandler().edit(branchline); } - -]]> - </script> - - <!-- formulaire --> - <JPanel id="body" layout='{new BorderLayout()}'> - - <Table insets="0" fill="both" constraints='BorderLayout.CENTER'> - <row> - <cell anchor="north" weightx="1"> - <JTabbedPane id='fishingOperationTabPane'> - - <tab id='generalTab'> - <JPanel layout='{new BorderLayout()}'> - <Table fill="both" constraints='BorderLayout.CENTER'> - - <!-- topType --> - <row> - <cell anchor='west'> - <JLabel id='topTypeLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <BeanComboBox id='topType' constructorParams='this' genericType='ReferentialReference<LineTypeDto>' _entityClass='LineTypeDto.class'/> - </cell> - </row> - - <!-- tracelineType --> - <row> - <cell anchor='west'> - <JLabel id='tracelineTypeLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <BeanComboBox id='tracelineType' constructorParams='this' genericType='ReferentialReference<LineTypeDto>' _entityClass='LineTypeDto.class'/> - </cell> - </row> - - <!-- depthRecorder --> - <!-- hookLost --> - <!-- traceCutOff --> - <row> - <cell columns="3"> - <JPanel layout="{new GridLayout()}"> - <JCheckBox id='depthRecorder'/> - <JCheckBox id='hookLost'/> - <JCheckBox id='traceCutOff'/> - </JPanel> - </cell> - </row> - - <!-- timer --> - <!-- timeSinceContact --> - <row> - <cell anchor='east'> - <JCheckBox id='timer'/> - </cell> - <cell> - <JLabel id='timeSinceContactLabel'/> - </cell> - <cell> - <NumberEditor id='timeSinceContact' constructorParams='this'/> - </cell> - </row> - - <!-- timerTimeOnBoard --> - <row> - <cell columns="3"> - <DateTimeEditor id='timerTimeOnBoard' constructorParams='this'/> - </cell> - </row> - - <!-- weighted snaps --> - <!-- snap weights --> - <row> - <cell anchor='east'> - <JCheckBox id='weightedSnap'/> - </cell> - <cell> - <JLabel id='snapWeightLabel'/> - </cell> - <cell> - <NumberEditor id='snapWeight' constructorParams='this'/> - </cell> - </row> - - <!-- weighted swivels --> - <!-- swivels weights --> - <row> - <cell anchor="east"> - <JCheckBox id='weightedSwivel'/> - </cell> - <cell anchor="west"> - <JLabel id='swivelWeightLabel'/> - </cell> - <cell> - <NumberEditor id='swivelWeight' constructorParams='this'/> - </cell> - </row> - - </Table> - </JPanel> - </tab> - - <tab id='hookAndBaitTab'> - <JPanel layout='{new BorderLayout()}'> - <Table fill="both" constraints='BorderLayout.CENTER'> - - <!-- HookType --> - <row> - <cell anchor='west'> - <JLabel id='hookTypeLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <BeanComboBox id='hookType' constructorParams='this' genericType='ReferentialReference<HookTypeDto>' _entityClass='HookTypeDto.class'/> - </cell> - </row> - - <!-- HookSize --> - <row> - <cell anchor='west'> - <JLabel id='hookSizeLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <BeanComboBox id='hookSize' constructorParams='this' genericType='ReferentialReference<HookSizeDto>' _entityClass='HookSizeDto.class'/> - </cell> - </row> - - <!-- hookOffset --> - <row> - <cell anchor='west'> - <JLabel id='hookOffsetLabel'/> - </cell> - <cell columns="2" weightx="1" fill="both"> - <NumberEditor id='hookOffset' constructorParams='this'/> - </cell> - </row> - - <!-- baitType --> - <row> - <cell anchor='west'> - <JLabel id='baitTypeLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <BeanComboBox id='baitType' constructorParams='this' genericType='ReferentialReference<BaitTypeDto>' _entityClass='BaitTypeDto.class'/> - </cell> - </row> - - <!-- baitSettingStatus --> - <row> - <cell anchor='west'> - <JLabel id='baitSettingStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <BeanComboBox id='baitSettingStatus' constructorParams='this' genericType='ReferentialReference<BaitSettingStatusDto>' _entityClass='BaitSettingStatusDto.class'/> - </cell> - </row> - - <!-- baitHaulingStatus --> - <row> - <cell anchor='west'> - <JLabel id='baitHaulingStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <BeanComboBox id='baitHaulingStatus' constructorParams='this' genericType='ReferentialReference<BaitHaulingStatusDto>' _entityClass='BaitHaulingStatusDto.class'/> - </cell> - </row> - - </Table> - </JPanel> - </tab> - </JTabbedPane> - </cell> - </row> - <row> - <cell weighty="1"> - <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2'/> - </JScrollPane> - </cell> - </row> - </Table> - - </JPanel> - -</fr.ird.observe.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/BranchlineUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/BranchlineUI.jcss deleted file mode 100644 index 084f82e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/BranchlineUI.jcss +++ /dev/null @@ -1,245 +0,0 @@ - /* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#model { - editable:true; - modified:{validator.isChanged()}; - valid:{validator.isValid()}; - enabled:{!model.isReadingMode()}; -} - - -#comment { - columnHeaderView:{new JLabel(t("observe.content.branchline.comment"))}; -} - -#comment2 { - _tablePropertyName: {BranchlineDto.PROPERTY_COMMENT}; - text:{getStringValue(bean.getComment())}; -} - -/* ***************************************************************************** */ -/* GENERAL TAB **************************************************************** */ -/* ***************************************************************************** */ - -#generalTab { - title:{t("observe.content.branchline.tab.general")}; - icon:{getHandler().getErrorIconIfFalse(model.isGeneralTabValid())}; -} - -#depthRecorder { - horizontalTextPosition:{JCheckBox.LEFT}; - text:"observe.content.branchline.depthRecorder"; - _propertyName:{BranchlineDto.PROPERTY_DEPTH_RECORDER}; - selected:{BooleanUtils.isTrue(bean.getDepthRecorder())}; - _validatorLabel:{t("observe.content.branchline.depthRecorder")}; -} - -#hookLost { - horizontalTextPosition:{JCheckBox.LEFT}; - text:"observe.content.branchline.hookLost"; - _propertyName:{BranchlineDto.PROPERTY_HOOK_LOST}; - selected:{BooleanUtils.isTrue(bean.getHookLost())}; - _validatorLabel:{t("observe.content.branchline.hookLost")}; -} - -#traceCutOff { - horizontalTextPosition:{JCheckBox.LEFT}; - text:"observe.content.branchline.traceCutOff"; - _propertyName:{BranchlineDto.PROPERTY_TRACE_CUT_OFF}; - selected:{BooleanUtils.isTrue(bean.getTraceCutOff())}; - _validatorLabel:{t("observe.content.branchline.traceCutOff")}; -} - -#timer { - text:"observe.content.branchline.timer"; - horizontalTextPosition:{JCheckBox.LEFT}; - _propertyName:{BranchlineDto.PROPERTY_TIMER}; - selected:{BooleanUtils.isTrue(bean.getTimer())}; - _validatorLabel:{t("observe.content.branchline.timer")}; -} - -#timeSinceContactLabel { - text:"observe.content.branchline.timeSinceContact"; - labelFor:{timeSinceContact}; -} - -#timeSinceContact { - enabled:{BooleanUtils.isTrue(bean.getTimer())}; - property:{BranchlineDto.PROPERTY_TIME_SINCE_CONTACT}; - model:{bean.getTimeSinceContact()}; - numberPattern:{fr.ird.observe.ui.UIHelper.LONG_10_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.branchline.timeSinceContact")}; -} - -#timerTimeOnBoardLabel { - text:"observe.content.branchline.timerTimeOnBoard"; - labelFor:{timerTimeOnBoard}; -} - -#timerTimeOnBoard { - enabled:{BooleanUtils.isTrue(bean.getTimer())}; - label:{t("observe.content.branchline.timerTimeOnBoard")}; - date:{bean.getTimerTimeOnBoard()}; - propertyDate: {BranchlineDto.PROPERTY_TIMER_TIME_ON_BOARD}; - _validatorLabel:{t("observe.content.branchline.timerTimeOnBoard")}; -} - -#topTypeLabel { - text:"observe.content.branchline.topType"; - labelFor:{topType}; -} - -#topType { - property:{BranchlineDto.PROPERTY_TOP_TYPE}; - selectedItem:{bean.getTopType()}; - _validatorLabel:{t("observe.content.branchline.topType")}; -} - -#tracelineTypeLabel { - text:"observe.content.branchline.tracelineType"; - labelFor:{tracelineType}; -} - -#tracelineType { - property:{BranchlineDto.PROPERTY_TRACELINE_TYPE}; - selectedItem:{bean.getTracelineType()}; - _validatorLabel:{t("observe.content.branchline.tracelineType")}; -} - -#weightedSwivel { - horizontalTextPosition:{JCheckBox.LEFT}; - text:"observe.content.branchline.weightedSwivel"; - _propertyName:{BranchlineDto.PROPERTY_WEIGHTED_SWIVEL}; - selected:{BooleanUtils.isTrue(bean.getWeightedSwivel())}; - _validatorLabel:{t("observe.content.branchline.weightedSwivel")}; -} - -#swivelWeightLabel { - text:"observe.content.branchline.swivelWeight"; - labelFor:{swivelWeight}; -} - -#swivelWeight { - enabled:{BooleanUtils.isTrue(bean.getWeightedSwivel())}; - property:{BranchlineDto.PROPERTY_SWIVEL_WEIGHT}; - model:{bean.getSwivelWeight()}; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL3_PATTERN}; - _validatorLabel:{t("observe.content.branchline.swivelWeight")}; -} - -#weightedSnap { - horizontalTextPosition:{JCheckBox.LEFT}; - text:"observe.content.branchline.weightedSnap"; - _propertyName:{BranchlineDto.PROPERTY_WEIGHTED_SNAP}; - selected:{BooleanUtils.isTrue(bean.getWeightedSnap())}; - _validatorLabel:{t("observe.content.branchline.weightedSnap")}; -} - -#snapWeightLabel { - text:"observe.content.branchline.snapWeight"; - labelFor:{snapWeight}; -} - -#snapWeight { - enabled:{BooleanUtils.isTrue(bean.getWeightedSnap())}; - property:{BranchlineDto.PROPERTY_SNAP_WEIGHT}; - model:{bean.getSnapWeight()}; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL3_PATTERN}; - _validatorLabel:{t("observe.content.branchline.snapWeight")}; -} - -/* ***************************************************************************** */ -/* HOOK AND BAIT TAB ********************************************************** */ -/* ***************************************************************************** */ - -#hookAndBaitTab { - title:{t("observe.content.branchline.tab.hookAndBait")}; - icon:{getHandler().getErrorIconIfFalse(model.isHookAndBaitTabValid())}; -} - -#hookTypeLabel { - text:"observe.content.branchline.hookType"; - labelFor:{hookType}; -} - -#hookType { - property:{BranchlineDto.PROPERTY_HOOK_TYPE}; - selectedItem:{bean.getHookType()}; - _validatorLabel:{t("observe.content.branchline.hookType")}; -} - -#hookSizeLabel { - text:"observe.content.branchline.hookSize"; - labelFor:{hookSize}; -} - -#hookSize { - property:{BranchlineDto.PROPERTY_HOOK_SIZE}; - selectedItem:{bean.getHookSize()}; - _validatorLabel:{t("observe.content.branchline.hookSize")}; -} - -#hookOffsetLabel { - text:"observe.content.branchline.hookOffset"; - labelFor:{hookOffset}; -} - -#hookOffset { - property:{BranchlineDto.PROPERTY_HOOK_OFFSET}; - model:{bean.getHookOffset()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.branchline.hookOffset")}; -} - -#baitSettingStatusLabel { - text:"observe.content.branchline.baitSettingStatus"; - labelFor:{baitSettingStatus}; -} - -#baitSettingStatus { - property:{BranchlineDto.PROPERTY_BAIT_SETTING_STATUS}; - selectedItem:{bean.getBaitSettingStatus()}; - _validatorLabel:{t("observe.content.branchline.baitSettingStatus")}; -} - -#baitHaulingStatusLabel { - text:"observe.content.branchline.baitHaulingStatus"; - labelFor:{baitHaulingStatus}; -} - -#baitHaulingStatus { - property:{BranchlineDto.PROPERTY_BAIT_HAULING_STATUS}; - selectedItem:{bean.getBaitHaulingStatus()}; - _validatorLabel:{t("observe.content.branchline.baitHaulingStatus")}; -} - -#baitTypeLabel { - text:"observe.content.branchline.baitType"; - labelFor:{baitType}; -} - -#baitType { - property:{BranchlineDto.PROPERTY_BAIT_TYPE}; - selectedItem:{bean.getBaitType()}; - _validatorLabel:{t("observe.content.branchline.baitType")}; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/BranchlineUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/BranchlineUIHandler.java deleted file mode 100644 index 5332563..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/BranchlineUIHandler.java +++ /dev/null @@ -1,354 +0,0 @@ -package fr.ird.observe.ui.content.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.longline.BranchlineDto; -import fr.ird.observe.services.dto.longline.BranchlineDtos; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.ContentUIHandler; -import fr.ird.observe.ui.content.ContentUIModel; -import jaxx.runtime.validator.swing.SwingValidatorMessage; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.decorator.Decorator; -import org.nuiton.i18n.I18n; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.JOptionPane; -import javax.swing.event.TableModelListener; -import java.util.HashSet; -import java.util.Set; - -/** - * Created on 12/22/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.10 - */ -public class BranchlineUIHandler extends ContentUIHandler<BranchlineDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(BranchlineUIHandler.class); - - // Compute valid state of tab from the error table - protected final TableModelListener computeTabValidStateListener; - - private Decorator<BranchlineDto> branchlineDecorator; - - public BranchlineUIHandler(BranchlineUI ui) { - super(ui, DataContextType.SetLongline, null); - computeTabValidStateListener = e -> { - - SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); - computeTabValidState(source); - - }; - } - - public void edit(BranchlineDto branchline) { - - if (log.isInfoEnabled()) { - log.info("Will edit branchline: " + branchlineDecorator.toString(branchline)); - } - - getModel().setBranchline(branchline); - BranchlineDtos.copyBranchlineDto(branchline, getBean()); - - if (branchline == null) { - - // stop edit - stopEditUI(); - - } else { - - if (getModel().isEnabled() && !getModel().isEditing()) { - - startEditUI(); - - } - } - - // To be sure always remove listener (could prevent some leaks) - getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); - // listen messages to see if required to add - getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); - - SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); - computeTabValidState(errorTableModel); - - getModel().setModified(false); - - } - - @Override - public BranchlineUIModel getModel() { - return (BranchlineUIModel) super.getModel(); - } - - @Override - public BranchlineUI getUi() { - return (BranchlineUI) super.getUi(); - } - - @Override - protected boolean computeCanWrite(ObserveSwingDataSource source) { - return source.canWriteData(); - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - ContentMode contentMode; - - if (getOpenDataManager().isOpenActivityLongline(dataContext.getSelectedActivityLonglineId())) { - - // l'activité est ouverte, mode édition - contentMode = ContentMode.UPDATE; - - } else { - - contentMode = ContentMode.READ; - - } - - return contentMode; - - } - - @Override - public void initUI() { - - branchlineDecorator = getDecoratorService().getDecoratorByType(BranchlineDto.class); - super.initUI(); - - } - - @Override - public void openUI() { - - if (log.isInfoEnabled()) { - log.info("OpenUI: " + getModel()); - } - - boolean canWrite = computeCanWrite(getDataSource()); - - getModel().setCanWrite(canWrite); - - updateActions(); - - ContentMode mode = computeContentMode(); - - // utilisation du mode requis - setContentMode(mode); - - // when opening screen do not edit incoming bean - edit(null); - - if (mode != ContentMode.READ) { - ui.startEdit(null); - } - - } - - @Override - public void startEditUI(String... binding) { - - ContentUIModel<BranchlineDto> model = getModel(); - - super.startEditUI(BranchlineUI.BINDING_COMMENT2_TEXT, - - BranchlineUI.BINDING_TOP_TYPE_SELECTED_ITEM, - BranchlineUI.BINDING_TRACELINE_TYPE_SELECTED_ITEM, - - BranchlineUI.BINDING_DEPTH_RECORDER_SELECTED, - BranchlineUI.BINDING_HOOK_LOST_SELECTED, - BranchlineUI.BINDING_TRACE_CUT_OFF_SELECTED, - - BranchlineUI.BINDING_WEIGHTED_SWIVEL_SELECTED, - BranchlineUI.BINDING_SWIVEL_WEIGHT_MODEL, - BranchlineUI.BINDING_WEIGHTED_SNAP_SELECTED, - BranchlineUI.BINDING_SNAP_WEIGHT_MODEL, - - BranchlineUI.BINDING_BAIT_TYPE_SELECTED_ITEM, - BranchlineUI.BINDING_BAIT_SETTING_STATUS_SELECTED_ITEM, - BranchlineUI.BINDING_BAIT_HAULING_STATUS_SELECTED_ITEM, - - BranchlineUI.BINDING_HOOK_TYPE_SELECTED_ITEM, - BranchlineUI.BINDING_HOOK_SIZE_SELECTED_ITEM, - BranchlineUI.BINDING_HOOK_OFFSET_MODEL, - - BranchlineUI.BINDING_TIMER_SELECTED, - BranchlineUI.BINDING_TIME_SINCE_CONTACT_MODEL, - BranchlineUI.BINDING_TIMER_TIME_ON_BOARD_DATE - ); - - model.setModified(false); - - } - - @Override - protected boolean doSave(BranchlineDto bean) throws Exception { - - // bind back to model branchline - BranchlineDto beanToSave = getModel().getBranchline(); - BranchlineDtos.copyBranchlineDto(bean, beanToSave); - - // for external models - getModel().fireSaved(); - - return true; - - } - - @Override - public void resetEditUI() { - - BranchlineDto branchline = getModel().getBranchline(); - - // on arrete l'edition - stopEditUI(); - - // on re-ouvre l'écran d'édition - try { - openUI(); - } catch (Exception ex) { - UIHelper.handlingError(ex); - stopEditUI(); - } - - edit(branchline); - - } - - public boolean tryToQuit() { - - boolean canContinue; - - if (getModel().isEditing() && getModel().isModified()) { - - canContinue = false; - - if (getModel().isValid()) { - - // le formulaire est valide, on demande a l'utilisateur s'il - // veut la sauvegarder - - int reponse = UIHelper.askUser( - I18n.t("observe.title.need.confirm"), - I18n.t("observe.content.branchline.message.modified"), - JOptionPane.WARNING_MESSAGE, - new Object[]{ - I18n.t("observe.choice.save"), - I18n.t("observe.choice.doNotSave"), - I18n.t("observe.choice.cancel")}, - 0); - if (log.isDebugEnabled()) { - log.debug("response : " + reponse); - } - - switch (reponse) { - case JOptionPane.CLOSED_OPTION: - case 2: - - break; - case 0: - // will save ui - // sauvegarde des modifications - saveUI(false); - canContinue = true; - break; - case 1: - - // reset edit - resetEditUI(); - canContinue = true; - - break; - } - - } else { - - // le formulaire n'est pas valide, on ne peut que proposer la perte - // des donnees car elles sont ne pas enregistrables - - int reponse = UIHelper.askUser( - I18n.t("observe.title.need.confirm"), - I18n.t("observe.content.branchline.message.modified.but.invalid"), - JOptionPane.ERROR_MESSAGE, - new Object[]{ - I18n.t("observe.choice.continue"), - I18n.t("observe.choice.cancel")}, - 0); - if (log.isDebugEnabled()) { - log.debug("response : " + reponse); - } - switch (reponse) { - case 0: - - // reset edit - resetEditUI(); - canContinue = true; - - break; - } - - } - - } else { - - // pas en mode edition ou formulaire non modifié - // on peut toujours quitter - canContinue = true; - - } - - return canContinue; - - } - - protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { - - Set<String> errorProperties = new HashSet<>(); - int rowCount = errorTableModel.getRowCount(); - for (int i = 0; i < rowCount; i++) { - - SwingValidatorMessage row = errorTableModel.getRow(i); - if (NuitonValidatorScope.ERROR.equals(row.getScope())) { - errorProperties.add(row.getField()); - } - } - - boolean generalTabValid = !errorProperties.removeAll(BranchlineUIModel.GENERAL_TAB_PROPERTIES); - boolean hookAndBaitTabValid = !errorProperties.removeAll(BranchlineUIModel.HOOK_AND_BAIT_TAB_PROPERTIES); - - BranchlineUIModel model = getModel(); - model.setGeneralTabValid(generalTabValid); - model.setHookAndBaitTabValid(hookAndBaitTabValid); - - } -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/BranchlineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/BranchlineUIModel.java deleted file mode 100644 index 50e857e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/BranchlineUIModel.java +++ /dev/null @@ -1,110 +0,0 @@ -package fr.ird.observe.ui.content.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.ImmutableSet; -import fr.ird.observe.services.dto.longline.BranchlineDto; -import fr.ird.observe.ui.content.ContentUIModel; - -import java.util.Set; - -/** - * Created on 12/22/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.10 - */ -public class BranchlineUIModel extends ContentUIModel<BranchlineDto> { - - public static final String PROPERTY_SAVED = "saved"; - - private static final long serialVersionUID = 1L; - - public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; - - public static final String PROPERTY_HOOK_AND_BAIT_TAB_VALID = "hookAndBaitTabValid"; - - public static final Set<String> GENERAL_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(BranchlineDto.PROPERTY_TOP_TYPE, - BranchlineDto.PROPERTY_TRACELINE_TYPE, - BranchlineDto.PROPERTY_DEPTH_RECORDER, - BranchlineDto.PROPERTY_HOOK_LOST, - BranchlineDto.PROPERTY_TRACE_CUT_OFF, - BranchlineDto.PROPERTY_TIMER, - BranchlineDto.PROPERTY_TIME_SINCE_CONTACT, - BranchlineDto.PROPERTY_TIMER_TIME_ON_BOARD, - BranchlineDto.PROPERTY_WEIGHTED_SNAP, - BranchlineDto.PROPERTY_SNAP_WEIGHT, - BranchlineDto.PROPERTY_WEIGHTED_SWIVEL, - BranchlineDto.PROPERTY_SWIVEL_WEIGHT).build(); - - public static final Set<String> HOOK_AND_BAIT_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(BranchlineDto.PROPERTY_HOOK_TYPE, - BranchlineDto.PROPERTY_HOOK_SIZE, - BranchlineDto.PROPERTY_HOOK_OFFSET, - BranchlineDto.PROPERTY_BAIT_TYPE, - BranchlineDto.PROPERTY_BAIT_SETTING_STATUS, - BranchlineDto.PROPERTY_BAIT_HAULING_STATUS).build(); - - private BranchlineDto branchlineDto; - - private boolean generalTabValid; - - private boolean hookAndBaitTabValid; - - public BranchlineUIModel() { - super(BranchlineDto.class); - } - - public BranchlineDto getBranchline() { - return branchlineDto; - } - - public void setBranchline(BranchlineDto branchlineDto) { - this.branchlineDto = branchlineDto; - } - - public boolean isGeneralTabValid() { - return generalTabValid; - } - - public void setGeneralTabValid(boolean generalTabValid) { - this.generalTabValid = generalTabValid; - firePropertyChange(PROPERTY_GENERAL_TAB_VALID, null, generalTabValid); - } - - public boolean isHookAndBaitTabValid() { - return hookAndBaitTabValid; - } - - public void setHookAndBaitTabValid(boolean hookAndBaitTabValid) { - this.hookAndBaitTabValid = hookAndBaitTabValid; - firePropertyChange(PROPERTY_HOOK_AND_BAIT_TAB_VALID, null, hookAndBaitTabValid); - } - - // For external model known when a saved action was done - public void fireSaved() { - firePropertyChange(PROPERTY_SAVED, null, true); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/BranchlinesTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/BranchlinesTableModel.java deleted file mode 100644 index c7d9076..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/BranchlinesTableModel.java +++ /dev/null @@ -1,180 +0,0 @@ -package fr.ird.observe.ui.content.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.longline.BranchlineDto; - -import java.util.Date; - -/** - * Created on 12/11/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.10 - */ -public class BranchlinesTableModel extends LonglineCompositionTableModelSupport<BranchlineDto> { - - private static final long serialVersionUID = 1L; - - protected Date defaultDate; - - private boolean useTimer; - - public BranchlinesTableModel(LonglineDetailCompositionUIModel model) { - super(model); - } - - public void setDefaultDate(Date defaultDate) { - this.defaultDate = defaultDate; - } - - @Override - protected BranchlineDto createNewRow() { - - BranchlineDto branchline = new BranchlineDto(); - branchline.setTimerTimeOnBoard(defaultDate); - branchline.setTimer(useTimer); - return branchline; - - } - - @Override - public int getColumnCount() { - return 4; - } - - @Override - public boolean isCellEditable(int rowIndex, int columnIndex) { - - boolean result; - - switch (columnIndex) { - - case 0: - - // can never edit setting id - result = false; - break; - - case 1: - - // can edit hauling id if and only if set has hauling breaks - result = !isGenerateHaulingIds(); - break; - - case 2: - - result = true; - break; - - case 3: - - result = true; - break; - - default: - throw new IllegalStateException("Can't come here"); - - } - - return result; - - } - - @Override - public Object getValueAt(int rowIndex, int columnIndex) { - - BranchlineDto row = data.get(rowIndex); - Object result; - - switch (columnIndex) { - case 0: - - result = row.getSettingIdentifier(); - break; - - case 1: - - result = row.getHaulingIdentifier(); - break; - - case 2: - - result = row.getBranchlineLength(); - break; - - case 3: - - result = row.getTracelineLength(); - break; - - default: - throw new IllegalStateException("Can't come here"); - } - - return result; - - } - - @Override - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - - BranchlineDto row = data.get(rowIndex); - - switch (columnIndex) { - case 0: - - row.setSettingIdentifier((Integer) aValue); - break; - - case 1: - - row.setHaulingIdentifier((Integer) aValue); - break; - - case 2: - - row.setBranchlineLength((Float) aValue); - break; - - case 3: - - row.setTracelineLength((Float) aValue); - break; - - default: - throw new IllegalStateException("Can't come here"); - } - - setModified(true); - - } - - public void setUseTimer(boolean useTimer) { - this.useTimer = useTimer; - } - - public boolean isUseTimer() { - return useTimer; - } -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineCompositionTableModelSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineCompositionTableModelSupport.java deleted file mode 100644 index c081516..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineCompositionTableModelSupport.java +++ /dev/null @@ -1,215 +0,0 @@ -package fr.ird.observe.ui.content.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.AbstractObserveDto; -import fr.ird.observe.services.dto.longline.LonglineCompositionDto; -import fr.ird.observe.ui.util.table.EditableTableModelSupport; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.List; - -/** - * Created on 12/13/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.10 - */ -public abstract class LonglineCompositionTableModelSupport<E extends AbstractObserveDto & LonglineCompositionDto> extends EditableTableModelSupport<E> { - - /** Logger. */ - private static final Log log = LogFactory.getLog(LonglineCompositionTableModelSupport.class); - - private static final long serialVersionUID = 1L; - - private final LonglineDetailCompositionUIModel model; - - public LonglineCompositionTableModelSupport(LonglineDetailCompositionUIModel model) { - super(false); - this.model = model; - } - - @Override - protected final boolean isRowValid(E valid) { - // Not used here - return true; - } - - @Override - public final boolean isRowNotEmpty(E valid) { - // Not used here - return true; - } - - public void rearrangeIds(boolean fire) { - - rearrangeIds(data); - - if (fire && !isEmpty()) { - - fireTableRowsUpdated(0, getRowCount() - 1); - - } - - } - - public void rearrangeIds(List<E> data) { - - boolean generateHaulingIds = isGenerateHaulingIds(); - boolean haulingdirectionSameAsSettings = model.isHaulingdirectionSameAsSettings(); - - int dataSize = data.size(); - - if (log.isInfoEnabled()) { - log.info("Will rearrange ids for " + dataSize + " data on " + this); - log.info("generateHaulingIds ? " + generateHaulingIds); - log.info("haulingdirectionSameAsSettings ? " + haulingdirectionSameAsSettings); - } - - int index = 1; - - for (E e : data) { - - if (log.isInfoEnabled()) { - log.info("SettingIdentifier : " + index); - } - e.setSettingIdentifier(index); - - if (generateHaulingIds) { - - int haulingId; - - if (haulingdirectionSameAsSettings) { - haulingId = index; - } else { - haulingId = dataSize - index + 1; - } - - if (log.isInfoEnabled()) { - log.info("HaulingIdentifier : " + haulingId); - } - e.setHaulingIdentifier(haulingId); - - } - - index++; - - } - - } - - @Override - public void addNewRow() { - - super.addNewRow(); - - validate(); - setModified(true); - - } - - @Override - public void insertAfterSelectedRow() { - - super.insertAfterSelectedRow(); - - validate(); - setModified(true); - - } - - @Override - public void insertBeforeSelectedRow() { - - super.insertBeforeSelectedRow(); - - validate(); - setModified(true); - - } - - @Override - public void removeData(int selectedRow) { - - super.removeData(selectedRow); - - validate(); - setModified(true); - - } - - protected boolean isGenerateHaulingIds() { - return model.isGenerateHaulingIds(); - } - - protected boolean isCanGenerate() { - return model.isCanGenerate(); - } - - @Override - public void fireTableDataChanged() { - - // rearrange ids when data has changed - rearrangeIds(false); - - super.fireTableDataChanged(); - - } - - @Override - public void fireTableRowsDeleted(int firstRow, int lastRow) { - super.fireTableRowsDeleted(firstRow, lastRow); - - // must rearrange ids - rearrangeIds(true); - - } - - @Override - public void fireTableRowsInserted(int firstRow, int lastRow) { - super.fireTableRowsInserted(firstRow, lastRow); - - // must rearrange ids - rearrangeIds(true); - - } - - @Override - public void removeSelectedRow() { - - super.removeSelectedRow(); - validate(); - setModified(true); - - } - - - @Override - public void setData(List<E> data) { - - super.setData(data); - validate(); - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionUI.jaxx deleted file mode 100644 index 499640d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionUI.jaxx +++ /dev/null @@ -1,205 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ContentUI superGenericType='SetLonglineDetailCompositionDto' - contentTitle='{n("observe.content.longlineDetailComposition.title")}'> - - <import> - fr.ird.observe.ObserveSwingApplicationContext - fr.ird.observe.services.dto.longline.SetLonglineDetailCompositionDto - fr.ird.observe.ui.actions.shared.ResetEditUIAction - fr.ird.observe.ui.actions.shared.SaveEditUIAction - - fr.ird.observe.ui.util.JVetoableTabbedPane - - org.jdesktop.swingx.JXTable - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <style source="../../Common.jcss"/> - - <!-- handler --> - <LonglineDetailCompositionUIHandler id='handler'/> - - <!-- model --> - <LonglineDetailCompositionUIModel id='model'/> - - <!-- section templates table model --> - <SectionTemplatesTableModel id='sectionTemplatesTableModel' initializer="getModel().getSectionTemplatesTableModel()"/> - - <!-- sections table model --> - <SectionsTableModel id='sectionsTableModel' initializer="getModel().getSectionsTableModel()"/> - - <!-- baskets table model --> - <BasketsTableModel id='basketsTableModel' initializer="getModel().getBasketsTableModel()"/> - - <!-- branchlines table model --> - <BranchlinesTableModel id='branchlinesTableModel' initializer="getModel().getBranchlinesTableModel()"/> - - <!-- edit bean --> - <SetLonglineDetailCompositionDto id='bean'/> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' beanClass='fr.ird.observe.services.dto.longline.SetLonglineDetailCompositionDto' - errorTableModel='{getErrorTableModel()}' context='ui-update-longlineDetailComposition'> - </BeanValidator> - - <BeanValidator id='sectionValidator' beanClass='fr.ird.observe.services.dto.longline.SectionDto' - errorTableModel='{getErrorTableModel()}' context='ui-update-table'> - <field name='basket' component='sectionsPane'/> - </BeanValidator> - - <BeanValidator id='basketValidator' beanClass='fr.ird.observe.services.dto.longline.BasketDto' - errorTableModel='{getErrorTableModel()}' context='ui-update-table'> - <field name='branchline' component='basketsPane'/> - <field name='floatline1Length' component='basketsPane'/> - <field name='floatline2Length' component='basketsPane'/> - </BeanValidator> - - <BeanValidator id='branchlineValidator' beanClass='fr.ird.observe.services.dto.longline.BranchlineDto' - errorTableModel='{getErrorTableModel()}' context='ui-update-table'> - <field name='settingIdentifier' component='branchlinesPane'/> - <field name='tracelineLength' component='branchlinesPane'/> - <field name='branchlineLength' component='branchlinesPane'/> - </BeanValidator> - - <JPopupMenu id='sectionTemplatesPopup'> - <JMenuItem id='deleteSelectedSectionTemplate' onActionPerformed='getHandler().deleteSelectedSectionTemplate()'/> - </JPopupMenu> - - <JPopupMenu id='sectionsPopup'> - <JMenuItem id='deleteSelectedSection' onActionPerformed='getHandler().deleteSelectedSection()'/> - <JMenuItem id='insertBeforeSelectedSection' onActionPerformed='getHandler().insertBeforeSelectedSection()'/> - <JMenuItem id='insertAfterSelectedSection' onActionPerformed='getHandler().insertAfterSelectedSection()'/> - </JPopupMenu> - - <JPopupMenu id='basketsPopup'> - <JMenuItem id='deleteSelectedBasket' onActionPerformed='getHandler().deleteSelectedBasket()'/> - <JMenuItem id='insertBeforeSelectedBasket' onActionPerformed='getHandler().insertBeforeSelectedBasket()'/> - <JMenuItem id='insertAfterSelectedBasket' onActionPerformed='getHandler().insertAfterSelectedBasket()'/> - </JPopupMenu> - - <JPopupMenu id='branchlinesPopup'> - <JMenuItem id='deleteSelectedBranchline' onActionPerformed='getHandler().deleteSelectedBranchline()'/> - <JMenuItem id='insertBeforeSelectedBranchline' onActionPerformed='getHandler().insertBeforeSelectedBranchline()'/> - <JMenuItem id='insertAfterSelectedBranchline' onActionPerformed='getHandler().insertAfterSelectedBranchline()'/> - </JPopupMenu> - - <!-- formulaire --> - <JPanel id="body" layout='{new BorderLayout()}'> - - <JVetoableTabbedPane id='fishingOperationTabPane' constraints='BorderLayout.CENTER'> - - <!-- generation tab --> - <tab id='generateTab'> - - <Table id='generateTabForm' fill='both' insets='1'> - - <!-- canGenerate --> - <row> - <cell anchor='west' fill="both"> - <JCheckBox id='canGenerate' - onItemStateChanged="getModel().setCanGenerate(((JCheckBox) event.getSource()).isSelected())"/> - </cell> - </row> - - <!-- sectionTemplates --> - <row> - <cell columns="2" fill="both" weightx="1" weighty="1"> - <JScrollPane id='sectionTemplatesPane'> - <JXTable id='sectionTemplatesTable'/> - </JScrollPane> - </cell> - </row> - - </Table> - - </tab> - - <!-- composition tab --> - <tab id='compositionTab'> - - <JPanel layout='{new BorderLayout()}'> - - <JPanel id="compositionActionPanel" constraints='BorderLayout.NORTH' layout='{new GridLayout()}'> - <JButton id='generateAll' onActionPerformed='getHandler().generateAllSections()'/> - <JButton id='deleteAll' onActionPerformed='getHandler().deleteAllSections()'/> - </JPanel> - - <JPanel id="compositionTablesPanel" constraints='BorderLayout.CENTER' layout='{new GridLayout(0,1)}'> - - <JScrollPane id='sectionsPane'> - <JXTable id='sectionsTable'/> - </JScrollPane> - - <JScrollPane id='basketsPane'> - <JXTable id='basketsTable'/> - </JScrollPane> - - <JScrollPane id='branchlinesPane'> - <JXTable id='branchlinesTable'/> - </JScrollPane> - - </JPanel> - - </JPanel> - - </tab> - - <!-- branchlineDetail tab --> - <tab id='branchlineDetailTab'> - - <JPanel id="branchlineDetailPanel" layout='{new BorderLayout()}'> - <Table fill="both" constraints='BorderLayout.NORTH'> - <row> - <cell weightx="1" fill="both" weighty="1"> - <BranchlineUI id="branchlineDetailUI" constructorParams="ObserveSwingApplicationContext.get().getMainUI()"/> - </cell> - </row> - </Table> - - </JPanel> - - </tab> - - </JVetoableTabbedPane> - - </JPanel> - - <!-- actions --> - <Table id="actions" fill='both' weightx='1' insets='0'> - <row> - <cell weightx="0.5"> - <JButton id='reset'/> - </cell> - <cell weightx="0.5"> - <JButton id='save'/> - </cell> - </row> - </Table> - - <!-- branchline detail model --> - <BranchlineUIModel id="branchlineDetailUIModel" initializer="branchlineDetailUI.getModel()"/> - -</fr.ird.observe.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionUIHandler.java deleted file mode 100644 index c81ccd5..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionUIHandler.java +++ /dev/null @@ -1,1369 +0,0 @@ -package fr.ird.observe.ui.content.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.longline.ActivityLonglineDto; -import fr.ird.observe.services.dto.longline.BasketDto; -import fr.ird.observe.services.dto.longline.BranchlineDto; -import fr.ird.observe.services.dto.longline.SectionDto; -import fr.ird.observe.services.dto.longline.SectionTemplate; -import fr.ird.observe.services.dto.longline.SectionWithTemplate; -import fr.ird.observe.services.dto.longline.SectionWithTemplates; -import fr.ird.observe.services.dto.longline.SetLonglineDetailCompositionDto; -import fr.ird.observe.services.dto.longline.SetLonglineDetailCompositionDtos; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.service.longline.SetLonglineDetailCompositionService; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.ContentUIHandler; -import fr.ird.observe.ui.content.ContentUIModel; -import fr.ird.observe.ui.util.JVetoableTabbedPane; -import org.apache.commons.lang3.BooleanUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.decorator.Decorator; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.JComboBox; -import javax.swing.JOptionPane; -import javax.swing.event.ChangeListener; -import javax.swing.event.TableModelListener; -import java.beans.PropertyChangeListener; -import java.util.ArrayList; -import java.util.LinkedHashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.stream.Collectors; - -import static com.google.common.collect.Lists.newArrayList; -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 12/5/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.8 - */ -public class LonglineDetailCompositionUIHandler extends ContentUIHandler<SetLonglineDetailCompositionDto> { - - static final String SECTION_TEMPLATES_EDITOR = "sectionTemplatesEditor"; - - /** Logger */ - private static final Log log = LogFactory.getLog(LonglineDetailCompositionUIHandler.class); - - private final PropertyChangeListener sectionTemplatesTableModelModified; - - private final PropertyChangeListener sectionsTableModelModified; - - private final TableModelListener sectionsTableModelChanged; - - private final PropertyChangeListener branchlineDetailChanged; - - private final PropertyChangeListener selectedSectionTemplateChanged; - - private final PropertyChangeListener basketsTableModelModified; - - private final TableModelListener basketsTableModelChanged; - - private final PropertyChangeListener branchinesTableModelModified; - - private final TableModelListener branchinesTableModelChanged; - - private final PropertyChangeListener selectedBranchlineChanged; - - private final ChangeListener tabbedPaneChanged; - - private Decorator<SectionDto> sectionDecorator; - - private Decorator<BasketDto> basketDecorator; - - private Decorator<BranchlineDto> branchlineDecorator; - - /** - * To avoid section flush when selected section changes (used when deleting a section). - */ - private boolean skipSavePreviousSelectedSection; - - /** - * To avoid basket flush when selection basket changes (used when deleting a bakset). - */ - private boolean skipSavePreviousSelectedBasket; - - /** - * To avoid branchline flush when selection branchline changes (used when deleting a branchline). - */ - private boolean skipSavePreviousSelectedBranchline; - - /** - * To avoid basket flush when section is adjusting (used when changing selected section). - */ - private boolean sectionAdjusting; - - private final PropertyChangeListener modelCanGenerateChanged; - - private final PropertyChangeListener selectedSectionChanged; - - /** - * To avoid branchline flush when basket is adjusting (used when changing selected basket). - */ - private boolean basketAdjusting; - - private final PropertyChangeListener selectedBasketChanged; - - private LonglineDetailCompositionUIValidationHelper validationHelper; - - /** - * To avoid some checks while opening ui. - */ - private boolean onOpen; - - private final JVetoableTabbedPane.ChangeSelectedIndex tabbedPaneWillChanged; - - public LonglineDetailCompositionUIHandler(LonglineDetailCompositionUI ui) { - super(ui, DataContextType.ActivityLongline, DataContextType.SetLongline); - sectionTemplatesTableModelModified = evt -> { - Boolean newValue = (Boolean) evt.getNewValue(); - onSectionTemplatesTableModelModified(newValue); - }; - sectionsTableModelModified = evt -> { - Boolean newValue = (Boolean) evt.getNewValue(); - onSectionsTableModelModified(newValue); - }; - sectionsTableModelChanged = e -> { - SectionsTableModel source = (SectionsTableModel) e.getSource(); - onSectionsTableModelChanged(source.getData()); - }; - branchlineDetailChanged = evt -> getUi().getValidator().setChanged(true); - selectedSectionTemplateChanged = evt -> { - SectionTemplate newValue = (SectionTemplate) evt.getNewValue(); - onSelectedSectionTemplateChanged(newValue); - }; - basketsTableModelModified = evt -> { - Boolean newValue = (Boolean) evt.getNewValue(); - onBasketsTableModelModified(newValue); - }; - basketsTableModelChanged = e -> { - BasketsTableModel source = (BasketsTableModel) e.getSource(); - onBasketsTableModelChanged(source.getData()); - }; - branchinesTableModelModified = evt -> onBranchlinesTableModelModified((Boolean) evt.getNewValue()); - branchinesTableModelChanged = e -> { - BranchlinesTableModel source = (BranchlinesTableModel) e.getSource(); - onBranchlinesTableModelChanged(source.getData()); - }; - selectedBranchlineChanged = evt -> { - BranchlineDto previousValue = (BranchlineDto) evt.getOldValue(); - BranchlineDto newValue = (BranchlineDto) evt.getNewValue(); - onSelectedBranchlineChanged(previousValue, newValue); - }; - tabbedPaneChanged = e -> { - JVetoableTabbedPane source = (JVetoableTabbedPane) e.getSource(); - int previousIndex = source.getPreviousIndex(); - int selectedIndex = source.getSelectedIndex(); - onTabChanged(previousIndex, selectedIndex); - }; - modelCanGenerateChanged = evt -> { - - sectionAdjusting = true; - - try { - Boolean newValue = (Boolean) evt.getNewValue(); - onModelCanGenerateChanged(newValue); - } finally { - - sectionAdjusting = false; - } - }; - selectedSectionChanged = evt -> { - - sectionAdjusting = true; - - try { - SectionDto previousValue = (SectionDto) evt.getOldValue(); - SectionDto newValue = (SectionDto) evt.getNewValue(); - onSelectedSectionChanged(previousValue, newValue); - } finally { - - sectionAdjusting = false; - } - }; - selectedBasketChanged = evt -> { - - basketAdjusting = true; - - try { - BasketDto previousValue = (BasketDto) evt.getOldValue(); - BasketDto newValue = (BasketDto) evt.getNewValue(); - onSelectedBasketChanged(previousValue, newValue); - } finally { - - basketAdjusting = false; - } - }; - tabbedPaneWillChanged = this::onTabWillChanged; - } - - @Override - public LonglineDetailCompositionUI getUi() { - return (LonglineDetailCompositionUI) super.getUi(); - } - - @Override - public LonglineDetailCompositionUIModel getModel() { - return (LonglineDetailCompositionUIModel) super.getModel(); - } - - @Override - protected boolean computeCanWrite(ObserveSwingDataSource source) { - return source.canWriteData(); - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - ContentMode contentMode; - - if (getOpenDataManager().isOpenActivityLongline(dataContext.getSelectedActivityLonglineId())) { - - // l'activité est ouverte, mode édition - contentMode = ContentMode.UPDATE; - } else { - - // l'activité n'est pas ouverte, mode lecture - addMessage(getUi(), - NuitonValidatorScope.INFO, - getEntityLabel(ActivityLonglineDto.class), - t("observe.storage.activityLongline.message.not.open")); - - contentMode = ContentMode.READ; - } - - return contentMode; - - } - - @Override - public void initUI() { - - this.sectionDecorator = getDecoratorService().getDecoratorByType(SectionDto.class); - this.basketDecorator = getDecoratorService().getDecoratorByType(BasketDto.class); - this.branchlineDecorator = getDecoratorService().getDecoratorByType(BranchlineDto.class); - - LonglineDetailCompositionUIInitializer uiInitializer = new LonglineDetailCompositionUIInitializer(getUi()); - uiInitializer.initUI(); - - LonglineDetailCompositionUI ui1 = getUi(); - - this.validationHelper = new LonglineDetailCompositionUIValidationHelper(ui1, getDecoratorService()); - - getBranchlineDetailUIModel().addPropertyChangeListener(BranchlineUIModel.PROPERTY_SAVED, branchlineDetailChanged); - - { - // init section templates table - - SectionTemplatesTableModel tableModel = getSectionTemplatesTableModel(); - tableModel.addPropertyChangeListener(SectionTemplatesTableModel.MODIFIED_PROPERTY, sectionTemplatesTableModelModified); - - getModel().addPropertyChangeListener(LonglineDetailCompositionUIModel.PROPERTY_CAN_GENERATE, modelCanGenerateChanged); - } - - { - // init sections table - - SectionsTableModel tableModel = getSectionsTableModel(); - tableModel.addPropertyChangeListener(SectionsTableModel.MODIFIED_PROPERTY, sectionsTableModelModified); - tableModel.addPropertyChangeListener(SectionsTableModel.SELECTED_ROW_PROPERTY, selectedSectionChanged); - tableModel.addPropertyChangeListener(SectionsTableModel.TEMPLATE_PROPERTY, selectedSectionTemplateChanged); - tableModel.addTableModelListener(sectionsTableModelChanged); - - } - { - // init baskets table - - BasketsTableModel tableModel = getBasketsTableModel(); - tableModel.addPropertyChangeListener(BasketsTableModel.MODIFIED_PROPERTY, basketsTableModelModified); - tableModel.addPropertyChangeListener(BasketsTableModel.SELECTED_ROW_PROPERTY, selectedBasketChanged); - tableModel.addTableModelListener(basketsTableModelChanged); - - } - - { - // init branchlines table - - BranchlinesTableModel tableModel = getBranchlinesTableModel(); - tableModel.addPropertyChangeListener(BranchlinesTableModel.MODIFIED_PROPERTY, branchinesTableModelModified); - tableModel.addPropertyChangeListener(BranchlinesTableModel.SELECTED_ROW_PROPERTY, selectedBranchlineChanged); - tableModel.addTableModelListener(branchinesTableModelChanged); - - } - - JVetoableTabbedPane tabPane = ui1.getFishingOperationTabPane(); - - tabPane.setChangeSelectedIndex(tabbedPaneWillChanged); - tabPane.addChangeListener(tabbedPaneChanged); - - } - - @Override - public void openUI() { - - UIHelper.stopEditing(getUi().getSectionTemplatesTable()); - UIHelper.stopEditing(getUi().getSectionsTable()); - - super.openUI(); - - { - // open brancheline detail - BranchlineUI branchlineDetailUI = getUi().getBranchlineDetailUI(); - branchlineDetailUI.open(); - } - - String setId = getSelectedId(); - - if (log.isInfoEnabled()) { - log.info("setId = " + setId); - } - ContentMode mode = computeContentMode(); - // utilisation du mode requis - setContentMode(mode); - - SetLonglineDetailCompositionService setLonglineService = getSetLonglineDetailCompositionService(); - - Form<SetLonglineDetailCompositionDto> setLonglineDtoForm = setLonglineService.loadForm(setId); - - loadReferentialReferenceSetsInModel(setLonglineDtoForm); - - getModel().setForm(setLonglineDtoForm); - - SetLonglineDetailCompositionDto bean = getBean(); - SetLonglineDetailCompositionDtos.copySetLonglineDetailCompositionDto(setLonglineDtoForm.getObject(), bean); - - //FIXME Voir comment gérer ça - Form<BranchlineDto> branchlineDtoForm = Form.newFormDto(BranchlineDto.class, null, null, null); - - BranchlineUIModel branchlineUIModel = getUi().getBranchlineDetailUI().getModel(); - branchlineUIModel.setReferentialReferenceSets(getModel().getReferentialReferenceSets()); - branchlineUIModel.setForm(branchlineDtoForm); - - //FIXME Validate this default date - if (log.isInfoEnabled()) { - log.info("Use as default branchline timer date: " + bean.getSettingStartTimeStamp()); - } - getBranchlinesTableModel().setDefaultDate(bean.getSettingStartTimeStamp()); - getBranchlinesTableModel().setUseTimer(BooleanUtils.isTrue(bean.getMonitored())); - - // by default, can generate if there is no section in database - getModel().setCanGenerate(bean.isSectionEmpty()); - - // TODO Use a cache of templates on setLongline (session scope) - getSectionTemplatesTableModel().setData(new ArrayList<>()); - - BranchlineUI branchlineDetailUI = getUi().getBranchlineDetailUI(); - branchlineDetailUI.edit(null); - - onOpen = true; - - try { - - List<SectionWithTemplate> section = SectionWithTemplates.getSectionTemplates(bean.getSection()); - getSectionsTableModel().setData(section); - - validationHelper.setObjectValueAdjusting(true); - - try { - - onSectionTemplatesTableModelModified(false); - onSectionsTableModelModified(false); - onBasketsTableModelModified(false); - onBranchlinesTableModelModified(false); - - } finally { - - validationHelper.setObjectValueAdjusting(false); - validationHelper.whenSectionChanged(); - - } - - // Always go back to first tab - getUi().getFishingOperationTabPane().setSelectedIndex(0); - - } finally { - - onOpen = false; - - } - - if (mode != ContentMode.READ) { - getUi().startEdit(null); - } - - } - - @Override - public void startEditUI(String... binding) { - - ContentUIModel<SetLonglineDetailCompositionDto> model = getModel(); - addInfoMessage(t("observe.content.longlineDetailComposition.message.updating")); - - super.startEditUI(LonglineDetailCompositionUI.BINDING_GENERATE_ALL_ENABLED, - LonglineDetailCompositionUI.BINDING_DELETE_ALL_ENABLED); - - model.setModified(false); - - } - - @Override - protected boolean doSave(SetLonglineDetailCompositionDto bean) throws Exception { - - BranchlineUI branchlineDetailUI = getUi().getBranchlineDetailUI(); - - boolean continueSave = true; - - if (getUi().getFishingOperationTabPane().getSelectedIndex() == 2) { - - BranchlineUIHandler branchlineUIHandler = branchlineDetailUI.getHandler(); - - continueSave = branchlineUIHandler.tryToQuit(); - - } - - if (continueSave) { - - SectionsTableModel sectionsTableModel = getSectionsTableModel(); - SectionWithTemplate selectedSection = sectionsTableModel.getSelectedRow(); - if (selectedSection != null) { - - // flush selected section before save - flushSection(selectedSection); - - } - - SaveResultDto saveResult = getSetLonglineDetailCompositionService().save(bean); - saveResult.toDto(bean); - - } - - return continueSave; - } - - public void generateAllSections() { - - if (log.isInfoEnabled()) { - log.info("Generate all sections."); - } - - SetLonglineDetailCompositionDto bean = getBean(); - Integer nbSections = bean.getTotalSectionsCount(); - Integer basketsCount = bean.getBasketsPerSectionCount(); - Integer nbBranchlines = bean.getBranchlinesPerBasketCount(); - - SectionTemplate template = null; - - SectionTemplatesTableModel sectionTemplatesTableModel = getSectionTemplatesTableModel(); - List<SectionTemplate> sectionTemplates = sectionTemplatesTableModel.getNotEmptyData(); - if (sectionTemplates.size() == 1) { - - template = sectionTemplates.get(0); - - boolean compiliantWithBasketCount = template.isCompiliantWithBasketCount(basketsCount); - if (!compiliantWithBasketCount) { - - if (log.isWarnEnabled()) { - log.warn("sectionTemplate " + template + " is not compliant with basketCount: " + basketsCount); - } - - UIHelper.displayWarning(t("observe.content.longlineDetailComposition.title.section.cant.use.firstTemplate"), t("observe.content.longlineDetailComposition.firstTemplate.template.notCompilant.basketCount", template.getFloatlineLengths(), basketsCount)); - - template = null; - - } - - } - - boolean usingTemplate = template != null; - - if (usingTemplate) { - - if (log.isInfoEnabled()) { - log.info("Will use sectionTemplate: " + template); - } - } - - validationHelper.setObjectValueAdjusting(true); - - try { - - SectionsTableModel sectionsTableModel = getSectionsTableModel(); - BasketsTableModel basketsTableModel = getBasketsTableModel(); - BranchlinesTableModel branchlinesTableModel = getBranchlinesTableModel(); - - List<SectionWithTemplate> sections = new ArrayList<>(nbSections); - - for (int sectionNumber = 0; sectionNumber < nbSections; sectionNumber++) { - - SectionWithTemplate section = sectionsTableModel.createNewRow(); - sections.add(section); - - for (int basketNumber = 0; basketNumber < basketsCount; basketNumber++) { - - BasketDto basket = basketsTableModel.createNewRow(); - section.addBasket(basket); - - for (int branchlineNumber = 0; branchlineNumber < nbBranchlines; branchlineNumber++) { - - BranchlineDto branchline = branchlinesTableModel.createNewRow(); - basket.addBranchline(branchline); - - } - - LinkedList<BranchlineDto> branchlines = Lists.newLinkedList(basket.getBranchline()); - branchlinesTableModel.rearrangeIds(branchlines); - - } - - List<BasketDto> baskets = Lists.newLinkedList(section.getBasket()); - basketsTableModel.rearrangeIds(baskets); - - if (usingTemplate) { - - section.setSectionTemplate(template); - template.applyToBaskets(baskets); - - } - - } - - sectionsTableModel.rearrangeIds(sections); - sectionsTableModel.setData(sections); - - List<SectionDto> sectionDtos = sections.stream() - .map(SectionWithTemplate::getDelegate) - .collect(Collectors.toList()); - - getBean().addAllSection(sectionDtos); - - getModel().setModified(true); - - } finally { - - validationHelper.setObjectValueAdjusting(false); - validationHelper.whenSectionChanged(); - - } - - } - - public void deleteAllSections() { - - if (getSectionsTableModel().isEmpty()) { - - // no section - return; - } - - boolean canDelete = true; - for (SectionWithTemplate sectionWithTemplate : getSectionsTableModel().getNotEmptyData()) { - - if (!canDeleteSection(sectionWithTemplate.getDelegate())) { - canDelete = false; - break; - } - } - - if (!canDelete) { - - // there is some references, can't delete - UIHelper.displayWarning(t("observe.content.section.cant.delete.title"), t("observe.content.section.cant.delete.message")); - return; - - } - - ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); - int response = UIHelper.askUser(mainUI, - t("observe.title.delete"), - t("observe.content.sections.delete.message"), - JOptionPane.WARNING_MESSAGE, - new Object[]{t("observe.choice.confirm.delete"), - t("observe.choice.cancel")}, - 1); - - if (response != 0) { - - // user cancel - return; - } - - if (log.isInfoEnabled()) { - log.info("Remove all sections."); - } - - validationHelper.setObjectValueAdjusting(true); - - try { - - getSectionsTableModel().setData(new ArrayList<>()); - getBean().getSection().clear(); - getModel().setModified(true); - - } finally { - - validationHelper.setObjectValueAdjusting(false); - validationHelper.whenSectionChanged(); - - } - - } - - public void deleteSelectedSectionTemplate() { - - SectionTemplatesTableModel tableModel = getSectionTemplatesTableModel(); - boolean selectionEmpty = tableModel.isSelectionEmpty(); - - if (!selectionEmpty) { - - SectionTemplate data = getSectionTemplatesTableModel().getSelectedRow(); - - if (log.isInfoEnabled()) { - log.info("Delete: " + data); - } - - ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); - int response = UIHelper.askUser(mainUI, - t("observe.title.delete"), - t("observe.content.sectionTemplate.delete.message"), - JOptionPane.WARNING_MESSAGE, - new Object[]{t("observe.choice.confirm.delete"), - t("observe.choice.cancel")}, - 1); - - if (response != 0) { - - // user cancel - return; - } - - getSectionTemplatesTableModel().removeSelectedRow(); - - } - - } - - public void deleteSelectedSection() { - - SectionsTableModel tableModel = getSectionsTableModel(); - - boolean selectionEmpty = tableModel.isSelectionEmpty(); - - if (!selectionEmpty) { - - SectionWithTemplate selectedSection = tableModel.getSelectedRow(); - - boolean canDelete = canDeleteSection(selectedSection.getDelegate()); - - if (!canDelete) { - // there is some references, can't delete - UIHelper.displayWarning(t("observe.content.section.cant.delete.title"), t("observe.content.section.cant.delete.message")); - return; - } - - boolean accept = UIHelper.confirmForEntityDelete(ui, SectionDto.class, selectedSection); - - ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); - mainUI.setBusy(false); - - if (!accept) { - return; - } - - if (log.isInfoEnabled()) { - log.info("Delete section: " + sectionDecorator.toString(selectedSection)); - } - - validationHelper.setObjectValueAdjusting(true); - skipSavePreviousSelectedSection = true; - - try { - - getBean().removeSection(tableModel.getSelectedRow().getDelegate()); - tableModel.removeSelectedRow(); - - } finally { - - skipSavePreviousSelectedSection = false; - validationHelper.setObjectValueAdjusting(false); - validationHelper.whenSectionChanged(); - - } - - } - - } - - public void insertBeforeSelectedSection() { - - validationHelper.setObjectValueAdjusting(true); - - try { - - SectionsTableModel tableModel = getSectionsTableModel(); - tableModel.insertBeforeSelectedRow(); - - SectionWithTemplate newSectionWithTemplate = tableModel.getSelectedRow(); - int selectedRowIndex = tableModel.getSelectedRowIndex(); - List<SectionDto> sections = newArrayList(getBean().getSection()); - sections.add(selectedRowIndex, newSectionWithTemplate.getDelegate()); - getBean().getSection().clear(); - getBean().addAllSection(sections); - - } finally { - - validationHelper.setObjectValueAdjusting(false); - validationHelper.whenSectionChanged(); - - } - - } - - public void insertAfterSelectedSection() { - - validationHelper.setObjectValueAdjusting(true); - - try { - - SectionsTableModel tableModel = getSectionsTableModel(); - tableModel.insertAfterSelectedRow(); - - SectionWithTemplate newSectionWithTemplate = tableModel.getSelectedRow(); - int selectedRowIndex = tableModel.getSelectedRowIndex(); - List<SectionDto> sections = newArrayList(getBean().getSection()); - sections.add(selectedRowIndex, newSectionWithTemplate.getDelegate()); - getBean().getSection().clear(); - getBean().addAllSection(sections); - - } finally { - - validationHelper.setObjectValueAdjusting(false); - validationHelper.whenSectionChanged(); - - } - - } - - public void deleteSelectedBasket() { - - BasketsTableModel tableModel = getBasketsTableModel(); - - boolean selectionNotEmpty = !tableModel.isSelectionEmpty(); - - if (selectionNotEmpty) { - - BasketDto selectedBasket = tableModel.getSelectedRow(); - - boolean canDelete = canDeleteBasket(selectedBasket); - - if (!canDelete) { - - // there is some references, can't delete - UIHelper.displayWarning(t("observe.content.basket.cant.delete.title"), t("observe.content.basket.cant.delete.message")); - return; - - } - - boolean accept = UIHelper.confirmForEntityDelete(ui, BasketDto.class, selectedBasket); - ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); - mainUI.setBusy(false); - - if (!accept) { - return; - } - - if (log.isInfoEnabled()) { - log.info("Delete basket: " + basketDecorator.toString(selectedBasket)); - } - - validationHelper.setObjectValueAdjusting(true); - skipSavePreviousSelectedBasket = true; - - try { - - getSectionsTableModel().getSelectedRow().removeBasket(selectedBasket); - tableModel.removeSelectedRow(); - - } finally { - - skipSavePreviousSelectedBasket = false; - - validationHelper.setObjectValueAdjusting(false); - validationHelper.whenBasketChanged(); - - } - - } - - } - - public void insertBeforeSelectedBasket() { - - validationHelper.setObjectValueAdjusting(true); - - try { - - BasketsTableModel tableModel = getBasketsTableModel(); - tableModel.insertBeforeSelectedRow(); - - BasketDto newBasket = tableModel.getSelectedRow(); - int selectedRowIndex = tableModel.getSelectedRowIndex(); - SectionWithTemplate selectedSection = getSectionsTableModel().getSelectedRow(); - if (selectedSection.isBasketEmpty()) { - selectedSection.setBasket(new LinkedHashSet<>()); - } - List<BasketDto> baskets = newArrayList(selectedSection.getBasket()); - baskets.add(selectedRowIndex, newBasket); - selectedSection.getBasket().clear(); - selectedSection.addAllBasket(baskets); - - } finally { - - validationHelper.setObjectValueAdjusting(false); - validationHelper.whenBasketChanged(); - - } - - } - - public void insertAfterSelectedBasket() { - - validationHelper.setObjectValueAdjusting(true); - - try { - - BasketsTableModel tableModel = getBasketsTableModel(); - tableModel.insertAfterSelectedRow(); - - BasketDto newBasket = tableModel.getSelectedRow(); - int selectedRowIndex = tableModel.getSelectedRowIndex(); - SectionWithTemplate selectedSection = getSectionsTableModel().getSelectedRow(); - if (selectedSection.isBasketEmpty()) { - selectedSection.setBasket(new LinkedHashSet<>()); - } - List<BasketDto> baskets = newArrayList(selectedSection.getBasket()); - baskets.add(selectedRowIndex, newBasket); - selectedSection.getBasket().clear(); - selectedSection.addAllBasket(baskets); - - } finally { - - validationHelper.setObjectValueAdjusting(false); - validationHelper.whenBasketChanged(); - - } - - } - - public void deleteSelectedBranchline() { - - BranchlinesTableModel tableModel = getBranchlinesTableModel(); - - boolean selectionNotEmpty = !tableModel.isSelectionEmpty(); - - if (selectionNotEmpty) { - - BranchlineDto selectedBranchline = tableModel.getSelectedRow(); - - boolean canDelete = canDeleteBranchline(selectedBranchline); - - if (!canDelete) { - - // there is some references, can't delete - UIHelper.displayWarning(t("observe.content.branchLine.cant.delete.title"), t("observe.content.branchLine.cant.delete.message")); - return; - - } - - boolean accept = UIHelper.confirmForEntityDelete(ui, BranchlineDto.class, selectedBranchline); - ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); - mainUI.setBusy(false); - if (!accept) { - return; - } - - if (log.isInfoEnabled()) { - log.info("Delete branchline: " + branchlineDecorator.toString(selectedBranchline)); - } - - validationHelper.setObjectValueAdjusting(true); - skipSavePreviousSelectedBranchline = true; - - try { - - getBasketsTableModel().getSelectedRow().removeBranchline(selectedBranchline); - tableModel.removeSelectedRow(); - - } finally { - - skipSavePreviousSelectedBranchline = false; - validationHelper.setObjectValueAdjusting(false); - validationHelper.whenBranchlineChanged(); - - } - - } - - } - - public void insertBeforeSelectedBranchline() { - - validationHelper.setObjectValueAdjusting(true); - - try { - - BranchlinesTableModel tableModel = getBranchlinesTableModel(); - tableModel.insertBeforeSelectedRow(); - - BranchlineDto newBranchline = tableModel.getSelectedRow(); - int selectedRowIndex = tableModel.getSelectedRowIndex(); - BasketDto selectedBasket = getBasketsTableModel().getSelectedRow(); - if (selectedBasket.isBranchlineEmpty()) { - selectedBasket.setBranchline(new LinkedHashSet<>()); - } - - List<BranchlineDto> branchlines = newArrayList(selectedBasket.getBranchline()); - branchlines.add(selectedRowIndex, newBranchline); - selectedBasket.getBranchline().clear(); - selectedBasket.addAllBranchline(branchlines); - - } finally { - - validationHelper.setObjectValueAdjusting(false); - validationHelper.whenBasketChanged(); - - } - - } - - public void insertAfterSelectedBranchline() { - - validationHelper.setObjectValueAdjusting(true); - - try { - - BranchlinesTableModel tableModel = getBranchlinesTableModel(); - tableModel.insertAfterSelectedRow(); - - BranchlineDto newBranchline = tableModel.getSelectedRow(); - int selectedRowIndex = tableModel.getSelectedRowIndex(); - BasketDto selectedBasket = getBasketsTableModel().getSelectedRow(); - if (selectedBasket.isBranchlineEmpty()) { - selectedBasket.setBranchline(new LinkedHashSet<>()); - } - List<BranchlineDto> branchlines = newArrayList(selectedBasket.getBranchline()); - branchlines.add(selectedRowIndex, newBranchline); - selectedBasket.getBranchline().clear(); - selectedBasket.addAllBranchline(branchlines); - - - } finally { - - validationHelper.setObjectValueAdjusting(false); - validationHelper.whenBasketChanged(); - - } - - } - - protected void onSectionTemplatesTableModelModified(Boolean newValue) { - - // recompute table model valid state - getSectionTemplatesTableModel().validate(); - - } - - protected void onSectionsTableModelModified(Boolean newValue) { - - if (newValue) { - - getModel().setModified(true); - - } - - validationHelper.whenSectionChanged(); - - } - - protected void onSectionsTableModelChanged(List<SectionWithTemplate> data) { - - if (log.isInfoEnabled()) { - log.info("Sections was changed, new size: " + data.size()); - } - - validationHelper.whenSectionChanged(); - - } - - protected void onModelCanGenerateChanged(Boolean canGenerate) { - - if (canGenerate) { - - if (getSectionTemplatesTableModel().isEmpty()) { - - // add an empty row - getSectionTemplatesTableModel().addNewRow(); - - } - - } - - } - - protected void onSelectedSectionChanged(SectionDto previousSection, SectionDto newSection) { - - if (log.isInfoEnabled()) { - log.info("New selected section: " + sectionDecorator.toString(newSection)); - } - - validationHelper.setObjectValueAdjusting(true); - - try { - - if (previousSection != null && !onOpen && !skipSavePreviousSelectedSection) { - - // must flush back baksets to the previous section - flushSection(previousSection); - - } - - List<BasketDto> baskets = newSection == null ? new ArrayList<>() : newArrayList(newSection.getBasket()); - getBasketsTableModel().setData(baskets); - - } finally { - - validationHelper.setObjectValueAdjusting(false); - - } - - } - - protected void onSelectedSectionTemplateChanged(SectionTemplate newTemplate) { - - if (newTemplate != null) { - - SectionWithTemplate selectedSection = getSectionsTableModel().getSelectedRow(); - if (log.isInfoEnabled()) { - log.info("Will apply template: " + newTemplate + " to section: " + sectionDecorator.toString(selectedSection)); - } - - validationHelper.setObjectValueAdjusting(true); - - try { - - getBasketsTableModel().applySectionTemplate(newTemplate); - - } finally { - - validationHelper.setObjectValueAdjusting(false); - validationHelper.whenSectionChanged(); - - } - - } - - } - - protected void onBasketsTableModelModified(Boolean newValue) { - - if (newValue) { - - getModel().setModified(true); - - } - - validationHelper.whenBasketChanged(); - - } - - protected void onBasketsTableModelChanged(List<BasketDto> data) { - - if (log.isInfoEnabled()) { - log.info("Baskets was changed, new size: " + data.size()); - } - - } - - protected void onSelectedBasketChanged(BasketDto previousBasket, BasketDto newBasket) { - - if (log.isInfoEnabled()) { - log.info("New selected basket: " + basketDecorator.toString(newBasket)); - } - - if (previousBasket != null && !sectionAdjusting && !skipSavePreviousSelectedBasket) { - - flushBasket(previousBasket); - - } - - List<BranchlineDto> branchlines = new ArrayList<>(); - if (newBasket != null && newBasket.getBranchline() != null) { - branchlines.addAll(newBasket.getBranchline()); - } - getBranchlinesTableModel().setData(branchlines); - - } - - protected void onBranchlinesTableModelModified(Boolean newValue) { - - if (newValue) { - - getModel().setModified(true); - - } - - validationHelper.whenBranchlineChanged(); - - } - - protected void onBranchlinesTableModelChanged(List<BranchlineDto> data) { - - if (log.isInfoEnabled()) { - log.info("Branchlines was changed, new size: " + data.size()); - } - - } - - protected void onSelectedBranchlineChanged(BranchlineDto previousBranchline, BranchlineDto newBranchline) { - - if (log.isInfoEnabled()) { - log.info("New selected branchline: " + branchlineDecorator.toString(newBranchline)); - } - - if (previousBranchline != null && !basketAdjusting && !skipSavePreviousSelectedBranchline) { - - // must flush back branchline detail to his row - flushBranchline(previousBranchline); - - } - - } - - protected boolean onTabWillChanged(int selectedIndex, int index) { - - boolean result = true; - - if (!onOpen && index > -1) { - - switch (selectedIndex) { - - case 0: - - boolean generateTabValid = getModel().isGenerateTabValid(); - result = generateTabValid; - - break; - - case 1: - - boolean compositionTabValid = getModel().isCompositionTabValid(); - result = compositionTabValid; - - break; - - case 2: - - boolean branchlineDetailTabValid = getUi().getBranchlineDetailUI().getHandler().tryToQuit(); - result = branchlineDetailTabValid; - - break; - } - - } - - return result; - } - - protected void onTabChanged(int previousIndex, int selectedIndex) { - - switch (previousIndex) { - case 0: - - // abort editing table - UIHelper.stopEditing(getUi().getSectionTemplatesTable()); - - break; - case 1: - - // abort editing tables - UIHelper.stopEditing(getUi().getSectionsTable()); - - break; - case 2: - - BranchlineUI branchlineDetailUI = getUi().getBranchlineDetailUI(); - branchlineDetailUI.getModel().removePropertyChangeListener(BranchlineUIModel.PROPERTY_MODIFIED, branchlineDetailChanged); - branchlineDetailUI.edit(null); - - break; - } - - switch (selectedIndex) { - case 0: - - break; - case 1: - - if (previousIndex == 0) { - - if (getModel().isCanGenerate()) { - - // update section templates list - List<SectionTemplate> sectionTemplates = getSectionTemplatesTableModel().getNotEmptyData(); - JComboBox comboBox = (JComboBox) getUi().getSectionsTable().getClientProperty(SECTION_TEMPLATES_EDITOR); - LonglineDetailCompositionUIInitializer.prepareComboBoxData(comboBox, sectionTemplates); - - //FIXME See why templates are not well reselect in cell editor - //FIXME See cell editor does not loose focus and empty selection when losing focus - - } - } - - break; - case 2: - - BranchlineDto branchline = getBranchlinesTableModel().getSelectedRow(); - - if (branchline != null) { - - // update branchline detail - BranchlineUI branchlineDetailUI = getUi().getBranchlineDetailUI(); - branchlineDetailUI.edit(branchline); - branchlineDetailUI.getModel().addPropertyChangeListener(BranchlineUIModel.PROPERTY_MODIFIED, branchlineDetailChanged); - - } - - break; - - } - - } - - protected void flushSection(SectionDto section) { - - BasketsTableModel basketsTableModel = getBasketsTableModel(); - - if (!basketsTableModel.isSelectionEmpty()) { - - // must flush back branchlines to selected basket - BasketDto selectedBasket = basketsTableModel.getSelectedRow(); - flushBasket(selectedBasket); - - } - - // flush bask baskets to the given section - - List<BasketDto> baskets = basketsTableModel.getNotEmptyData(); - section.setBasket(new LinkedHashSet<>(baskets)); - - if (log.isInfoEnabled()) { - log.info("Flush baskets (" + baskets.size() + ") to his section: " + sectionDecorator.toString(section)); - } - - } - - protected void flushBasket(BasketDto basket) { - - BranchlinesTableModel branchlinesTableModel = getBranchlinesTableModel(); - - if (!branchlinesTableModel.isSelectionEmpty()) { - - // must flush back details to selected branchline - flushBranchline(branchlinesTableModel.getSelectedRow()); - - } - - // flush bask branchlines to the given basket - - List<BranchlineDto> branchlines = branchlinesTableModel.getNotEmptyData(); - basket.setBranchline(new LinkedHashSet<>(branchlines)); - - if (log.isInfoEnabled()) { - log.info("Flush branchlines (" + branchlines.size() + ") to his basket: " + basketDecorator.toString(basket)); - } - - } - - protected void flushBranchline(BranchlineDto branchline) { - - if (log.isInfoEnabled()) { - log.info("Flush branchline details: " + branchlineDecorator.toString(branchline)); - } - - } - - protected SectionTemplatesTableModel getSectionTemplatesTableModel() { - return getModel().getSectionTemplatesTableModel(); - } - - protected SectionsTableModel getSectionsTableModel() { - return getModel().getSectionsTableModel(); - } - - protected BasketsTableModel getBasketsTableModel() { - return getModel().getBasketsTableModel(); - } - - protected BranchlinesTableModel getBranchlinesTableModel() { - return getModel().getBranchlinesTableModel(); - } - - public BranchlineUIModel getBranchlineDetailUIModel() { - return getUi().getBranchlineDetailUIModel(); - } - - protected boolean canDeleteSection(SectionDto section) { - - return section.isNotPersisted() || getSetLonglineDetailCompositionService().canDeleteSection(section.getId()); - - } - - protected boolean canDeleteBasket(BasketDto basket) { - - return basket.isNotPersisted() || getSetLonglineDetailCompositionService().canDeleteBasket(basket.getId()); - - } - - protected boolean canDeleteBranchline(BranchlineDto branchline) { - - return branchline.isNotPersisted() || getSetLonglineDetailCompositionService().canDeleteBranchline(branchline.getId()); - - } - - protected SetLonglineDetailCompositionService getSetLonglineDetailCompositionService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newSetLonglineDetailCompositionService(); - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionUIInitializer.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionUIInitializer.java deleted file mode 100644 index 7a72ff7..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionUIInitializer.java +++ /dev/null @@ -1,398 +0,0 @@ -package fr.ird.observe.ui.content.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.longline.SectionTemplate; -import fr.ird.observe.services.dto.longline.SetLonglineDetailCompositionDto; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.ContentUIInitializer; -import fr.ird.observe.ui.util.table.AutotSelectRowAndShowPopupActionSupport; -import fr.ird.observe.ui.util.table.EditableTableModelSupport; -import org.jdesktop.swingx.autocomplete.ComboBoxCellEditor; -import org.nuiton.decorator.Decorator; - -import javax.swing.JComboBox; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.table.TableCellRenderer; -import java.awt.Container; -import java.io.Serializable; -import java.util.Collections; - -import static org.nuiton.i18n.I18n.n; - -/** - * Created on 12/13/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.10 - */ -public class LonglineDetailCompositionUIInitializer extends ContentUIInitializer<SetLonglineDetailCompositionDto, LonglineDetailCompositionUI> { - - public LonglineDetailCompositionUIInitializer(LonglineDetailCompositionUI ui) { - super(ui); - } - - @Override - public void initUI() { - super.initUI(); - - LonglineDetailCompositionUIModel model = ui.getModel(); - - { - // init section templates table - JTable table = ui.getSectionTemplatesTable(); - - UIHelper.setI18nTableHeaderRenderer(table, - n("observe.content.longlineDetailComposition.sectionTemplatesTable.identifier"), - n("observe.content.longlineDetailComposition.sectionTemplatesTable.identifier.tip"), - n("observe.content.longlineDetailComposition.sectionTemplatesTable.value"), - n("observe.content.longlineDetailComposition.sectionTemplatesTable.value.tip")); - - SectionTemplatesTableModel tableModel = model.getSectionTemplatesTableModel(); - tableModel.installTableKeyListener(table); - tableModel.installTableFocusListener(table); - - ListSelectionModel selectionModel = table.getSelectionModel(); - selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - tableModel.installSelectionListener(table); - - new SectionTemplatesAutotSelectRowAndShowPopupAction(ui, ui.getSectionTemplatesPane(), table, ui.getSectionTemplatesPopup()); - - } - - { - // init sections table - JTable table = ui.getSectionsTable(); - - UIHelper.setI18nTableHeaderRenderer(table, - n("observe.content.longlineDetailComposition.sectionsTable.settingIdentifier"), - n("observe.content.longlineDetailComposition.sectionsTable.settingIdentifier.tip"), - n("observe.content.longlineDetailComposition.sectionsTable.haulingIdentifier"), - n("observe.content.longlineDetailComposition.sectionsTable.haulingIdentifier.tip"), - n("observe.content.longlineDetailComposition.sectionsTable.template"), - n("observe.content.longlineDetailComposition.sectionsTable.template.tip")); - - TableCellRenderer renderer = table.getDefaultRenderer(Object.class); - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 2, UIHelper.newDecorateTableCellRenderer(renderer, SectionTemplate.class)); - - UIHelper.setTableColumnEditor(table, 1, newIntegerColumnEditor(table)); - - DecoratorService decoratorService = ui.getHandler().getDecoratorService(); - Decorator<SectionTemplate> sectionTemplateDecorator = decoratorService.getDecoratorByType(SectionTemplate.class); - JComboBox comboBox = new JComboBox(); - table.putClientProperty(LonglineDetailCompositionUIHandler.SECTION_TEMPLATES_EDITOR, comboBox); - ComboBoxCellEditor editor = newDataColumnEditor(comboBox, Collections.emptyList(), sectionTemplateDecorator); - UIHelper.setTableColumnEditor(table, 2, editor); - - SectionsTableModel tableModel = model.getSectionsTableModel(); - tableModel.installTableKeyListener(table); - tableModel.installTableFocusListener(table); - - ListSelectionModel selectionModel = table.getSelectionModel(); - selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - tableModel.installSelectionListener(table); - - new SectionsAutotSelectRowAndShowPopupAction(ui, ui.getSectionsPane(), table, ui.getSectionsPopup()); - - } - { - // init baskets table - JTable table = ui.getBasketsTable(); - - UIHelper.setI18nTableHeaderRenderer(table, - n("observe.content.longlineDetailComposition.basketsTable.settingIdentifier"), - n("observe.content.longlineDetailComposition.basketsTable.settingIdentifier.tip"), - n("observe.content.longlineDetailComposition.basketsTable.haulingIdentifier"), - n("observe.content.longlineDetailComposition.basketsTable.haulingIdentifier.tip"), - n("observe.content.longlineDetailComposition.basketsTable.floatline1Length"), - n("observe.content.longlineDetailComposition.basketsTable.floatline1Length.tip"), - n("observe.content.longlineDetailComposition.basketsTable.floatline2Length"), - n("observe.content.longlineDetailComposition.basketsTable.floatline2Length.tip")); - - TableCellRenderer renderer = table.getDefaultRenderer(Object.class); - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - - UIHelper.setTableColumnEditor(table, 1, newIntegerColumnEditor(table)); - UIHelper.setTableColumnEditor(table, 2, newFloatColumnEditor(table)); - UIHelper.setTableColumnEditor(table, 3, newFloatColumnEditor(table)); - - BasketsTableModel tableModel = model.getBasketsTableModel(); - tableModel.installTableKeyListener(table); - tableModel.installTableFocusListener(table); - - ListSelectionModel selectionModel = table.getSelectionModel(); - selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - tableModel.installSelectionListener(table); - - new BasketsAutotSelectRowAndShowPopupAction(ui, ui.getBasketsPane(), table, ui.getBasketsPopup()); - - } - - { - // init branchlines table - JTable table = ui.getBranchlinesTable(); - - UIHelper.setI18nTableHeaderRenderer(table, - n("observe.content.longlineDetailComposition.branchlinesTable.settingIdentifier"), - n("observe.content.longlineDetailComposition.branchlinesTable.settingIdentifier.tip"), - n("observe.content.longlineDetailComposition.branchlinesTable.haulingIdentifier"), - n("observe.content.longlineDetailComposition.branchlinesTable.haulingIdentifier.tip"), - n("observe.content.longlineDetailComposition.branchlinesTable.branchlineLength"), - n("observe.content.longlineDetailComposition.branchlinesTable.branchlineLength.tip"), - n("observe.content.longlineDetailComposition.branchlinesTable.tracelineLength"), - n("observe.content.longlineDetailComposition.branchlinesTable.tracelineLength.tip")); - - TableCellRenderer renderer = table.getDefaultRenderer(Object.class); - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - - UIHelper.setTableColumnEditor(table, 1, newIntegerColumnEditor(table)); - UIHelper.setTableColumnEditor(table, 2, newFloatColumnEditor(table)); - UIHelper.setTableColumnEditor(table, 3, newFloatColumnEditor(table)); - - BranchlinesTableModel tableModel = model.getBranchlinesTableModel(); - tableModel.installTableKeyListener(table); - tableModel.installTableFocusListener(table); - - ListSelectionModel selectionModel = table.getSelectionModel(); - selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - tableModel.installSelectionListener(table); - - new BranchlinesAutotSelectRowAndShowPopupAction(ui, ui.getBranchlinesPane(), table, ui.getBranchlinesPopup()); - - } - - { - - // init branchlineDetail tab - BranchlineUI compositionUI = ui.getBranchlineDetailUI(); - compositionUI.init(); - Container parent = ui.getBranchlineDetailPanel(); - parent .removeAll(); - parent.add(compositionUI.getBody()); - - } - - } - - - static class SectionTemplatesAutotSelectRowAndShowPopupAction extends AutotSelectRowAndShowPopupActionSupport { - - private final LonglineDetailCompositionUI ui; - - public SectionTemplatesAutotSelectRowAndShowPopupAction(LonglineDetailCompositionUI ui, - JScrollPane pane, - JTable table, - JPopupMenu popup) { - super(pane, table, popup); - this.ui = ui; - } - - @Override - protected void beforeOpenPopup(int modelRowIndex, int modelColumnIndex) { - - EditableTableModelSupport model = (EditableTableModelSupport) getTable().getModel(); - - boolean canDelete = !model.isSelectionEmpty(); - - if (canDelete) { - - // check also that the row is not empty - Serializable selectedData = model.getSelectedRow(); - canDelete = model.isRowNotEmpty(selectedData); - - } - - ui.getDeleteSelectedSectionTemplate().setEnabled(canDelete); - - } - - } - - static class SectionsAutotSelectRowAndShowPopupAction extends AutotSelectRowAndShowPopupActionSupport { - - private final LonglineDetailCompositionUI ui; - - public SectionsAutotSelectRowAndShowPopupAction(LonglineDetailCompositionUI ui, - JScrollPane pane, - JTable table, - JPopupMenu popup) { - super(pane, table, popup); - this.ui = ui; - } - - @Override - protected void beforeOpenPopup(int modelRowIndex, int modelColumnIndex) { - - EditableTableModelSupport model = (EditableTableModelSupport) getTable().getModel(); - - boolean selectionNotEmpty = !model.isSelectionEmpty(); - boolean selectedRowIsNotEmpty = false; - - if (selectionNotEmpty) { - - Serializable selectedData = model.getSelectedRow(); - selectedRowIsNotEmpty = model.isRowNotEmpty(selectedData); - - } - - boolean canDelete = false; - boolean canInsertBefore = true; - boolean canInsertAfter = true; - - if (selectionNotEmpty) { - - // can delete only a non empty selected row - canDelete = selectedRowIsNotEmpty; - - // won't add before an empty row - canInsertBefore = selectedRowIsNotEmpty; - - // won't after before an empty row - canInsertAfter = selectedRowIsNotEmpty; - - } - - ui.getDeleteSelectedSection().setEnabled(canDelete); - ui.getInsertBeforeSelectedSection().setEnabled(canInsertBefore); - ui.getInsertAfterSelectedSection().setEnabled(canInsertAfter); - - } - - } - - static class BasketsAutotSelectRowAndShowPopupAction extends AutotSelectRowAndShowPopupActionSupport { - - private final LonglineDetailCompositionUI ui; - - public BasketsAutotSelectRowAndShowPopupAction(LonglineDetailCompositionUI ui, - JScrollPane pane, - JTable table, - JPopupMenu popup) { - super(pane, table, popup); - this.ui = ui; - } - - @Override - protected void beforeOpenPopup(int modelRowIndex, int modelColumnIndex) { - - EditableTableModelSupport model = (EditableTableModelSupport) getTable().getModel(); - - boolean selectionNotEmpty = !model.isSelectionEmpty(); - boolean selectedRowIsNotEmpty = false; - - if (selectionNotEmpty) { - - Serializable selectedData = model.getSelectedRow(); - selectedRowIsNotEmpty = model.isRowNotEmpty(selectedData); - - } - - boolean canDelete = false; - boolean canInsertBefore = true; - boolean canInsertAfter = true; - - if (selectionNotEmpty) { - - // can delete only a non empty selected row - canDelete = selectedRowIsNotEmpty; - - // won't add before an empty row - canInsertBefore = selectedRowIsNotEmpty; - - // won't after before an empty row - canInsertAfter = selectedRowIsNotEmpty; - - } - - ui.getDeleteSelectedBasket().setEnabled(canDelete); - ui.getInsertBeforeSelectedBasket().setEnabled(canInsertBefore); - ui.getInsertAfterSelectedBasket().setEnabled(canInsertAfter); - - } - - } - - static class BranchlinesAutotSelectRowAndShowPopupAction extends AutotSelectRowAndShowPopupActionSupport { - - private final LonglineDetailCompositionUI ui; - - public BranchlinesAutotSelectRowAndShowPopupAction(LonglineDetailCompositionUI ui, - JScrollPane pane, - JTable table, - JPopupMenu popup) { - super(pane, table, popup); - this.ui = ui; - } - - @Override - protected void beforeOpenPopup(int modelRowIndex, int modelColumnIndex) { - - EditableTableModelSupport model = (EditableTableModelSupport) getTable().getModel(); - - boolean selectionNotEmpty = !model.isSelectionEmpty(); - boolean selectedRowIsNotEmpty = false; - - if (selectionNotEmpty) { - - Serializable selectedData = model.getSelectedRow(); - selectedRowIsNotEmpty = model.isRowNotEmpty(selectedData); - - } - - boolean canDelete = false; - boolean canInsertBefore = true; - boolean canInsertAfter = true; - - if (selectionNotEmpty) { - - // can delete only a non empty selected row - canDelete = selectedRowIsNotEmpty; - - // won't add before an empty row - canInsertBefore = selectedRowIsNotEmpty; - - // won't after before an empty row - canInsertAfter = selectedRowIsNotEmpty; - - } - - ui.getDeleteSelectedBranchline().setEnabled(canDelete); - ui.getInsertBeforeSelectedBranchline().setEnabled(canInsertBefore); - ui.getInsertAfterSelectedBranchline().setEnabled(canInsertAfter); - - } - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionUIModel.java deleted file mode 100644 index 1570c25..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionUIModel.java +++ /dev/null @@ -1,132 +0,0 @@ -package fr.ird.observe.ui.content.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.longline.SetLonglineDetailCompositionDto; -import fr.ird.observe.ui.content.ContentUIModel; - -/** - * Created on 12/5/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.8 - */ -public class LonglineDetailCompositionUIModel extends ContentUIModel<SetLonglineDetailCompositionDto> { - - public static final String PROPERTY_CAN_GENERATE = "canGenerate"; - - public static final String PROPERTY_GENERATE_TAB_VALID = "generateTabValid"; - - public static final String PROPERTY_COMPOSITION_TAB_VALID = "compositionTabValid"; - - public static final String PROPERTY_BRANCHLINE_DETAIL_TAB_VALID = "branchlineDetailTabValid"; - - private static final long serialVersionUID = 1L; - - protected final SectionTemplatesTableModel sectionTemplatesTableModel; - - protected final SectionsTableModel sectionsTableModel; - - protected final BasketsTableModel basketsTableModel; - - protected final BranchlinesTableModel branchlinesTableModel; - - protected boolean canGenerate; - - protected boolean generateTabValid; - - protected boolean compositionTabValid; - - protected boolean branchlineDetailTabValid; - - public LonglineDetailCompositionUIModel() { - - super(SetLonglineDetailCompositionDto.class); - this.sectionTemplatesTableModel = new SectionTemplatesTableModel(); - this.sectionsTableModel = new SectionsTableModel(this); - this.basketsTableModel = new BasketsTableModel(this); - this.branchlinesTableModel = new BranchlinesTableModel(this); - } - - public SectionTemplatesTableModel getSectionTemplatesTableModel() { - return sectionTemplatesTableModel; - } - - public BasketsTableModel getBasketsTableModel() { - return basketsTableModel; - } - - public SectionsTableModel getSectionsTableModel() { - return sectionsTableModel; - } - - public BranchlinesTableModel getBranchlinesTableModel() { - return branchlinesTableModel; - } - - public boolean isHaulingdirectionSameAsSettings() { - Boolean haulingDirectionSameAsSetting = getBean().getHaulingDirectionSameAsSetting(); - return haulingDirectionSameAsSetting != null && haulingDirectionSameAsSetting; - } - - public boolean isGenerateHaulingIds() { - return getBean().getHaulingBreaks() == 0; - } - - public boolean isCanGenerate() { - return canGenerate; - } - - public void setCanGenerate(boolean canGenerate) { - this.canGenerate = canGenerate; - firePropertyChange(PROPERTY_CAN_GENERATE, null, canGenerate); - } - - public boolean isBranchlineDetailTabValid() { - return branchlineDetailTabValid; - } - - public void setBranchlineDetailTabValid(boolean branchlineDetailTabValid) { - this.branchlineDetailTabValid = branchlineDetailTabValid; - firePropertyChange(PROPERTY_BRANCHLINE_DETAIL_TAB_VALID, null, branchlineDetailTabValid); - } - - public boolean isCompositionTabValid() { - return compositionTabValid; - } - - public void setCompositionTabValid(boolean compositionTabValid) { - this.compositionTabValid = compositionTabValid; - firePropertyChange(PROPERTY_COMPOSITION_TAB_VALID, null, compositionTabValid); - } - - public boolean isGenerateTabValid() { - return generateTabValid; - } - - public void setGenerateTabValid(boolean generateTabValid) { - this.generateTabValid = generateTabValid; - firePropertyChange(PROPERTY_GENERATE_TAB_VALID, null, generateTabValid); - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionUIValidationHelper.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionUIValidationHelper.java deleted file mode 100644 index fcec8a8..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionUIValidationHelper.java +++ /dev/null @@ -1,165 +0,0 @@ -package fr.ird.observe.ui.content.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.ImmutableMap; -import com.google.common.collect.ImmutableSet; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.services.dto.longline.BasketDto; -import fr.ird.observe.services.dto.longline.BranchlineDto; -import fr.ird.observe.services.dto.longline.SectionDto; -import fr.ird.observe.services.dto.longline.SectionWithTemplate; -import fr.ird.observe.ui.util.ObserveSwingValidatorMessageTableModel; -import jaxx.runtime.validator.swing.SwingValidator; -import jaxx.runtime.validator.swing.SwingValidatorMessage; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.validator.bean.simple.SimpleBeanValidator; - -import javax.swing.JComponent; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** - * Created on 3/18/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.15 - */ -public class LonglineDetailCompositionUIValidationHelper { - - /** Logger. */ - private static final Log log = LogFactory.getLog(LonglineDetailCompositionUIValidationHelper.class); - - private final LonglineDetailCompositionUIModel model; - - private final ObserveSwingValidatorMessageTableModel errorTableModel; - - private boolean objectValueAdjusting; - - private final LonglineDetailCompositionValidatorService validatorService; - - private final Set<SwingValidator> validators; - - public LonglineDetailCompositionUIValidationHelper(LonglineDetailCompositionUI ui, DecoratorService decoratorService) { - this.model = ui.getModel(); - this.errorTableModel = (ObserveSwingValidatorMessageTableModel) ui.getErrorTableModel(); - SwingValidator<SectionDto> sectionValidator = ui.getSectionValidator(); - SwingValidator<BasketDto> basketValidator = ui.getBasketValidator(); - SwingValidator<BranchlineDto> branchlineValidator = ui.getBranchlineValidator(); - - this.validators = ImmutableSet.<SwingValidator>builder().add( - sectionValidator, - basketValidator, - branchlineValidator - ).build(); - Map<SwingValidator, JComponent> validatorEditor = ImmutableMap.<SwingValidator, JComponent>builder() - .put(sectionValidator, ui.getSectionsPane()) - .put(basketValidator, ui.getBasketsPane()) - .put(branchlineValidator, ui.getBranchlinesPane()) - .build(); - - this.validatorService = new LonglineDetailCompositionValidatorService( - sectionValidator, - basketValidator, - branchlineValidator, - validatorEditor, - decoratorService - ); - } - - public void whenSectionChanged() { - - if (!objectValueAdjusting) { - - if (log.isInfoEnabled()) { - log.info("Rebuild messages, section model changes."); - } - - List<SectionWithTemplate> notEmptyData = model.getSectionsTableModel().getNotEmptyData(); - List<SwingValidatorMessage> messages = validatorService.validateSections(notEmptyData); - - removeOldMessages(); - - errorTableModel.addMessages(messages); - - model.setCompositionTabValid(messages.isEmpty()); - - } - } - - public void whenBasketChanged() { - - if (!objectValueAdjusting) { - - if (log.isInfoEnabled()) { - log.info("Rebuild messages, basket model changes."); - } - List<SectionWithTemplate> notEmptyData = model.getSectionsTableModel().getNotEmptyData(); - List<SwingValidatorMessage> messages = validatorService.validateSections(notEmptyData); - - removeOldMessages(); - - errorTableModel.addMessages(messages); - - model.setCompositionTabValid(messages.isEmpty()); - - } - - } - - public void whenBranchlineChanged() { - - if (!objectValueAdjusting) { - - if (log.isInfoEnabled()) { - log.info("Rebuild messages, branchline model changes."); - } - - List<SectionWithTemplate> notEmptyData = model.getSectionsTableModel().getNotEmptyData(); - List<SwingValidatorMessage> messages = validatorService.validateSections(notEmptyData); - - removeOldMessages(); - - errorTableModel.addMessages(messages); - - model.setCompositionTabValid(messages.isEmpty()); - - } - - } - - public void removeOldMessages() { - errorTableModel.removeMessages(input -> { - SimpleBeanValidator<?> validator = input.getValidator(); - boolean remove = validators.contains(validator); - return remove; - }); - } - - public void setObjectValueAdjusting(boolean objectValueAdjusting) { - this.objectValueAdjusting = objectValueAdjusting; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionValidationContext.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionValidationContext.java deleted file mode 100644 index 385739e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionValidationContext.java +++ /dev/null @@ -1,116 +0,0 @@ -package fr.ird.observe.ui.content.impl.longline; - -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.services.dto.longline.BasketDto; -import fr.ird.observe.services.dto.longline.BranchlineDto; -import fr.ird.observe.services.dto.longline.SectionDto; -import jaxx.runtime.validator.swing.SwingValidator; -import jaxx.runtime.validator.swing.SwingValidatorMessage; -import org.nuiton.validator.NuitonValidatorScope; -import org.nuiton.validator.bean.simple.SimpleBeanValidatorEvent; -import org.nuiton.validator.bean.simple.SimpleBeanValidatorListener; - -import javax.swing.JComponent; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 09/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - */ -public class LonglineDetailCompositionValidationContext implements SimpleBeanValidatorListener { - - SectionDto section; - - BasketDto basket; - - BranchlineDto branchline; - - String contextLabel; - - final List<SwingValidatorMessage> messages; - - final DecoratorService decoratorService; - - private final Map<SwingValidator, JComponent> validatorEditors; - - LonglineDetailCompositionValidationContext(DecoratorService decoratorService, Map<SwingValidator, JComponent> validatorEditors) { - this.decoratorService = decoratorService; - this.validatorEditors = validatorEditors; - this.messages = new ArrayList<>(); - } - - public List<SwingValidatorMessage> getMessages() { - return messages; - } - - public void setSection(SectionDto section) { - this.section = section; - this.basket = null; - this.branchline = null; - updateContextLabel(); - } - - public void setBasket(BasketDto basket) { - this.basket = basket; - this.branchline = null; - updateContextLabel(); - } - - public void setBranchline(BranchlineDto branchline) { - this.branchline = branchline; - updateContextLabel(); - } - - protected void updateContextLabel() { - - contextLabel = ""; - if (section != null) { - contextLabel += "S " + section.getSettingIdentifier(); - if (basket != null) { - contextLabel += " Ba " + basket.getSettingIdentifier(); - if (branchline != null) { - contextLabel += " Br " + branchline.getSettingIdentifier(); - } - } - } - - } - - @Override - public void onFieldChanged(SimpleBeanValidatorEvent event) { - - String[] messagesToAdd = event.getMessagesToAdd(); - if (messagesToAdd != null) { - - String field = event.getField(); - NuitonValidatorScope scope = event.getScope(); - SwingValidator<?> validator = (SwingValidator<?>) event.getSource(); - - for (String messageToAdd : messagesToAdd) { - addMessage(validator, scope, field, messageToAdd); - } - - } - - } - - public void addMessage(SwingValidator validator, NuitonValidatorScope scope, String field, String messageToAdd) { - - String propertyLabel = DecoratorService.getPropertyLabel(field); - SwingValidatorMessage message = new SwingValidatorMessage( - validator, - contextLabel + " - " + t(propertyLabel), - messageToAdd, - scope, - validatorEditors.get(validator) - ); - messages.add(message); - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionValidatorService.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionValidatorService.java deleted file mode 100644 index 4836516..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionValidatorService.java +++ /dev/null @@ -1,155 +0,0 @@ -package fr.ird.observe.ui.content.impl.longline; - -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.services.dto.longline.BasketDto; -import fr.ird.observe.services.dto.longline.BranchlineDto; -import fr.ird.observe.services.dto.longline.SectionDto; -import jaxx.runtime.validator.swing.SwingValidator; -import jaxx.runtime.validator.swing.SwingValidatorMessage; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.JComponent; -import java.util.List; -import java.util.Map; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 09/08/16. - * - * @author Tony Chemit - chemit@codelutin.com - */ -public class LonglineDetailCompositionValidatorService { - - private final SwingValidator<SectionDto> sectionValidator; - - private final SwingValidator<BasketDto> basketValidator; - - private final SwingValidator<BranchlineDto> branchlineValidator; - - private final DecoratorService decoratorService; - - private final Map<SwingValidator, JComponent> validatorEditors; - - public LonglineDetailCompositionValidatorService(SwingValidator<SectionDto> sectionValidator, - SwingValidator<BasketDto> basketValidator, - SwingValidator<BranchlineDto> branchlineValidator, - Map<SwingValidator, JComponent> validatorEditors, - DecoratorService decoratorService) { - this.sectionValidator = sectionValidator; - this.basketValidator = basketValidator; - this.branchlineValidator = branchlineValidator; - this.validatorEditors = validatorEditors; - this.decoratorService = decoratorService; - - } - - public List<SwingValidatorMessage> validateSections(List<? extends SectionDto> sections) { - - LonglineDetailCompositionValidationContext validationContext = new LonglineDetailCompositionValidationContext(decoratorService, validatorEditors); - - addListener(validationContext); - - try { - - for (SectionDto section : sections) { - - validateSection(validationContext, section); - - } - - } finally { - - removeListener(validationContext); - - } - - return validationContext.getMessages(); - - } - - protected void validateSection(LonglineDetailCompositionValidationContext validationContext, SectionDto section) { - - validationContext.setSection(section); - validationContext.setBasket(null); - validationContext.setBranchline(null); - - sectionValidator.setBean(null); - sectionValidator.setBean(section); - - if (!section.isBasketEmpty()) { - - BasketDto previousBasket = null; - - for (BasketDto basket : section.getBasket()) { - - if (previousBasket != null) { - - // validate previousBasket.floatline2Length = basket.floatline1Length - Float previousBasketFloatline2Length = previousBasket.getFloatline2Length(); - Float basketFloatline1Length = basket.getFloatline1Length(); - if (previousBasketFloatline2Length != null - && basketFloatline1Length != null - && Math.abs(previousBasketFloatline2Length - basketFloatline1Length) > 0.001f) { - - validationContext.addMessage(basketValidator, NuitonValidatorScope.ERROR, "floatline2Length", t("observe.content.basket.invalid.nextFloatline1Length", previousBasketFloatline2Length, basketFloatline1Length)); - - } - } - - validateBasket(validationContext, basket); - - previousBasket = basket; - - } - } - - } - - protected void validateBasket(LonglineDetailCompositionValidationContext validationContext, BasketDto basket) { - - validationContext.setBranchline(null); - validationContext.setBasket(basket); - - basketValidator.setBean(null); - basketValidator.setBean(basket); - - if (!basket.isBranchlineEmpty()) { - - for (BranchlineDto branchline : basket.getBranchline()) { - - validateBranchline(validationContext, branchline); - - } - } - - validationContext.setBranchline(null); - - } - - protected void validateBranchline(LonglineDetailCompositionValidationContext validationContext, BranchlineDto branchline) { - - validationContext.setBranchline(branchline); - branchlineValidator.setBean(null); - branchlineValidator.setBean(branchline); - - - } - - protected void addListener(LonglineDetailCompositionValidationContext validationContext) { - - sectionValidator.addSimpleBeanValidatorListener(validationContext); - basketValidator.addSimpleBeanValidatorListener(validationContext); - branchlineValidator.addSimpleBeanValidatorListener(validationContext); - - } - - protected void removeListener(LonglineDetailCompositionValidationContext validationContext) { - - sectionValidator.removeSimpleBeanValidatorListener(validationContext); - basketValidator.removeSimpleBeanValidatorListener(validationContext); - branchlineValidator.removeSimpleBeanValidatorListener(validationContext); - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineGlobalCompositionUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineGlobalCompositionUI.jaxx deleted file mode 100644 index 66380e6..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineGlobalCompositionUI.jaxx +++ /dev/null @@ -1,157 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ContentUI superGenericType='SetLonglineGlobalCompositionDto' - contentTitle='{n("observe.content.longlineGlobalComposition.title")}'> - - <import> - fr.ird.observe.ObserveSwingApplicationContext - fr.ird.observe.services.dto.CommentableDto - fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.longline.MitigationTypeDto - fr.ird.observe.ui.actions.shared.ResetEditUIAction - fr.ird.observe.ui.actions.shared.SaveEditUIAction - fr.ird.observe.ui.content.table.impl.longline.BaitsCompositionUI - fr.ird.observe.ui.content.table.impl.longline.BaitsCompositionUIModel - fr.ird.observe.ui.content.table.impl.longline.BranchlinesCompositionUI - fr.ird.observe.ui.content.table.impl.longline.BranchlinesCompositionUIModel - fr.ird.observe.ui.content.table.impl.longline.FloatlinesCompositionUI - fr.ird.observe.ui.content.table.impl.longline.FloatlinesCompositionUIModel - fr.ird.observe.ui.content.table.impl.longline.HooksCompositionUI - fr.ird.observe.ui.content.table.impl.longline.HooksCompositionUIModel - - org.nuiton.jaxx.widgets.select.FilterableDoubleList - - java.awt.Dimension - javax.swing.JLabel - java.util.Collection - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - static org.nuiton.i18n.I18n.t - </import> - - <style source="../../Common.jcss"/> - - <!-- handler --> - <LonglineGlobalCompositionUIHandler id='handler'/> - - <!-- model --> - <LonglineGlobalCompositionUIModel id='model'/> - - <!-- edit bean --> - <SetLonglineGlobalCompositionDto id='bean'/> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' beanClass='fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto' - errorTableModel='{getErrorTableModel()}' context='ui-update-globalComposition'> - </BeanValidator> - - <!-- formulaire --> - <JPanel id="body" layout='{new BorderLayout()}'> - - <Table insets="0" fill="both" constraints='BorderLayout.CENTER'> - <row> - <cell anchor="north"> - <JTabbedPane id='fishingOperationTabPane'> - - <!-- floatlinesComposition --> - <tab id='floatlinesCompositionTab'> - <JPanel id="floatlinesCompositionPanel" layout='{new BorderLayout()}'> - <FloatlinesCompositionUI id="floatlinesCompositionUI" - constructorParams="ObserveSwingApplicationContext.get().getMainUI()"/> - </JPanel> - </tab> - - <!-- branchlinesComposition --> - <tab id='branchlinesCompositionTab'> - <JPanel id="branchlinesCompositionPanel" layout='{new BorderLayout()}'> - <BranchlinesCompositionUI id="branchlinesCompositionUI" - constructorParams="ObserveSwingApplicationContext.get().getMainUI()"/> - </JPanel> - </tab> - - <!-- hooksComposition --> - <tab id='hooksCompositionTab'> - <JPanel id="hooksCompositionPanel" layout='{new BorderLayout()}'> - <HooksCompositionUI id="hooksCompositionUI" - constructorParams="ObserveSwingApplicationContext.get().getMainUI()"/> - </JPanel> - </tab> - - <!-- baitsComposition --> - <tab id='baitsCompositionTab'> - <JPanel id="baitsCompositionPanel" layout='{new BorderLayout()}'> - <BaitsCompositionUI id="baitsCompositionUI" - constructorParams="ObserveSwingApplicationContext.get().getMainUI()"/> - </JPanel> - </tab> - - <tab id='mitigationTypeTab'> - - <!-- mitigationType --> - <JPanel layout='{new BorderLayout()}'> - <Table fill='both' constraints='BorderLayout.NORTH'> - <row> - <cell weighty="1" weightx="1"> - <FilterableDoubleList id='mitigationType' genericType='ReferentialReference<MitigationTypeDto>' _entityClass='MitigationTypeDto.class'/> - </cell> - </row> - </Table> - </JPanel> - - </tab> - - </JTabbedPane> - </cell> - </row> - - <row> - <cell fill="both" weighty="1" weightx="1"> - <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2'/> - </JScrollPane> - </cell> - </row> - - </Table> - </JPanel> - - <!-- actions --> - <Table id="actions" fill='both' weightx='1' insets='0'> - <row> - <cell weightx="0.5"> - <JButton id='reset'/> - </cell> - <cell weightx="0.5"> - <JButton id='save'/> - </cell> - </row> - </Table> - - <FloatlinesCompositionUIModel id="floatlinesCompositionModel" initializer="floatlinesCompositionUI.getModel()"/> - <BranchlinesCompositionUIModel id="branchlinesCompositionModel" initializer="branchlinesCompositionUI.getModel()"/> - <HooksCompositionUIModel id="hooksCompositionModel" initializer="hooksCompositionUI.getModel()"/> - <BaitsCompositionUIModel id="baitsCompositionModel" initializer="baitsCompositionUI.getModel()"/> - -</fr.ird.observe.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineGlobalCompositionUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineGlobalCompositionUIHandler.java deleted file mode 100644 index e2a4a6c..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineGlobalCompositionUIHandler.java +++ /dev/null @@ -1,248 +0,0 @@ -package fr.ird.observe.ui.content.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.longline.ActivityLonglineDto; -import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto; -import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDtos; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.service.longline.SetLonglineGlobalCompositionService; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.ContentUIHandler; -import fr.ird.observe.ui.content.table.impl.longline.BaitsCompositionUI; -import fr.ird.observe.ui.content.table.impl.longline.BaitsCompositionUIModel; -import fr.ird.observe.ui.content.table.impl.longline.BranchlinesCompositionUI; -import fr.ird.observe.ui.content.table.impl.longline.BranchlinesCompositionUIModel; -import fr.ird.observe.ui.content.table.impl.longline.FloatlinesCompositionUI; -import fr.ird.observe.ui.content.table.impl.longline.FloatlinesCompositionUIModel; -import fr.ird.observe.ui.content.table.impl.longline.HooksCompositionUI; -import fr.ird.observe.ui.content.table.impl.longline.HooksCompositionUIModel; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.validator.NuitonValidatorScope; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 12/5/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.8 - */ -public class LonglineGlobalCompositionUIHandler extends ContentUIHandler<SetLonglineGlobalCompositionDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(LonglineGlobalCompositionUIHandler.class); - - public LonglineGlobalCompositionUIHandler(LonglineGlobalCompositionUI ui) { - super(ui, DataContextType.ActivityLongline, DataContextType.SetLongline); - } - - @Override - public LonglineGlobalCompositionUI getUi() { - return (LonglineGlobalCompositionUI) super.getUi(); - } - - @Override - protected boolean computeCanWrite(ObserveSwingDataSource source) { - return source.canWriteData(); - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - String activityId = dataContext.getSelectedActivityLonglineId(); - - if (getOpenDataManager().isOpenActivityLongline(activityId)) { - - // l'activité est ouverte, mode édition - return ContentMode.UPDATE; - } - - // l'activité n'est pas ouverte, mode lecture - addMessage(getUi(), - NuitonValidatorScope.INFO, - getEntityLabel(ActivityLonglineDto.class), - t("observe.storage.activityLongline.message.not.open")); - return ContentMode.READ; - } - - @Override - public void initUI() { - super.initUI(); - { - // init floatlinesComposition tab - FloatlinesCompositionUI compositionUI = getUi().getFloatlinesCompositionUI(); - compositionUI.init(); - getUi().getFloatlinesCompositionPanel().remove(compositionUI); - getUi().getFloatlinesCompositionPanel().add(compositionUI.getBody()); - } - - { - // init branchlinesComposition tab - BranchlinesCompositionUI compositionUI = getUi().getBranchlinesCompositionUI(); - compositionUI.init(); - getUi().getBranchlinesCompositionPanel().remove(compositionUI); - getUi().getBranchlinesCompositionPanel().add(compositionUI.getBody()); - } - - { - // init hooksComposition tab - HooksCompositionUI compositionUI = getUi().getHooksCompositionUI(); - compositionUI.init(); - getUi().getHooksCompositionPanel().remove(compositionUI); - getUi().getHooksCompositionPanel().add(compositionUI.getBody()); - } - - { - // init baitsComposition tab - BaitsCompositionUI compositionUI = getUi().getBaitsCompositionUI(); - compositionUI.init(); - getUi().getBaitsCompositionPanel().remove(compositionUI); - getUi().getBaitsCompositionPanel().add(compositionUI.getBody()); - } - - } - - @Override - public void openUI() { - super.openUI(); - - String activityId = getSelectedParentId(); - String setId = getSelectedId(); - - if (log.isInfoEnabled()) { - log.info("activityId = " + activityId); - log.info("setId = " + setId); - } - ContentMode mode = computeContentMode(); - - // update mode - Form<SetLonglineGlobalCompositionDto> form = getSetLonglineGlobalCompositionService().loadForm(setId); - - loadReferentialReferenceSetsInModel(form); - - getModel().setForm(form); - SetLonglineGlobalCompositionDtos.copySetLonglineGlobalCompositionDto(form.getObject(), getBean()); - - // utilisation du mode requis - setContentMode(mode); - - if (mode != ContentMode.READ) { - getUi().startEdit(null); - } - - { - // open floatlinesComposition tab - FloatlinesCompositionUIModel floatlinesCompositionModel = getUi().getFloatlinesCompositionModel(); - floatlinesCompositionModel.setReferentialReferenceSets(getModel().getReferentialReferenceSets()); - floatlinesCompositionModel.setForm(form); - SetLonglineGlobalCompositionDtos.copySetLonglineGlobalCompositionDto(form.getObject(), floatlinesCompositionModel.getBean()); - - FloatlinesCompositionUI compositionUI = getUi().getFloatlinesCompositionUI(); - compositionUI.open(); - - } - - { - // open branchlinesComposition tab - BranchlinesCompositionUIModel branchlinesCompositionModel = getUi().getBranchlinesCompositionModel(); - branchlinesCompositionModel.setReferentialReferenceSets(getModel().getReferentialReferenceSets()); - branchlinesCompositionModel.setForm(form); - SetLonglineGlobalCompositionDtos.copySetLonglineGlobalCompositionDto(form.getObject(), branchlinesCompositionModel.getBean()); - - BranchlinesCompositionUI compositionUI = getUi().getBranchlinesCompositionUI(); - compositionUI.open(); - - } - - { - // open hooksComposition tab - HooksCompositionUIModel hooksCompositionModel = getUi().getHooksCompositionModel(); - hooksCompositionModel.setReferentialReferenceSets(getModel().getReferentialReferenceSets()); - hooksCompositionModel.setForm(form); - SetLonglineGlobalCompositionDtos.copySetLonglineGlobalCompositionDto(form.getObject(), hooksCompositionModel.getBean()); - - HooksCompositionUI compositionUI = getUi().getHooksCompositionUI(); - compositionUI.open(); - - } - - { - // open baitsComposition tab - BaitsCompositionUIModel baitsCompositionModel = getUi().getBaitsCompositionModel(); - baitsCompositionModel.setReferentialReferenceSets(getModel().getReferentialReferenceSets()); - baitsCompositionModel.setForm(form); - SetLonglineGlobalCompositionDtos.copySetLonglineGlobalCompositionDto(form.getObject(), baitsCompositionModel.getBean()); - - BaitsCompositionUI compositionUI = getUi().getBaitsCompositionUI(); - compositionUI.open(); - - } - - } - - @Override - public void startEditUI(String... binding) { - LonglineGlobalCompositionUIModel model = (LonglineGlobalCompositionUIModel) getModel(); - addInfoMessage(t("observe.content.longlineGlobalComposition.message.updating")); - - super.startEditUI(LonglineGlobalCompositionUI.BINDING_COMMENT2_TEXT); - model.setModified(false); - } - - @Override - protected boolean doSave(SetLonglineGlobalCompositionDto bean) throws Exception { - - bean.setFloatlinesComposition(getUi().getFloatlinesCompositionModel().getBean().getFloatlinesComposition()); - bean.setBranchlinesComposition(getUi().getBranchlinesCompositionModel().getBean().getBranchlinesComposition()); - bean.setHooksComposition(getUi().getHooksCompositionModel().getBean().getHooksComposition()); - bean.setBaitsComposition(getUi().getBaitsCompositionModel().getBean().getBaitsComposition()); - - SaveResultDto saveResult = getSetLonglineGlobalCompositionService().save(bean); - saveResult.toDto(bean); - - return true; - } - - @Override - protected void afterSave(boolean refresh) { - super.afterSave(refresh); - - getUi().getFloatlinesCompositionUI().getHandler().afterSave(refresh); - getUi().getBranchlinesCompositionUI().getHandler().afterSave(refresh); - getUi().getHooksCompositionUI().getHandler().afterSave(refresh); - getUi().getBaitsCompositionUI().getHandler().afterSave(refresh); - } - - protected SetLonglineGlobalCompositionService getSetLonglineGlobalCompositionService() { - - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newSetLonglineGlobalCompositionService(); - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineGlobalCompositionUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineGlobalCompositionUIModel.java deleted file mode 100644 index 4b1995d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/LonglineGlobalCompositionUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto; -import fr.ird.observe.ui.content.ContentUIModel; - -/** - * Created on 12/5/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.8 - */ -public class LonglineGlobalCompositionUIModel extends ContentUIModel<SetLonglineGlobalCompositionDto> { - - private static final long serialVersionUID = 1L; - - public LonglineGlobalCompositionUIModel() { - super(SetLonglineGlobalCompositionDto.class); - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/SectionTemplatesTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/SectionTemplatesTableModel.java deleted file mode 100644 index ca2fd65..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/SectionTemplatesTableModel.java +++ /dev/null @@ -1,158 +0,0 @@ -package fr.ird.observe.ui.content.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.longline.SectionTemplate; -import fr.ird.observe.ui.util.table.EditableTableModelSupport; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.HashSet; -import java.util.Set; - -/** - * Created on 12/11/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.10 - */ -public class SectionTemplatesTableModel extends EditableTableModelSupport<SectionTemplate> { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(SectionTemplatesTableModel.class); - - public SectionTemplatesTableModel() { - super(true); - } - - @Override - public boolean isRowNotEmpty(SectionTemplate row) { - return !(StringUtils.isBlank(row.getId()) && StringUtils.isBlank(row.getFloatlineLengths())); - } - - @Override - public boolean isRowValid(SectionTemplate row) { - return StringUtils.isNotBlank(row.getId()) && - StringUtils.isNotBlank(row.getFloatlineLengths()) && - row.isFloatlineLengthsValid(); - } - - @Override - protected SectionTemplate createNewRow() { - return new SectionTemplate(); - } - - @Override - public int getColumnCount() { - return 2; - } - - @Override - public Object getValueAt(int rowIndex, int columnIndex) { - SectionTemplate measure = data.get(rowIndex); - Object result; - - switch (columnIndex) { - case 0: - - result = measure.getId(); - break; - - case 1: - - result = measure.getFloatlineLengths(); - break; - - default: - throw new IllegalStateException("Can't come here"); - } - - return result; - } - - @Override - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - SectionTemplate measure = data.get(rowIndex); - - switch (columnIndex) { - case 0: - - measure.setId((String) aValue); - break; - - case 1: - - measure.setFloatlineLengths((String) aValue); - break; - - default: - throw new IllegalStateException("Can't come here"); - } - - setModified(true); - - } - - @Override - protected boolean computeValidState() { - - boolean newValidState = super.computeValidState(); - if (newValidState) { - - // check that we are using unique ids - Set<String> ids = new HashSet<>(); - for (SectionTemplate sectionTemplate : data) { - - boolean add = ids.add(sectionTemplate.getId()); - if (!add) { - - if (log.isWarnEnabled()) { - log.warn("Template identifiants (" + sectionTemplate.getId() + ") are not unique."); - } - newValidState = false; - break; - } - - } - - } - return newValidState; - - } - - @Override - protected boolean isCanCreateNewRow(int rowIndex) { - - boolean canCreateNewRow = super.isCanCreateNewRow(rowIndex); - if (canCreateNewRow) { - - // add a new row if and only if all rows are valid - canCreateNewRow = computeValidState(); - } - return canCreateNewRow; - - } -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/SectionsTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/SectionsTableModel.java deleted file mode 100644 index 4b416e7..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/SectionsTableModel.java +++ /dev/null @@ -1,180 +0,0 @@ -package fr.ird.observe.ui.content.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.longline.SectionTemplate; -import fr.ird.observe.services.dto.longline.SectionWithTemplate; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Created on 12/11/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.10 - */ -public class SectionsTableModel extends LonglineCompositionTableModelSupport<SectionWithTemplate> { - - public static final String TEMPLATE_PROPERTY = "template"; - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(SectionsTableModel.class); - - public SectionsTableModel(LonglineDetailCompositionUIModel model) { - super(model); - } - - @Override - protected SectionWithTemplate createNewRow() { - return new SectionWithTemplate(); - } - - @Override - public int getColumnCount() { - return 3; - } - - @Override - public boolean isCellEditable(int rowIndex, int columnIndex) { - - boolean result; - - switch (columnIndex) { - - case 0: - - // can never edit setting id - result = false; - break; - - case 1: - - // can edit hauling id if and only if set has hauling breaks - result = !isGenerateHaulingIds(); - break; - - case 2: - - // can change template if in generate mode - result = isCanGenerate(); - break; - - default: - throw new IllegalStateException("Can't come here"); - - } - - return result; - - } - - @Override - public Object getValueAt(int rowIndex, int columnIndex) { - SectionWithTemplate row = data.get(rowIndex); - Object result; - - switch (columnIndex) { - case 0: - - result = row.getSettingIdentifier(); - break; - - case 1: - - result = row.getHaulingIdentifier(); - break; - - case 2: - - result = row.getSectionTemplate(); - break; - - default: - throw new IllegalStateException("Can't come here"); - } - - return result; - } - - @Override - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - SectionWithTemplate row = data.get(rowIndex); - - switch (columnIndex) { - case 0: - - row.setSettingIdentifier((Integer) aValue); - setModified(true); - break; - - case 1: - - row.setHaulingIdentifier((Integer) aValue); - setModified(true); - break; - - case 2: - - SectionTemplate sectionTemplate = (SectionTemplate) aValue; - - boolean changeTemplate = true; - - if (sectionTemplate != null) { - - // check if can use this template - int basketsCount = row.sizeBasket(); - boolean compiliantWithBasketCount = sectionTemplate.isCompiliantWithBasketCount(basketsCount); - - if (!compiliantWithBasketCount) { - - // We can't use this value - if (log.isWarnEnabled()) { - log.warn("sectionTemplate " + sectionTemplate + " is not compliant with basketCount: " + basketsCount); - } - //TODO Send user a message - - changeTemplate = false; - - } - - } - - if (changeTemplate) { - - SectionTemplate previousSectionTemplate = row.getSectionTemplate(); - row.setSectionTemplate(sectionTemplate); - firePropertyChange(TEMPLATE_PROPERTY, previousSectionTemplate, sectionTemplate); - - } - - break; - - default: - throw new IllegalStateException("Can't come here"); - } - - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/SetLonglineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/SetLonglineUI.jaxx deleted file mode 100644 index ccb76a1..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/SetLonglineUI.jaxx +++ /dev/null @@ -1,428 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ContentUI superGenericType='SetLonglineDto' contentTitle='{n("observe.content.setLongline.title")}'> - - <import> - fr.ird.observe.services.dto.CommentableDto - fr.ird.observe.services.dto.longline.SetLonglineDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.longline.SettingShapeDto - fr.ird.observe.services.dto.referential.longline.LineTypeDto - fr.ird.observe.services.dto.referential.longline.LightsticksTypeDto - fr.ird.observe.services.dto.referential.longline.LightsticksColorDto - - fr.ird.observe.ui.actions.shared.CancelCreateUIAction - fr.ird.observe.ui.actions.shared.DeleteDataUIAction - fr.ird.observe.ui.actions.shared.ResetEditUIAction - fr.ird.observe.ui.actions.shared.SaveEditUIAction - fr.ird.observe.ui.content.ContentUIModel - fr.ird.observe.ui.util.BooleanEditor - - jaxx.runtime.swing.editor.NumberEditor - org.nuiton.jaxx.widgets.datetime.TimeEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - org.nuiton.jaxx.widgets.gis.absolute.CoordinatesEditor - org.nuiton.jaxx.widgets.datetime.DateTimeEditor - - org.jdesktop.swingx.JXDatePicker - - org.apache.commons.lang3.BooleanUtils - - java.awt.Dimension - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <style source="../../Common.jcss"/> - - <!-- handler --> - <SetLonglineUIHandler id='handler'/> - - <!-- model --> - <SetLonglineUIModel id='model'/> - - <!-- edit bean --> - <SetLonglineDto id='bean'/> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' context='ui-update' - beanClass='fr.ird.observe.services.dto.longline.SetLonglineDto' - errorTableModel='{getErrorTableModel()}'> - - <field name='settingStartLongitude' component='settingStartCoordinates'/> - <field name='settingStartLatitude' component='settingStartCoordinates'/> - - <field name='settingEndLongitude' component='settingEndCoordinates'/> - <field name='settingEndLatitude' component='settingEndCoordinates'/> - - <field name='haulingStartLongitude' component='haulingStartCoordinates'/> - <field name='haulingStartLatitude' component='haulingStartCoordinates'/> - - <field name='haulingEndLongitude' component='haulingEndCoordinates'/> - <field name='haulingEndLatitude' component='haulingEndCoordinates'/> - - </BeanValidator> - - <!-- formulaire --> - <JPanel id="body" layout='{new BorderLayout()}'> - - <Table insets="0" fill="both" constraints='BorderLayout.CENTER'> - <row> - <cell anchor="north"> - <JTabbedPane id='fishingOperationTabPane'> - <tab id='settingTab'> - <JPanel layout='{new BorderLayout()}'> - <Table fill='both' constraints='BorderLayout.NORTH'> - - <!-- homeId --> - <row> - <cell anchor='west'> - <JLabel id='homeIdLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel layout='{new BorderLayout()}'> - <JToolBar id='homeIdToolbar' constraints='BorderLayout.WEST'> - <JButton id='resetHomeId' constraints='BorderLayout.WEST' styleClass='resetButton'/> - </JToolBar> - <JTextField id='homeId' constraints='BorderLayout.CENTER'/> - </JPanel> - </cell> - </row> - <!-- number --> - <row> - <cell anchor='west'> - <JLabel id='numberLabel'/> - </cell> - <cell columns="2" weightx="1" fill="both"> - <NumberEditor id='number' constructorParams='this'/> - </cell> - </row> - - <row> - <cell columns="2"> - <Table insets="0" fill='both'> - <!-- setting start timeStamp --> - <row> - <cell weightx="1"> - <DateTimeEditor id='settingStartTimeStamp' constructorParams='this'/> - </cell> - </row> - - <!-- setting start position --> - <row> - <cell anchor="east"> - <CoordinatesEditor id='settingStartCoordinates' constructorParams='this'/> - </cell> - </row> - - <!-- setting end timeStamp --> - <row> - <cell> - <DateTimeEditor id='settingEndTimeStamp' constructorParams='this'/> - </cell> - </row> - - <!-- setting end position --> - <row> - <cell anchor="east"> - <CoordinatesEditor id='settingEndCoordinates' constructorParams='this'/> - </cell> - </row> - </Table> - </cell> - </row> - - </Table> - </JPanel> - - </tab> - - <tab id='settingCaracteristicsTab'> - <Table fill='both'> - - <!-- setting shape --> - <row> - <cell anchor='west'> - <JLabel id='settingShapeLabel'/> - </cell> - <cell columns="2" fill="both"> - <BeanComboBox id='settingShape' constructorParams='this' genericType='ReferentialReference<SettingShapeDto>' _entityClass='SettingShapeDto.class'/> - </cell> - </row> - <!-- line type --> - <row> - <cell anchor='west'> - <JLabel id='lineTypeLabel'/> - </cell> - <cell columns="2"> - <BeanComboBox id='lineType' constructorParams='this' genericType='ReferentialReference<LineTypeDto>' _entityClass='LineTypeDto.class'/> - </cell> - </row> - - <!-- lightsticks type --> - <row> - <cell anchor='west'> - <JLabel id='lightsticksTypeLabel'/> - </cell> - <cell columns="2"> - <BeanComboBox id='lightsticksType' constructorParams='this' genericType='ReferentialReference<LightsticksTypeDto>' _entityClass='LightsticksTypeDto.class'/> - </cell> - </row> - - <!-- lightsticks color --> - <row> - <cell anchor='west'> - <JLabel id='lightsticksColorLabel'/> - </cell> - <cell columns="2"> - <BeanComboBox id='lightsticksColor' constructorParams='this' genericType='ReferentialReference<LightsticksColorDto>' _entityClass='LightsticksColorDto.class'/> - </cell> - </row> - - <!-- setting vessel speed --> - <row> - <cell> - <JLabel id='settingVesselSpeedLabel'/> - </cell> - <cell columns="2"> - <NumberEditor id='settingVesselSpeed' constructorParams='this'/> - </cell> - </row> - - <!-- max depth targeted (m) --> - <row> - <cell> - <JLabel id='maxDepthTargetedLabel'/> - </cell> - <cell columns="2"> - <NumberEditor id='maxDepthTargeted' constructorParams='this'/> - </cell> - </row> - - <!-- shooter used --> - <!-- shooter speed --> - <row> - <cell anchor="east"> - <JCheckBox id='shooterUsed'/> - </cell> - <cell> - <JLabel id='shooterSpeedLabel'/> - </cell> - <cell> - <NumberEditor id='shooterSpeed' constructorParams='this'/> - </cell> - </row> - - <!-- weighted swivels --> - <!-- swivels weights --> - <row> - <cell anchor="east"> - <JCheckBox id='weightedSwivel'/> - </cell> - <cell anchor="west"> - <JLabel id='swivelWeightLabel'/> - </cell> - <cell> - <NumberEditor id='swivelWeight' constructorParams='this'/> - </cell> - </row> - - <!-- weighted snaps --> - <!-- snap weights --> - <row> - <cell anchor='east'> - <JCheckBox id='weightedSnap'/> - </cell> - <cell> - <JLabel id='snapWeightLabel'/> - </cell> - <cell> - <NumberEditor id='snapWeight' constructorParams='this'/> - </cell> - </row> - - <!-- monitored --> - <!-- time between hooks --> - <row> - <cell anchor='east'> - <JCheckBox id='monitored'/> - </cell> - <cell anchor='west'> - <JLabel id='timeBetweenHooksLabel'/> - </cell> - <cell fill='both' weightx="1"> - <NumberEditor id='timeBetweenHooks' constructorParams='this'/> - </cell> - </row> - - <row> - <cell columns="3" fill="both"> - <Table insets="0"> - - <!-- basket per section count --> - <!-- total section count --> - <row> - <cell anchor='west'> - <JLabel id='basketsPerSectionCountLabel'/> - </cell> - <cell fill='both' weightx="1"> - <NumberEditor id='basketsPerSectionCount' constructorParams='this'/> - </cell> - <cell anchor='west'> - <JLabel id='totalSectionsCountLabel'/> - </cell> - <cell fill='both' weightx="1"> - <NumberEditor id='totalSectionsCount' constructorParams='this'/> - </cell> - </row> - - <!-- ligtsticks per basket count --> - <!-- total basket count --> - <row> - <cell anchor='west'> - <JLabel id='lightsticksPerBasketCountLabel'/> - </cell> - <cell fill='both' weightx="1"> - <NumberEditor id='lightsticksPerBasketCount' constructorParams='this'/> - </cell> - <cell anchor='west'> - <JLabel id='totalBasketsCountLabel'/> - </cell> - <cell fill='both' weightx="1"> - <NumberEditor id='totalBasketsCount' constructorParams='this'/> - </cell> - </row> - - <!-- branchlines per basket count --> - <!-- total hooks count --> - <row> - <cell anchor='west'> - <JLabel id='branchlinesPerBasketCountLabel'/> - </cell> - <cell fill='both' weightx="1"> - <NumberEditor id='branchlinesPerBasketCount' constructorParams='this'/> - </cell> - <cell anchor='west'> - <JLabel id='totalHooksCountLabel'/> - </cell> - <cell fill='both' weightx="1"> - <NumberEditor id='totalHooksCount' constructorParams='this'/> - </cell> - </row> - </Table> - </cell> - </row> - - </Table> - </tab> - - <tab id='haulingTab'> - - <JPanel layout='{new BorderLayout()}'> - <Table fill='both' constraints='BorderLayout.NORTH'> - - <!-- hauling same direction as setting --> - <row> - <cell> - <JLabel id='haulingDirectionSameAsSettingLabel'/> - </cell> - <cell> - <BooleanEditor id='haulingDirectionSameAsSetting'/> - </cell> - </row> - - <!-- hauling start timeStamp --> - <row> - <cell columns="2" weightx="1"> - <DateTimeEditor id='haulingStartTimeStamp' constructorParams='this'/> - </cell> - </row> - - <!-- hauling start position --> - <row> - <cell columns="2" anchor='east'> - <CoordinatesEditor id='haulingStartCoordinates' constructorParams='this'/> - </cell> - </row> - - <!-- hauling end timeStamp --> - <row> - <cell columns="2" weightx="1"> - <DateTimeEditor id='haulingEndTimeStamp' constructorParams='this'/> - </cell> - </row> - - <!-- hauling end position --> - <row> - <cell columns="2" anchor='east'> - <CoordinatesEditor id='haulingEndCoordinates' constructorParams='this'/> - </cell> - </row> - - <row> - <!-- hauling breaks --> - <cell anchor="west"> - <JLabel id='haulingBreaksLabel'/> - </cell> - <cell weightx="1" fill="both"> - <NumberEditor id='haulingBreaks' constructorParams='this'/> - </cell> - </row> - </Table> - </JPanel> - </tab> - </JTabbedPane> - </cell> - </row> - - <row> - <cell fill="both" weighty="1" weightx="1"> - <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2'/> - </JScrollPane> - </cell> - </row> - - </Table> - </JPanel> - - <!-- actions --> - <Table id="actions" fill='both' weightx='1' insets='0'> - <row> - <cell weightx="0.5" fill="both"> - <JButton id='cancel'/> - </cell> - <cell weightx="0.5"> - <JButton id='reset'/> - </cell> - <cell weightx="0.5"> - <JButton id='save'/> - </cell> - <cell weightx="0.5"> - <JButton id='delete'/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/SetLonglineUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/SetLonglineUI.jcss deleted file mode 100644 index c716f72..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/SetLonglineUI.jcss +++ /dev/null @@ -1,398 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#model { - editable:true; - modified:{validator.isChanged()}; - valid:{validator.isValid()}; - enabled:{!model.isReadingMode()}; -} - -/* ***************************************************************************** */ -/* SETTING TAB **************************************************************** */ -/* ***************************************************************************** */ - -#settingTab { - title:{t("observe.content.setLongline.tab.setting")}; - icon:{handler.getErrorIconIfFalse(model.isSettingTabValid())}; -} - -#homeIdLabel { - text:"observe.content.setLongline.homeId"; - labelFor:{homeId}; -} - -#homeId { - text: {getStringValue(bean.getHomeId())}; - _propertyName: {SetLonglineDto.PROPERTY_HOME_ID}; - _validatorLabel:{t("observe.content.setLongline.homeId")}; -} - -#resetHomeId { - _resetPropertyName: {SetLonglineDto.PROPERTY_HOME_ID}; - toolTipText:"observe.content.setLongline.action.reset.homeId.tip"; -} - -#numberLabel { - text:"observe.content.setLongline.number"; - labelFor:{number}; -} - -#number { - property: {SetLonglineDto.PROPERTY_NUMBER}; - model:{bean.getNumber()}; - useFloat:false; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.setLongline.number")}; -} - -#settingStartTimeStamp { - label:{t("observe.content.setLongline.settingStartTimeStamp")}; - date:{bean.getSettingStartTimeStamp()}; - propertyDate: {SetLonglineDto.PROPERTY_SETTING_START_TIME_STAMP}; - _validatorLabel:{t("observe.content.setLongline.settingStartTimeStamp")}; -} - -#settingStartCoordinatesLabel { - text:"observe.content.setLongline.settingStartCoordinates"; -} - -#settingStartCoordinates { - propertyLatitude:{SetLonglineDto.PROPERTY_SETTING_START_LATITUDE}; - propertyLongitude:{SetLonglineDto.PROPERTY_SETTING_START_LONGITUDE}; - latitude:{bean.getSettingStartLatitude()}; - longitude:{bean.getSettingStartLongitude()}; - _validatorLabel:{t("observe.content.setLongline.settingStartCoordinates")}; -} - -#settingEndTimeStamp { - label:{t("observe.content.setLongline.settingEndTimeStamp")}; - date:{bean.getSettingEndTimeStamp()}; - propertyDate: {SetLonglineDto.PROPERTY_SETTING_END_TIME_STAMP}; - _validatorLabel:{t("observe.content.setLongline.settingEndTimeStamp")}; -} - -#settingEndCoordinatesLabel { - text:"observe.content.setLongline.settingEndCoordinates"; -} - -#settingEndCoordinates { - propertyLatitude:{SetLonglineDto.PROPERTY_SETTING_END_LATITUDE}; - propertyLongitude:{SetLonglineDto.PROPERTY_SETTING_END_LONGITUDE}; - latitude:{bean.getSettingEndLatitude()}; - longitude:{bean.getSettingEndLongitude()}; - _validatorLabel:{t("observe.content.setLongline.settingEndCoordinates")}; -} - -/* ***************************************************************************** */ -/* SETTING CARACTERISTICS TAB ************************************************* */ -/* ***************************************************************************** */ - -#settingCaracteristicsTab { - title:{t("observe.content.setLongline.tab.settingCaracteristics")}; - icon:{handler.getErrorIconIfFalse(model.isSettingCaracteristicsTabValid())}; -} - -#settingVesselSpeedLabel { - text:"observe.content.setLongline.settingVesselSpeed"; - labelFor:{settingVesselSpeed}; -} - -#settingVesselSpeed { - property:{SetLonglineDto.PROPERTY_SETTING_VESSEL_SPEED}; - model:{bean.getSettingVesselSpeed()}; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL3_PATTERN}; - _validatorLabel:{t("observe.content.setLongline.settingVesselSpeed")}; -} - -#shooterUsed { - text:"observe.content.setLongline.shooterUsed"; - horizontalTextPosition:{JCheckBox.LEFT}; - _propertyName:{SetLonglineDto.PROPERTY_SHOOTER_USED}; - selected:{BooleanUtils.isTrue(bean.getShooterUsed())}; -} - -#shooterSpeedLabel { - text:"observe.content.setLongline.shooterSpeed"; - labelFor:{shooterSpeed}; -} - -#shooterSpeed { - enabled:{BooleanUtils.isTrue(bean.getShooterUsed())}; - property:{SetLonglineDto.PROPERTY_SHOOTER_SPEED}; - model:{bean.getShooterSpeed()}; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL3_PATTERN}; - _validatorLabel:{t("observe.content.setLongline.shooterSpeed")}; -} - -#settingShapeLabel { - text:"observe.content.setLongline.settingShape"; - labelFor:{settingShape}; -} - -#settingShape { - property:{SetLonglineDto.PROPERTY_SETTING_SHAPE}; - selectedItem:{bean.getSettingShape()}; - _validatorLabel:{t("observe.content.setLongline.settingShape")}; -} - -#weightedSwivel { - horizontalTextPosition:{JCheckBox.LEFT}; - text:"observe.content.setLongline.weightedSwivel"; - _propertyName:{SetLonglineDto.PROPERTY_WEIGHTED_SWIVEL}; - selected:{BooleanUtils.isTrue(bean.getWeightedSwivel())}; - _validatorLabel:{t("observe.content.setLongline.weightedSwivel")}; -} - -#swivelWeightLabel { - text:"observe.content.setLongline.swivelWeight"; - labelFor:{swivelWeight}; -} - -#swivelWeight { - enabled:{BooleanUtils.isTrue(bean.getWeightedSwivel())}; - property:{SetLonglineDto.PROPERTY_SWIVEL_WEIGHT}; - model:{bean.getSwivelWeight()}; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL3_PATTERN}; - _validatorLabel:{t("observe.content.setLongline.swivelWeight")}; -} - -#weightedSnap { - horizontalTextPosition:{JCheckBox.LEFT}; - text:"observe.content.setLongline.weightedSnap"; - _propertyName:{SetLonglineDto.PROPERTY_WEIGHTED_SNAP}; - selected:{BooleanUtils.isTrue(bean.getWeightedSnap())}; - _validatorLabel:{t("observe.content.setLongline.weightedSnap")}; -} - -#snapWeightLabel { - text:"observe.content.setLongline.snapWeight"; - labelFor:{snapWeight}; -} - -#snapWeight { - enabled:{BooleanUtils.isTrue(bean.getWeightedSnap())}; - property:{SetLonglineDto.PROPERTY_SNAP_WEIGHT}; - model:{bean.getSnapWeight()}; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL3_PATTERN}; - _validatorLabel:{t("observe.content.setLongline.snapWeight")}; -} - -#lineTypeLabel { - text:"observe.content.setLongline.lineType"; - labelFor:{lineType}; -} - -#lineType { - property:{SetLonglineDto.PROPERTY_LINE_TYPE}; - selectedItem:{bean.getLineType()}; - _validatorLabel:{t("observe.content.setLongline.lineType")}; -} - -#maxDepthTargetedLabel { - text:"observe.content.setLongline.maxDepthTargeted"; - labelFor:{maxDepthTargeted}; -} - -#maxDepthTargeted { - property:{SetLonglineDto.PROPERTY_MAX_DEPTH_TARGETED}; - model:{bean.getMaxDepthTargeted()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.setLongline.maxDepthTargeted")}; -} - -#monitored { - horizontalTextPosition:{JCheckBox.LEFT}; - text:"observe.content.setLongline.monitored"; - _propertyName:{SetLonglineDto.PROPERTY_MONITORED}; - selected:{BooleanUtils.isTrue(bean.getMonitored())}; - _validatorLabel:{t("observe.content.setLongline.monitored")}; -} - -#lightsticksTypeLabel { - text:"observe.content.setLongline.lightsticksType"; - labelFor:{lightsticksType}; -} - -#lightsticksType { - property:{SetLonglineDto.PROPERTY_LIGHTSTICKS_TYPE}; - selectedItem:{bean.getLightsticksType()}; - _validatorLabel:{t("observe.content.setLongline.lightsticksType")}; -} - -#lightsticksColorLabel { - text:"observe.content.setLongline.lightsticksColor"; - labelFor:{lightsticksColor}; -} - -#lightsticksColor { - property:{SetLonglineDto.PROPERTY_LIGHTSTICKS_COLOR}; - selectedItem:{bean.getLightsticksColor()}; - _validatorLabel:{t("observe.content.setLongline.lightsticksColor")}; -} - -#timeBetweenHooksLabel { - text:"observe.content.setLongline.timeBetweenHooks"; - labelFor:{timeBetweenHooks}; -} - -#timeBetweenHooks { - property:{SetLonglineDto.PROPERTY_TIME_BETWEEN_HOOKS}; - model:{bean.getTimeBetweenHooks()}; - modelType:{Long.class}; - numberPattern:{fr.ird.observe.ui.UIHelper.LONG_10_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.setLongline.timeBetweenHooks")}; -} - -#lightsticksPerBasketCountLabel { - text:"observe.content.setLongline.lightsticksPerBasketCount"; - labelFor:{lightsticksPerBasketCount}; -} - -#lightsticksPerBasketCount { - property:{SetLonglineDto.PROPERTY_LIGHTSTICKS_PER_BASKET_COUNT}; - model:{bean.getLightsticksPerBasketCount()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.setLongline.lightsticksPerBasketCount")}; -} - -#basketsPerSectionCountLabel { - text:"observe.content.setLongline.basketsPerSectionCount"; - labelFor:{basketsPerSectionCount}; -} - -#basketsPerSectionCount { - property:{SetLonglineDto.PROPERTY_BASKETS_PER_SECTION_COUNT}; - model:{bean.getBasketsPerSectionCount()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.setLongline.basketsPerSectionCount")}; -} - -#totalBasketsCountLabel { - text:"observe.content.setLongline.totalBasketsCount"; - labelFor:{totalBasketsCount}; -} - -#totalBasketsCount { - property:{SetLonglineDto.PROPERTY_TOTAL_BASKETS_COUNT}; - model:{bean.getTotalBasketsCount()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.setLongline.totalBasketsCount")}; -} - -#branchlinesPerBasketCountLabel { - text:"observe.content.setLongline.branchlinesPerBasketCount"; - labelFor:{branchlinesPerBasketCount}; -} - -#branchlinesPerBasketCount { - property:{SetLonglineDto.PROPERTY_BRANCHLINES_PER_BASKET_COUNT}; - model:{bean.getBranchlinesPerBasketCount()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.setLongline.branchlinesPerBasketCount")}; -} - -#totalSectionsCountLabel { - text:"observe.content.setLongline.totalSectionsCount"; - labelFor:{totalSectionsCount}; -} - -#totalSectionsCount { - property:{SetLonglineDto.PROPERTY_TOTAL_SECTIONS_COUNT}; - model:{bean.getTotalSectionsCount()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.setLongline.totalSectionsCount")}; -} - -#totalHooksCountLabel { - text:"observe.content.setLongline.totalHooksCount"; - labelFor:{totalHooksCount}; -} - -#totalHooksCount { - property:{SetLonglineDto.PROPERTY_TOTAL_HOOKS_COUNT}; - model:{bean.getTotalHooksCount()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.setLongline.totalHooksCount")}; -} - -/* ***************************************************************************** */ -/* HAULING TAB **************************************************************** */ -/* ***************************************************************************** */ - -#haulingTab { - title:{t("observe.content.setLongline.tab.hauling")}; - icon:{handler.getErrorIconIfFalse(model.isHaulingTabValid())}; -} - -#haulingDirectionSameAsSettingLabel { - text:"observe.content.setLongline.haulingDirectionSameAsSetting"; - labelFor:{haulingDirectionSameAsSetting}; -} - -#haulingDirectionSameAsSetting { - booleanValue:{bean.getHaulingDirectionSameAsSetting()}; - _propertyName: {SetLonglineDto.PROPERTY_HAULING_DIRECTION_SAME_AS_SETTING}; - _validatorLabel:{t("observe.content.setLongline.haulingDirectionSameAsSetting")}; -} - -#haulingStartTimeStamp { - label:{t("observe.content.setLongline.haulingStartTimeStamp")}; - date:{bean.getHaulingStartTimeStamp()}; - propertyDate: {SetLonglineDto.PROPERTY_HAULING_START_TIME_STAMP}; - _validatorLabel:{t("observe.content.setLongline.haulingStartTimeStamp")}; -} - -#haulingStartCoordinates { - propertyLatitude:{SetLonglineDto.PROPERTY_HAULING_START_LATITUDE}; - propertyLongitude:{SetLonglineDto.PROPERTY_HAULING_START_LONGITUDE}; - latitude:{bean.getHaulingStartLatitude()}; - longitude:{bean.getHaulingStartLongitude()}; - _validatorLabel:{t("observe.content.setLongline.haulingStartCoordinates")}; -} - -#haulingEndTimeStamp { - label:{t("observe.content.setLongline.haulingEndTimeStamp")}; - date:{bean.getHaulingEndTimeStamp()}; - propertyDate: {SetLonglineDto.PROPERTY_HAULING_END_TIME_STAMP}; - _validatorLabel:{t("observe.content.setLongline.haulingEndTimeStamp")}; -} - -#haulingEndCoordinates { - propertyLatitude:{SetLonglineDto.PROPERTY_HAULING_END_LATITUDE}; - propertyLongitude:{SetLonglineDto.PROPERTY_HAULING_END_LONGITUDE}; - latitude:{bean.getHaulingEndLatitude()}; - longitude:{bean.getHaulingEndLongitude()}; - _validatorLabel:{t("observe.content.setLongline.haulingEndCoordinates")}; -} - -#haulingBreaksLabel { - text:"observe.content.setLongline.haulingBreaks"; - labelFor:{haulingBreaks}; -} - -#haulingBreaks { - property:{SetLonglineDto.PROPERTY_HAULING_BREAKS}; - model:{bean.getHaulingBreaks()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.setLongline.haulingBreaks")}; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/SetLonglineUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/SetLonglineUIHandler.java deleted file mode 100644 index 3f9520f..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/SetLonglineUIHandler.java +++ /dev/null @@ -1,470 +0,0 @@ -package fr.ird.observe.ui.content.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.longline.ActivityLonglineDto; -import fr.ird.observe.services.dto.longline.SetLonglineDto; -import fr.ird.observe.services.dto.longline.SetLonglineDtos; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.service.longline.SetLonglineService; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.ContentUIHandler; -import fr.ird.observe.ui.content.ContentUIModel; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import jaxx.runtime.swing.HidorButton; -import jaxx.runtime.validator.swing.SwingValidatorMessage; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; -import jaxx.runtime.validator.swing.SwingValidatorUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.jaxx.widgets.gis.CoordinateFormat; -import org.nuiton.jaxx.widgets.gis.absolute.CoordinatesEditorModel; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.event.TableModelListener; -import java.beans.PropertyChangeListener; -import java.util.HashSet; -import java.util.Set; - -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 9/1/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class SetLonglineUIHandler extends ContentUIHandler<SetLonglineDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(SetLonglineUIHandler.class); - - // Compute valid state of tab from the error table - protected final TableModelListener computeTabValidStateListener; - - // Change toogle target visible on all TimeEditors - protected final PropertyChangeListener onToogleTimeEditorSliderChangedListener; - - // Change toogle target visible on all TimeEditors - protected final PropertyChangeListener onCoordinateFormatChangedListener; - -// private final LogPropertyChanges logCoordinatesChanges; - - protected boolean toogleTimeEditorSliderIsChanging; - - protected boolean coordinateFormatChangedIsChanging; - -// static ImmutableSet<String> COORDINATES_PROPERTIES = ImmutableSet.of( -// SetLongline.PROPERTY_HAULING_START_LONGITUDE, -// SetLongline.PROPERTY_HAULING_START_LATITUDE, -// SetLongline.PROPERTY_HAULING_START_QUADRANT, -// SetLongline.PROPERTY_SETTING_START_LONGITUDE, -// SetLongline.PROPERTY_SETTING_START_LATITUDE, -// SetLongline.PROPERTY_SETTING_START_QUADRANT, -// SetLongline.PROPERTY_HAULING_END_LONGITUDE, -// SetLongline.PROPERTY_HAULING_END_LATITUDE, -// SetLongline.PROPERTY_HAULING_END_QUADRANT, -// SetLongline.PROPERTY_SETTING_END_LONGITUDE, -// SetLongline.PROPERTY_SETTING_END_LATITUDE, -// SetLongline.PROPERTY_SETTING_END_QUADRANT); - - public SetLonglineUIHandler(SetLonglineUI ui) { - super(ui, DataContextType.ActivityLongline, DataContextType.SetLongline); -// this.logCoordinatesChanges = new LogPropertyChanges(COORDINATES_PROPERTIES); - computeTabValidStateListener = e -> { - - SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); - computeTabValidState(source); - - }; - onToogleTimeEditorSliderChangedListener = evt -> { - Boolean newValue = (Boolean) evt.getNewValue(); - onToogleTimeEditorSliderChanged(newValue); - }; - onCoordinateFormatChangedListener = evt -> { - CoordinateFormat newValue = (CoordinateFormat) evt.getNewValue(); - onCoordinateFormatChanged(newValue); - }; - } - - @Override - public SetLonglineUI getUi() { - return (SetLonglineUI) super.getUi(); - } - - @Override - protected boolean computeCanWrite(ObserveSwingDataSource source) { - return source.canWriteData(); - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - String setId = getSelectedId(); - - if (setId == null) { - - // mode creation - return ContentMode.CREATE; - - } - - if (getOpenDataManager().isOpenActivityLongline(dataContext.getSelectedActivityLonglineId())) { - - // l'activité est ouverte, mode édition - return ContentMode.UPDATE; - - } - - // l'activité n'est pas ouverte, mode lecture - addMessage(getUi(), - NuitonValidatorScope.INFO, - getEntityLabel(ActivityLonglineDto.class), - t("observe.storage.activityLongline.message.not.open")); - - return ContentMode.READ; - - } - - @Override - public void initUI() { - - super.initUI(); - - getUi().getSettingStartTimeStamp().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); - getUi().getSettingEndTimeStamp().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); - getUi().getHaulingStartTimeStamp().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); - getUi().getHaulingEndTimeStamp().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); - - getUi().getSettingStartCoordinates().getModel().addPropertyChangeListener(CoordinatesEditorModel.PROPERTY_FORMAT, onCoordinateFormatChangedListener); - getUi().getSettingEndCoordinates().getModel().addPropertyChangeListener(CoordinatesEditorModel.PROPERTY_FORMAT, onCoordinateFormatChangedListener); - getUi().getHaulingStartCoordinates().getModel().addPropertyChangeListener(CoordinatesEditorModel.PROPERTY_FORMAT, onCoordinateFormatChangedListener); - getUi().getHaulingEndCoordinates().getModel().addPropertyChangeListener(CoordinatesEditorModel.PROPERTY_FORMAT, onCoordinateFormatChangedListener); - -// getBean().removePropertyChangeListener(logCoordinatesChanges); -// getBean().addPropertyChangeListener(logCoordinatesChanges); - } - - - @Override - public void openUI() { - - getUi().getSettingStartCoordinates().resetModel(); - getUi().getSettingEndCoordinates().resetModel(); - getUi().getHaulingStartCoordinates().resetModel(); - getUi().getHaulingEndCoordinates().resetModel(); - - // Reset quandrant - resetQuadrant(getUi().getSettingStartCoordinates()); - resetQuadrant(getUi().getSettingEndCoordinates()); - resetQuadrant(getUi().getHaulingStartCoordinates()); - resetQuadrant(getUi().getHaulingEndCoordinates()); - - if (log.isInfoEnabled()) { - log.info("OpenUI: " + getModel()); - } - super.openUI(); - - String activityId = getSelectedParentId(); - String setId = getSelectedId(); - - if (log.isInfoEnabled()) { - log.info("activityId = " + activityId); - log.info("setId = " + setId); - } - ContentMode mode = computeContentMode(); - - SetLonglineDto bean = getBean(); - - Form<SetLonglineDto> form; - if (setId == null) { - - // create mode - form = getSetLonglineService().preCreate(activityId); - - } else { - - // update mode - form = getSetLonglineService().loadForm(setId); - - } - - loadReferentialReferenceSetsInModel(form); - - getModel().setForm(form); - SetLonglineDtos.copySetLonglineDto(form.getObject(), bean); - - getUi().getSettingStartCoordinates().setLatitudeAndLongitude(bean.getSettingStartLatitude(), bean.getSettingStartLongitude()); - getUi().getSettingEndCoordinates().setLatitudeAndLongitude(bean.getSettingEndLatitude(), bean.getSettingEndLongitude()); - getUi().getHaulingStartCoordinates().setLatitudeAndLongitude(bean.getHaulingStartLatitude(), bean.getHaulingStartLongitude()); - getUi().getHaulingEndCoordinates().setLatitudeAndLongitude(bean.getHaulingEndLatitude(), bean.getHaulingEndLongitude()); - - // utilisation du mode requis - setContentMode(mode); - - // To be sure always remove listener (could prevent some leaks) - getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); - // listen messages to see if required to add - getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); - - SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); - computeTabValidState(errorTableModel); - - if (mode != ContentMode.READ) { - getUi().startEdit(null); - } - - } - - @Override - protected void closeSafeUI() { - - if (log.isInfoEnabled()) { - log.info("CloseUI: " + getModel()); - } - super.closeSafeUI(); - - // remove listener - getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); - - } - - @Override - public void startEditUI(String... binding) { - - ContentUIModel<SetLonglineDto> model = getModel(); - boolean create = model.getMode() == ContentMode.CREATE; - String contextName = getValidatorContextName(model.getMode()); - getUi().getValidator().setContext(contextName); - if (create) { - addInfoMessage(t("observe.content.setLongline.message.creating")); - } else { - addInfoMessage(t("observe.content.setLongline.message.updating")); - } - - super.startEditUI(SetLonglineUI.BINDING_COMMENT2_TEXT, - - // setting tab - SetLonglineUI.BINDING_HOME_ID_TEXT, - SetLonglineUI.BINDING_NUMBER_MODEL, - - SetLonglineUI.BINDING_SETTING_START_TIME_STAMP_DATE, - SetLonglineUI.BINDING_SETTING_START_COORDINATES_LATITUDE, - SetLonglineUI.BINDING_SETTING_START_COORDINATES_LONGITUDE, - - SetLonglineUI.BINDING_SETTING_END_TIME_STAMP_DATE, - SetLonglineUI.BINDING_SETTING_END_COORDINATES_LATITUDE, - SetLonglineUI.BINDING_SETTING_END_COORDINATES_LONGITUDE, - - // setting caracteristics tab - SetLonglineUI.BINDING_SETTING_VESSEL_SPEED_MODEL, - SetLonglineUI.BINDING_SHOOTER_USED_SELECTED, - SetLonglineUI.BINDING_SHOOTER_SPEED_MODEL, - SetLonglineUI.BINDING_TIME_BETWEEN_HOOKS_MODEL, - SetLonglineUI.BINDING_SETTING_SHAPE_SELECTED_ITEM, - SetLonglineUI.BINDING_WEIGHTED_SWIVEL_SELECTED, - SetLonglineUI.BINDING_SWIVEL_WEIGHT_MODEL, - SetLonglineUI.BINDING_WEIGHTED_SNAP_SELECTED, - SetLonglineUI.BINDING_SNAP_WEIGHT_MODEL, - SetLonglineUI.BINDING_LINE_TYPE_SELECTED_ITEM, - SetLonglineUI.BINDING_MAX_DEPTH_TARGETED_MODEL, - SetLonglineUI.BINDING_MONITORED_SELECTED, - SetLonglineUI.BINDING_LIGHTSTICKS_TYPE_SELECTED_ITEM, - SetLonglineUI.BINDING_LIGHTSTICKS_COLOR_SELECTED_ITEM, - SetLonglineUI.BINDING_LIGHTSTICKS_PER_BASKET_COUNT_MODEL, - SetLonglineUI.BINDING_BASKETS_PER_SECTION_COUNT_MODEL, - SetLonglineUI.BINDING_TOTAL_BASKETS_COUNT_MODEL, - SetLonglineUI.BINDING_BRANCHLINES_PER_BASKET_COUNT_MODEL, - SetLonglineUI.BINDING_TOTAL_SECTIONS_COUNT_MODEL, - SetLonglineUI.BINDING_TOTAL_HOOKS_COUNT_MODEL, - - // hauling tab - SetLonglineUI.BINDING_HAULING_DIRECTION_SAME_AS_SETTING_BOOLEAN_VALUE, - - SetLonglineUI.BINDING_HAULING_START_TIME_STAMP_DATE, - SetLonglineUI.BINDING_HAULING_START_COORDINATES_LATITUDE, - SetLonglineUI.BINDING_HAULING_START_COORDINATES_LONGITUDE, - - SetLonglineUI.BINDING_HAULING_END_TIME_STAMP_DATE, - SetLonglineUI.BINDING_HAULING_END_COORDINATES_LATITUDE, - SetLonglineUI.BINDING_HAULING_END_COORDINATES_LONGITUDE, - - SetLonglineUI.BINDING_HAULING_BREAKS_MODEL); - - model.setModified(create); - - } - - @Override - protected boolean doSave(SetLonglineDto bean) throws Exception { - - String activityId = getSelectedParentId(); - - SaveResultDto saveResult = getSetLonglineService().save(activityId, bean); - saveResult.toDto(bean); - - return true; - - } - - @Override - protected void afterSave(boolean refresh) { - - super.afterSave(refresh); - - SetLonglineDto bean = getBean(); - - SwingValidatorUtil.setValidatorChanged(getUi(), false); - - ObserveTreeHelper treeHelper = getTreeHelper(getUi()); - - ObserveNode node = treeHelper.getSelectedNode(); - boolean create = node.getId() == null; - - if (create) { - - getModel().setMode(ContentMode.UPDATE); - - // remove old node and recreate new node - ObserveNode parentNode = treeHelper.removeNode(node); - - DataReference<SetLonglineDto> beanRef = ObserveSwingApplicationContext.get().getReferenceBinderEngine().transformDataDtoToReference(getDecoratorService().getReferentialLocale(), bean); - node = treeHelper.addSetLongline(parentNode, beanRef); - - stopEditUI(); - treeHelper.selectNode(node); - - } else { - - // select ancestor node -// treeHelper.refreshNode(node, false); - treeHelper.reloadSelectedNode(false, false); - - } - - } - - @Override - protected boolean doDelete(SetLonglineDto bean) { - - if (askToDelete(bean)) { - return false; - } - - String activityId = getSelectedParentId(); - getSetLonglineService().delete(activityId, bean.getId()); - - return true; - - } - - protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { - - Set<String> errorProperties = new HashSet<>(); - int rowCount = errorTableModel.getRowCount(); - for (int i = 0; i < rowCount; i++) { - - SwingValidatorMessage row = errorTableModel.getRow(i); - if (NuitonValidatorScope.ERROR.equals(row.getScope())) { - errorProperties.add(row.getField()); - } - } - - boolean settingTabValid = !errorProperties.removeAll(SetLonglineUIModel.SETTING_TAB_PROPERTIES); - boolean settingCaracteristicsTabValid = !errorProperties.removeAll(SetLonglineUIModel.SETTING_CARACTERISTICS_TAB_PROPERTIES); - boolean haulingTabValid = !errorProperties.removeAll(SetLonglineUIModel.HAULING_TAB_PROPERTIES); - - SetLonglineUIModel model = (SetLonglineUIModel) getModel(); - model.setSettingTabValid(settingTabValid); - model.setSettingCaracteristicsTabValid(settingCaracteristicsTabValid); - model.setHaulingTabValid(haulingTabValid); - - } - - protected void onToogleTimeEditorSliderChanged(boolean newValue) { - - if (!toogleTimeEditorSliderIsChanging) { - - toogleTimeEditorSliderIsChanging = true; - - boolean selected = !newValue; - - try { - - getUi().getSettingStartTimeStamp().getSliderHidor().setSelected(selected); - getUi().getSettingStartTimeStamp().getSliderHidor().setTargetVisible(newValue); - - getUi().getSettingEndTimeStamp().getSliderHidor().setSelected(selected); - getUi().getSettingEndTimeStamp().getSliderHidor().setTargetVisible(newValue); - - getUi().getHaulingStartTimeStamp().getSliderHidor().setSelected(selected); - getUi().getHaulingStartTimeStamp().getSliderHidor().setTargetVisible(newValue); - - getUi().getHaulingEndTimeStamp().getSliderHidor().setSelected(selected); - getUi().getHaulingEndTimeStamp().getSliderHidor().setTargetVisible(newValue); - - } finally { - - toogleTimeEditorSliderIsChanging = false; - - } - - } - - } - - protected synchronized void onCoordinateFormatChanged(CoordinateFormat newValue) { - - if (!coordinateFormatChangedIsChanging) { - - coordinateFormatChangedIsChanging = true; - - try { - - getUi().getSettingStartCoordinates().setFormat(newValue); - getUi().getSettingEndCoordinates().setFormat(newValue); - - getUi().getHaulingStartCoordinates().setFormat(newValue); - getUi().getHaulingEndCoordinates().setFormat(newValue); - - } finally { - - coordinateFormatChangedIsChanging = false; - - } - - } - - } - - protected SetLonglineService getSetLonglineService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newSetLonglineService(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/SetLonglineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/SetLonglineUIModel.java deleted file mode 100644 index cffbf8a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/longline/SetLonglineUIModel.java +++ /dev/null @@ -1,132 +0,0 @@ -package fr.ird.observe.ui.content.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.ImmutableSet; -import fr.ird.observe.services.dto.longline.SetLonglineDto; -import fr.ird.observe.ui.content.ContentUIModel; - -import java.util.Set; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class SetLonglineUIModel extends ContentUIModel<SetLonglineDto> { - - public static final String PROPERTY_SETTING_TAB_VALID = "settingTabValid"; - - public static final String PROPERTY_SETTING_CARACTERISTICS_TAB_VALID = "settingCaracteristicsTabValid"; - - public static final String PROPERTY_HAULING_TAB_VALID = "haulingTabValid"; - - public static final Set<String> SETTING_TAB_PROPERTIES = - ImmutableSet.<String>builder().add( - SetLonglineDto.PROPERTY_HOME_ID, - SetLonglineDto.PROPERTY_NUMBER, - SetLonglineDto.PROPERTY_SETTING_START_TIME_STAMP, - SetLonglineDto.PROPERTY_SETTING_START_LATITUDE, - SetLonglineDto.PROPERTY_SETTING_START_LONGITUDE, - SetLonglineDto.PROPERTY_SETTING_END_TIME_STAMP, - SetLonglineDto.PROPERTY_SETTING_END_LATITUDE, - SetLonglineDto.PROPERTY_SETTING_END_LONGITUDE - ).build(); - - public static final Set<String> SETTING_CARACTERISTICS_TAB_PROPERTIES = - ImmutableSet.<String>builder().add( - SetLonglineDto.PROPERTY_SETTING_SHAPE, - SetLonglineDto.PROPERTY_LINE_TYPE, - SetLonglineDto.PROPERTY_LIGHTSTICKS_TYPE, - SetLonglineDto.PROPERTY_LIGHTSTICKS_COLOR, - SetLonglineDto.PROPERTY_SETTING_VESSEL_SPEED, - SetLonglineDto.PROPERTY_MAX_DEPTH_TARGETED, - SetLonglineDto.PROPERTY_SHOOTER_USED, - SetLonglineDto.PROPERTY_SHOOTER_SPEED, - SetLonglineDto.PROPERTY_WEIGHTED_SWIVEL, - SetLonglineDto.PROPERTY_SWIVEL_WEIGHT, - SetLonglineDto.PROPERTY_WEIGHTED_SNAP, - SetLonglineDto.PROPERTY_SNAP_WEIGHT, - SetLonglineDto.PROPERTY_MONITORED, - SetLonglineDto.PROPERTY_TIME_BETWEEN_HOOKS, - SetLonglineDto.PROPERTY_BASKETS_PER_SECTION_COUNT, - SetLonglineDto.PROPERTY_BRANCHLINES_PER_BASKET_COUNT, - SetLonglineDto.PROPERTY_LIGHTSTICKS_PER_BASKET_COUNT, - SetLonglineDto.PROPERTY_TOTAL_SECTIONS_COUNT, - SetLonglineDto.PROPERTY_TOTAL_BASKETS_COUNT, - SetLonglineDto.PROPERTY_TOTAL_HOOKS_COUNT - ).build(); - - public static final Set<String> HAULING_TAB_PROPERTIES = - ImmutableSet.<String>builder().add( - SetLonglineDto.PROPERTY_HAULING_DIRECTION_SAME_AS_SETTING, - SetLonglineDto.PROPERTY_HAULING_START_LATITUDE, - SetLonglineDto.PROPERTY_HAULING_START_LONGITUDE, - SetLonglineDto.PROPERTY_HAULING_START_TIME_STAMP, - SetLonglineDto.PROPERTY_HAULING_END_LATITUDE, - SetLonglineDto.PROPERTY_HAULING_END_LONGITUDE, - SetLonglineDto.PROPERTY_HAULING_END_TIME_STAMP, - SetLonglineDto.PROPERTY_HAULING_BREAKS - ).build(); - - private static final long serialVersionUID = 1L; - - protected boolean settingTabValid; - - protected boolean settingCaracteristicsTabValid; - - protected boolean haulingTabValid; - - public SetLonglineUIModel() { - super(SetLonglineDto.class); - } - - public boolean isHaulingTabValid() { - return haulingTabValid; - } - - public void setHaulingTabValid(boolean haulingTabValid) { - this.haulingTabValid = haulingTabValid; - firePropertyChange(PROPERTY_HAULING_TAB_VALID, null, haulingTabValid); - } - - public boolean isSettingCaracteristicsTabValid() { - return settingCaracteristicsTabValid; - } - - public void setSettingCaracteristicsTabValid(boolean settingCaracteristicsTabValid) { - this.settingCaracteristicsTabValid = settingCaracteristicsTabValid; - firePropertyChange(PROPERTY_SETTING_CARACTERISTICS_TAB_VALID, null, settingCaracteristicsTabValid); - } - - public boolean isSettingTabValid() { - return settingTabValid; - } - - public void setSettingTabValid(boolean settingTabValid) { - this.settingTabValid = settingTabValid; - firePropertyChange(PROPERTY_SETTING_TAB_VALID, null, settingTabValid); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/ActivitySeineObservedSystemUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/ActivitySeineObservedSystemUI.jaxx deleted file mode 100644 index 2969a51..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/ActivitySeineObservedSystemUI.jaxx +++ /dev/null @@ -1,113 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ContentUI superGenericType='ActivitySeineObservedSystemDto' contentTitle='{n("observe.storage.activitySeineObservedSystem.title")}'> - - <import> - fr.ird.observe.services.dto.seine.ActivitySeineObservedSystemDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.seine.ObservedSystemDto - fr.ird.observe.ui.actions.shared.ResetEditUIAction - fr.ird.observe.ui.actions.shared.SaveEditUIAction - - jaxx.runtime.swing.editor.NumberEditor - org.nuiton.jaxx.widgets.select.FilterableDoubleList - - java.util.List - java.util.ArrayList - java.util.Collection - - java.awt.Dimension - - javax.swing.DefaultListModel - javax.swing.ListSelectionModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <ActivitySeineObservedSystemUIHandler id='handler'/> - - <!-- model --> - <ActivitySeineObservedSystemUIModel id='model'/> - - <!-- edit bean --> - <ActivitySeineObservedSystemDto id='bean'/> - - <!-- validator --> - <BeanValidator id='validator' - beanClass='fr.ird.observe.services.dto.seine.ActivitySeineObservedSystemDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update'> - <field name='observedSystem' component='observedSystemPane'/> - <field name='observedSystemDistance'/> - <field name='comment'/> - </BeanValidator> - - <!-- formulaire --> - <JPanel id="body" layout='{new BorderLayout()}'> - <Table fill='both' constraints="BorderLayout.CENTER"> - <!-- systeme observe --> - <row> - <cell columns="2" fill="both" weighty="0.7"> - <JScrollPane id='observedSystemPane' onFocusGained='observedSystem.requestFocus()'> - <FilterableDoubleList id='observedSystem' - genericType='ReferentialReference<ObservedSystemDto>' - _entityClass='ObservedSystemDto.class'/> - </JScrollPane> - </cell> - </row> - <!-- distance au système observe --> - <row> - <cell anchor='west'> - <JLabel id='observedSystemDistanceLabel'/> - </cell> - <cell weightx="1" fill="both"> - <NumberEditor id='observedSystemDistance' constructorParams='this'/> - </cell> - </row> - <!-- comment --> - <row> - <cell columns='2' fill="both" weighty="0.3"> - <JScrollPane id='comment' - onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2' - onKeyReleased='getBean().setComment(comment2.getText())'/> - </JScrollPane> - </cell> - </row> - </Table> - </JPanel> - - <!-- actions --> - <Table id="actions" fill='both' weightx='1' insets='0'> - <row> - <cell weightx="0.5"> - <JButton id='reset'/> - </cell> - <cell weightx="0.5"> - <JButton id='save'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/ActivitySeineObservedSystemUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/ActivitySeineObservedSystemUI.jcss deleted file mode 100644 index 8980592..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/ActivitySeineObservedSystemUI.jcss +++ /dev/null @@ -1,78 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#model { - editable:true; - modified:{validator.isChanged()}; - valid:{validator.isValid()}; - enabled:{!model.isReadingMode()}; -} - -#observedSystemPane { - /*columnHeaderView:{new JLabel(t("observe.common.observedSystem"))};*/ - minimumSize:{new Dimension(10,150)}; -} - -#observedSystem { - bean:{bean}; - property: {ActivitySeineObservedSystemDto.PROPERTY_OBSERVED_SYSTEM}; - selected:{(Collection)bean.getObservedSystem()}; - _validatorLabel: {t("observe.common.observedSystem")}; - showListLabel: true; - universeLabel:{t("observe.storage.activityObservedSystem.availableObservedSystem")}; - selectedLabel:{t("observe.storage.activityObservedSystem.selectedObservedSystem")}; -} - -#observedSystemDistanceLabel { - text:"observe.common.observedSystemDistance"; - labelFor:{observedSystemDistance}; -} - -#observedSystemDistance { - bean:{bean}; - property: {ActivitySeineObservedSystemDto.PROPERTY_OBSERVED_SYSTEM_DISTANCE}; - model:{bean.getObservedSystemDistance()}; - useFloat:true; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL2_PATTERN}; -} - -#comment { - columnHeaderView:{new JLabel(t("observe.common.comment.activity"))}; - minimumSize:{new Dimension(10,50)}; -} - -#comment2 { - text:{getStringValue(bean.getComment())}; -} - -#reset { - _observeAction:{ResetEditUIAction.ACTION_NAME}; - visible:{model.isUpdatingMode()}; - enabled:{model.isModified()}; -} - -#save { - _observeAction:{SaveEditUIAction.ACTION_NAME}; - visible:{model.isEnabled()}; - enabled:{model.isModified() && model.isValid()}; -} - diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/ActivitySeineObservedSystemUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/ActivitySeineObservedSystemUIHandler.java deleted file mode 100644 index e4d6db5..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/ActivitySeineObservedSystemUIHandler.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.impl.seine; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.dto.seine.ActivitySeineObservedSystemDto; -import fr.ird.observe.services.dto.seine.ActivitySeineObservedSystemDtos; -import fr.ird.observe.services.service.seine.ActivitySeineObservedSystemService; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.ContentUIHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import static org.nuiton.i18n.I18n.t; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class ActivitySeineObservedSystemUIHandler extends ContentUIHandler<ActivitySeineObservedSystemDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(ActivitySeineObservedSystemUIHandler.class); - - public ActivitySeineObservedSystemUIHandler(ActivitySeineObservedSystemUI ui) { - super(ui, DataContextType.ActivitySeine, null); - } - - @Override - public ActivitySeineObservedSystemUI getUi() { - return (ActivitySeineObservedSystemUI) super.getUi(); - } - - @Override - protected boolean computeCanWrite(ObserveSwingDataSource source) { - return source.canWriteData(); - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - if (getOpenDataManager().isOpenActivitySeine(dataContext.getSelectedActivitySeineId())) { - - // l'activity courante est ouverte, on peut modifier - return ContentMode.UPDATE; - } - - // activity courante non ouverte - addInfoMessage(t("observe.storage.activitySeine.message.not.open")); - - return ContentMode.READ; - } - - @Override - public void openUI() { - super.openUI(); - - String activityId = getSelectedParentId(); - - if (log.isInfoEnabled()) { - log.info("activityId = " + activityId); - } - - ContentMode mode = computeContentMode(); - - getModel().setMode(mode); - - Form<ActivitySeineObservedSystemDto> form = getActivitySeineObservedSystemService().loadForm(activityId); - - loadReferentialReferenceSetsInModel(form); - - getModel().setForm(form); - ActivitySeineObservedSystemDtos.copyActivitySeineObservedSystemDto(form.getObject(), getBean()); - - if (mode == ContentMode.UPDATE) { - getUi().startEdit(null); - } - } - - @Override - public void startEditUI(String... binding) { - addInfoMessage(t("observe.storage.activitySeine.message.updating")); - super.startEditUI(binding); - } - - @Override - protected boolean doSave(ActivitySeineObservedSystemDto bean) throws Exception { - - // on sauvegarde l'activity (mais pas la calée) - SaveResultDto saveResult = getActivitySeineObservedSystemService().save(bean); - saveResult.toDto(bean); - - return true; - } - - protected ActivitySeineObservedSystemService getActivitySeineObservedSystemService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivitySeineObservedSystemService(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/ActivitySeineObservedSystemUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/ActivitySeineObservedSystemUIModel.java deleted file mode 100644 index 6f10c45..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/ActivitySeineObservedSystemUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.seine.ActivitySeineObservedSystemDto; -import fr.ird.observe.ui.content.ContentUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ActivitySeineObservedSystemUIModel extends ContentUIModel<ActivitySeineObservedSystemDto> { - - private static final long serialVersionUID = 1L; - - public ActivitySeineObservedSystemUIModel() { - super(ActivitySeineObservedSystemDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUI.jaxx deleted file mode 100644 index f54f608..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUI.jaxx +++ /dev/null @@ -1,257 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ContentUI superGenericType='FloatingObjectTransmittingBuoyDto' - contentTitle='{n("observe.content.floatingObjectTransmittingBuoyOperation.title")}'> - - <import> - fr.ird.observe.services.dto.seine.FloatingObjectTransmittingBuoyDto - fr.ird.observe.services.dto.seine.TransmittingBuoyDto - fr.ird.observe.services.dto.constants.seine.Ownership - fr.ird.observe.services.dto.constants.seine.TypeTransmittingBuoyOperation - fr.ird.observe.services.dto.referential.CountryDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.seine.TransmittingBuoyOperationDto - fr.ird.observe.services.dto.referential.seine.TransmittingBuoyTypeDto - fr.ird.observe.ui.actions.shared.ResetEditUIAction - fr.ird.observe.ui.actions.shared.SaveEditUIAction - fr.ird.observe.ui.content.ContentUIModel - jaxx.runtime.swing.editor.bean.BeanComboBox - - java.awt.Dimension - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <FloatingObjectTransmittingBuoyOperationUIHandler id='handler'/> - - <!-- model --> - <FloatingObjectTransmittingBuoyOperationUIModel id='model'/> - - <!-- edit bean --> - <FloatingObjectTransmittingBuoyDto id='bean'/> - - <!-- transmittingBuoy1 edit bean --> - <TransmittingBuoyDto id='transmittingBuoy1' initializer='new TransmittingBuoyDto()'/> - - <!-- transmittingBuoy2 edit bean --> - <TransmittingBuoyDto id='transmittingBuoy2' initializer='new TransmittingBuoyDto()'/> - - <!-- validator --> - <BeanValidator id='validator' - autoField='true' - beanClass='fr.ird.observe.services.dto.seine.FloatingObjectTransmittingBuoyDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update-objectOperation'> - </BeanValidator> - - <BeanValidator id='validatorBalise1' - beanClass='fr.ird.observe.services.dto.seine.TransmittingBuoyDto' - errorTableModel='{getErrorTableModel()}' - parentValidator='{validator}' - context='ui-update'> - <field name="transmittingBuoyType" component="transmittingBuoyType1"/> - <field name="transmittingBuoyOperation" component="transmittingBuoyOperation1"/> - <field name="ownership" component="ownership1"/> - <field name="code" component="code1"/> - <field name="country" component="country1"/> - </BeanValidator> - - <BeanValidator id='validatorBalise2' - beanClass='fr.ird.observe.services.dto.seine.TransmittingBuoyDto' - errorTableModel='{getErrorTableModel()}' - parentValidator='{validator}' - context='ui-update'> - <field name="transmittingBuoyType" component="transmittingBuoyType2"/> - <field name="transmittingBuoyOperation" component="transmittingBuoyOperation2"/> - <field name="ownership" component="ownership2"/> - <field name="code" component="code2"/> - <field name="country" component="country2"/> - </BeanValidator> - - - <!-- formulaire --> - <JPanel id="body" layout='{new BorderLayout()}'> - - - <Table fill='both' constraints="BorderLayout.NORTH"> - <row> - <cell anchor='west'> - <JLabel id='typeOperationLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <EnumEditor id='typeOperation' - genericType='TypeTransmittingBuoyOperation' - constructorParams='TypeTransmittingBuoyOperation.class' - onItemStateChanged='if(event.getStateChange()==ItemEvent.SELECTED && model.isEditing()) { getHandler().changeTypeOperation(typeOperation.getSelectedItem(), true); model.setModified(true); }'/> - </cell> - </row> - </Table> - - <JPanel id="transmittingBuoys" constraints="BorderLayout.CENTER"/> - - <JScrollPane id='comment' constraints="BorderLayout.SOUTH" - onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2' - onKeyReleased='getBean().setComment(comment2.getText())'/> - </JScrollPane> - - </JPanel> - - <!-- actions --> - <Table id="actions" fill='both' weightx='1' insets='0'> - <row> - <cell weightx="0.5"> - <JButton id='reset'/> - </cell> - <cell weightx="0.5"> - <JButton id='save'/> - </cell> - </row> - </Table> - - <JPanel id="invisible"> - - <JLabel id='noBaliseEditor'/> - - <Table id='transmittingBuoy1Editor' fill="horizontal"> - <row> - <cell anchor='west'> - <JLabel id='transmittingBuoyOperation1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='transmittingBuoyOperation1' constructorParams='this' - genericType='ReferentialReference<TransmittingBuoyOperationDto>' - _entityClass='TransmittingBuoyOperationDto.class'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='transmittingBuoyType1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='transmittingBuoyType1' constructorParams='this' - genericType='ReferentialReference<TransmittingBuoyTypeDto>' - _entityClass='TransmittingBuoyTypeDto.class'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='ownership1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <EnumEditor id='ownership1' - constructorParams='Ownership.class' - onItemStateChanged='transmittingBuoy1.setOwnership((Ownership) ownership1.getSelectedItem())'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='country1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='country1' constructorParams='this' genericType='ReferentialReference<CountryDto>' _entityClass='CountryDto.class'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='code1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='code1' - onKeyReleased='transmittingBuoy1.setCode(code1.getText())'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='brand1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='brand1' - onKeyReleased='transmittingBuoy1.setBrand(brand1.getText())'/> - </cell> - </row> - </Table> - - <Table id='transmittingBuoy2Editor' fill="horizontal"> - <row> - <cell anchor='west'> - <JLabel id='transmittingBuoyOperation2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='transmittingBuoyOperation2' constructorParams='this' - genericType='ReferentialReference<TransmittingBuoyOperationDto>' - _entityClass='TransmittingBuoyOperationDto.class'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='transmittingBuoyType2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='transmittingBuoyType2' constructorParams='this' - genericType='ReferentialReference<TransmittingBuoyTypeDto>' - _entityClass='TransmittingBuoyTypeDto.class'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='ownership2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <EnumEditor id='ownership2' - constructorParams='Ownership.class' - onItemStateChanged='transmittingBuoy2.setOwnership((Ownership) ownership2.getSelectedItem())'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='country2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='country2' constructorParams='this' genericType='ReferentialReference<CountryDto>' _entityClass='CountryDto.class'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='code2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='code2' - onKeyReleased='transmittingBuoy2.setCode(code2.getText())'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='brand2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='brand2' - onKeyReleased='transmittingBuoy2.setBrand(brand2.getText())'/> - </cell> - </row> - </Table> - - </JPanel> -</fr.ird.observe.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUIHandler.java deleted file mode 100644 index 62da39a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUIHandler.java +++ /dev/null @@ -1,376 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.impl.seine; - -import com.google.common.collect.Lists; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.constants.seine.Ownership; -import fr.ird.observe.services.dto.constants.seine.TypeTransmittingBuoyOperation; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.seine.TransmittingBuoyOperationDto; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.services.dto.seine.FloatingObjectTransmittingBuoyDto; -import fr.ird.observe.services.dto.seine.FloatingObjectTransmittingBuoyDtos; -import fr.ird.observe.services.dto.seine.TransmittingBuoyDto; -import fr.ird.observe.services.dto.seine.TransmittingBuoyDtos; -import fr.ird.observe.services.service.seine.TransmittingBuoyOperationService; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.ContentUIHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.JPanel; -import javax.swing.SwingUtilities; -import java.awt.GridLayout; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import static org.nuiton.i18n.I18n.t; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class FloatingObjectTransmittingBuoyOperationUIHandler extends ContentUIHandler<FloatingObjectTransmittingBuoyDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(FloatingObjectTransmittingBuoyOperationUIHandler.class); - - public FloatingObjectTransmittingBuoyOperationUIHandler(FloatingObjectTransmittingBuoyOperationUI ui) { - super(ui, DataContextType.FloatingObject, null); - } - - @Override - public FloatingObjectTransmittingBuoyOperationUI getUi() { - return (FloatingObjectTransmittingBuoyOperationUI) super.getUi(); - } - - @Override - public FloatingObjectTransmittingBuoyOperationUIModel getModel() { - return (FloatingObjectTransmittingBuoyOperationUIModel) super.getModel(); - } - - @Override - protected boolean computeCanWrite(ObserveSwingDataSource source) { - return source.canWriteData(); - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - if (getOpenDataManager().isOpenActivitySeine(dataContext.getSelectedActivitySeineId())) { - - // l'activity courante est ouverte, on peut modifier - return ContentMode.UPDATE; - } - - // activity courante non ouverte - addMessage(getUi(), - NuitonValidatorScope.INFO, - getEntityLabel(ActivitySeineDto.class), - t("observe.storage.activitySeine.message.not.open")); - - return ContentMode.READ; - } - - @Override - public void openUI() { - super.openUI(); - - ContentMode mode = computeContentMode(); - - String dcpId = getSelectedParentId(); - - if (log.isInfoEnabled()) { - log.info("dcpId = " + dcpId); - } - - FloatingObjectTransmittingBuoyDto bean = getBean(); - - bean.getTransmittingBuoy().clear(); - - // pour etre sur que rien ne va changer pendant le chargement de l'objet. - - getModel().setEditing(false); - - Form<FloatingObjectTransmittingBuoyDto> form = getTransmittingBuoyOperationService().loadForm(dcpId); - loadReferentialReferenceSetsInModel(form); - - getModel().setForm(form); - FloatingObjectTransmittingBuoyDtos.copyFloatingObjectTransmittingBuoyDto(form.getObject(), bean); - - if (bean.sizeTransmittingBuoy() >= 1) { - TransmittingBuoyDtos.copyTransmittingBuoyDto( - bean.getTransmittingBuoy(0), - getUi().getTransmittingBuoy1()); - - if (bean.sizeTransmittingBuoy() >= 2) { - TransmittingBuoyDtos.copyTransmittingBuoyDto( - bean.getTransmittingBuoy(1), - getUi().getTransmittingBuoy2()); - } - } - - getUi().processDataBinding( - FloatingObjectTransmittingBuoyOperationUI.BINDING_TYPE_OPERATION_SELECTED_ITEM); - - TypeTransmittingBuoyOperation typeOperation = - getUi().getTypeOperation().getSelectedItem(); - changeTypeOperation(typeOperation, false); - - getModel().setMode(mode); - - if (mode == ContentMode.UPDATE) { - getUi().startEdit(null); - } - } - - - @Override - public void startEditUI(String... binding) { - super.startEditUI( - FloatingObjectTransmittingBuoyOperationUI.BINDING_TRANSMITTING_BUOY_OPERATION1_SELECTED_ITEM, - FloatingObjectTransmittingBuoyOperationUI.BINDING_TRANSMITTING_BUOY_OPERATION2_SELECTED_ITEM, - FloatingObjectTransmittingBuoyOperationUI.BINDING_CODE1_TEXT, - FloatingObjectTransmittingBuoyOperationUI.BINDING_CODE2_TEXT, - FloatingObjectTransmittingBuoyOperationUI.BINDING_OWNERSHIP1_SELECTED_ITEM, - FloatingObjectTransmittingBuoyOperationUI.BINDING_OWNERSHIP2_SELECTED_ITEM, - FloatingObjectTransmittingBuoyOperationUI.BINDING_TRANSMITTING_BUOY_TYPE1_SELECTED_ITEM, - FloatingObjectTransmittingBuoyOperationUI.BINDING_TRANSMITTING_BUOY_TYPE2_SELECTED_ITEM, - FloatingObjectTransmittingBuoyOperationUI.BINDING_BRAND1_TEXT, - FloatingObjectTransmittingBuoyOperationUI.BINDING_BRAND2_TEXT, - FloatingObjectTransmittingBuoyOperationUI.BINDING_COUNTRY1_SELECTED_ITEM, - FloatingObjectTransmittingBuoyOperationUI.BINDING_COUNTRY2_SELECTED_ITEM, - FloatingObjectTransmittingBuoyOperationUI.BINDING_TYPE_OPERATION_SELECTED_ITEM - ); - - FloatingObjectTransmittingBuoyOperationUI ui = getUi(); - - addInfoMessage(t("observe.message.updating.floatingObject")); - - Collection<TransmittingBuoyDto> balises = getBean().getTransmittingBuoy(); - if (balises != null && !balises.isEmpty()) { - TransmittingBuoyDto transmittingBuoy1 = ui.getTransmittingBuoy1(); - ui.getValidatorBalise1().setBean(transmittingBuoy1); - - if (balises.size() == 2) { - TransmittingBuoyDto transmittingBuoy2 = ui.getTransmittingBuoy2(); - ui.getValidatorBalise2().setBean(transmittingBuoy2); - } - } - - UIHelper.processDataBinding( - ui, - FloatingObjectTransmittingBuoyOperationUI.BINDING_TRANSMITTING_BUOY_OPERATION1_SELECTED_ITEM, - FloatingObjectTransmittingBuoyOperationUI.BINDING_TRANSMITTING_BUOY_OPERATION2_SELECTED_ITEM, - FloatingObjectTransmittingBuoyOperationUI.BINDING_CODE1_TEXT, - FloatingObjectTransmittingBuoyOperationUI.BINDING_CODE2_TEXT, - FloatingObjectTransmittingBuoyOperationUI.BINDING_OWNERSHIP1_SELECTED_ITEM, - FloatingObjectTransmittingBuoyOperationUI.BINDING_OWNERSHIP2_SELECTED_ITEM, - FloatingObjectTransmittingBuoyOperationUI.BINDING_BRAND1_TEXT, - FloatingObjectTransmittingBuoyOperationUI.BINDING_BRAND2_TEXT, - FloatingObjectTransmittingBuoyOperationUI.BINDING_COUNTRY1_SELECTED_ITEM, - FloatingObjectTransmittingBuoyOperationUI.BINDING_COUNTRY2_SELECTED_ITEM, - FloatingObjectTransmittingBuoyOperationUI.BINDING_TRANSMITTING_BUOY_TYPE1_SELECTED_ITEM, - FloatingObjectTransmittingBuoyOperationUI.BINDING_TRANSMITTING_BUOY_TYPE2_SELECTED_ITEM); - getModel().setModified(false); - } - - public boolean isBalisePose(TransmittingBuoyOperationDto operation) { - return operation != null && "3".equals(operation.getCode()); - } - - public boolean isBalisePose(ReferentialReference<TransmittingBuoyOperationDto> operation) { - return operation != null && "3".equals(operation.getPropertyValue(TransmittingBuoyOperationDto.PROPERTY_CODE)); - } - - @Override - protected boolean doSave(FloatingObjectTransmittingBuoyDto bean) throws Exception { - - SaveResultDto saveResult = getTransmittingBuoyOperationService().save(bean); - saveResult.toDto(bean); - //FIXME, il faut declancher un evenement dans le cache du storage pour pouvoir redessiner le noeud - return true; - } - - @Override - protected void afterSave(boolean refresh) { - // rien a rafraichir ? - resetEditUI(); - } - - protected void changeTypeOperation(TypeTransmittingBuoyOperation typeOperation, boolean reset) { - - FloatingObjectTransmittingBuoyOperationUI ui = getUi(); - - if (log.isInfoEnabled()) { - log.info(typeOperation + " doReset ? " + reset); - } - int nbBalises = typeOperation.getNbBalises(); - - FloatingObjectTransmittingBuoyDto bean = getBean(); - - boolean hasBalise = !bean.isTransmittingBuoyEmpty(); - - List<TransmittingBuoyDto> objets = new ArrayList<>(); - if (!reset) { - if (hasBalise) { - objets.addAll(bean.getTransmittingBuoy()); - } - } - - if (hasBalise) { - // always reset balise lues of editBean to avoid side-effects - bean.getTransmittingBuoy().clear(); - } - - // clean container - JPanel editorPanel = ui.getTransmittingBuoys(); - editorPanel.removeAll(); - - String[] codeOperations = typeOperation.getCodeOperation(); - List<ReferentialReference<TransmittingBuoyOperationDto>> operations = - ui.getTransmittingBuoyOperation1().getData(); - - TransmittingBuoyDto transmittingBuoy; - ReferentialReference<TransmittingBuoyOperationDto> objectOperation; - switch (nbBalises) { - case 0: - // no balise - editorPanel.setLayout(new GridLayout()); - editorPanel.add(ui.getNoBaliseEditor()); - if (getModel().isEditing()) { - ui.getValidatorBalise1().setBean(null); - ui.getValidatorBalise2().setBean(null); - } - break; - - case 1: - - transmittingBuoy = reset ? null : objets.get(0); - - objectOperation = reset ? getObjectOperation(operations, codeOperations[0]) : null; - - bindEditBalise(ui.getTransmittingBuoy1(), objectOperation, transmittingBuoy); - - editorPanel.setLayout(new GridLayout(1, 0)); - editorPanel.add(ui.getTransmittingBuoy1Editor()); - if (getModel().isEditing()) { - ui.getValidatorBalise1().setBean(ui.getTransmittingBuoy1()); - ui.getValidatorBalise2().setBean(null); - } - break; - - case 2: - - transmittingBuoy = reset ? null : objets.get(0); - objectOperation = reset ? getObjectOperation(operations, codeOperations[0]) : null; - bindEditBalise(ui.getTransmittingBuoy1(), objectOperation, transmittingBuoy); - - transmittingBuoy = reset ? null : objets.get(1); - objectOperation = reset ? getObjectOperation(operations, codeOperations[1]) : null; - bindEditBalise(ui.getTransmittingBuoy2(), objectOperation, transmittingBuoy); - - editorPanel.setLayout(new GridLayout(2, 0)); - editorPanel.add(ui.getTransmittingBuoy1Editor()); - editorPanel.add(ui.getTransmittingBuoy2Editor()); - if (getModel().isEditing()) { - ui.getValidatorBalise1().setBean(ui.getTransmittingBuoy1()); - ui.getValidatorBalise2().setBean(ui.getTransmittingBuoy2()); - } - break; - } - - SwingUtilities.invokeLater(() -> { - - // recalcul de la disposition - getUi().revalidate(); - }); - - } - - protected void bindEditBalise(TransmittingBuoyDto editBean, - ReferentialReference<TransmittingBuoyOperationDto> transmittingBuoyOperation, - TransmittingBuoyDto transmittingBuoy) { - - if (transmittingBuoy == null) { - - TransmittingBuoyDtos.copyTransmittingBuoyDto(new TransmittingBuoyDto(), editBean); - - editBean.setTransmittingBuoyOperation(transmittingBuoyOperation); - - if (log.isDebugEnabled()) { - log.debug("Reuse an empty balise lue for objectOperation " + - transmittingBuoyOperation.getPropertyValue(TransmittingBuoyOperationDto.PROPERTY_LABEL1)); - } - - if (isBalisePose(transmittingBuoyOperation)) { - - // objectOperation de pose - // toujours appartient au navire - editBean.setOwnership(Ownership.ceVessel); - } - - } else { - - TransmittingBuoyDtos.copyTransmittingBuoyDto(editBean, transmittingBuoy); - - } - - FloatingObjectTransmittingBuoyDto bean = getBean(); - - if (bean.getTransmittingBuoy() == null) { - bean.setTransmittingBuoy(Lists.newArrayList()); - } - bean.getTransmittingBuoy().add(editBean); - } - - protected ReferentialReference<TransmittingBuoyOperationDto> getObjectOperation(List<ReferentialReference<TransmittingBuoyOperationDto>> objectOperations, - String codeOperation) { - ReferentialReference<TransmittingBuoyOperationDto> objectOperation = null; - for (ReferentialReference<TransmittingBuoyOperationDto> op : objectOperations) { - if (codeOperation.equals(op.getPropertyValue(TransmittingBuoyOperationDto.PROPERTY_CODE))) { - objectOperation = op; - break; - } - } - if (objectOperation == null) { - throw new IllegalArgumentException( - "could not find a " + - TransmittingBuoyOperationDto.class + " with code " + codeOperation); - } - return objectOperation; - } - - protected TransmittingBuoyOperationService getTransmittingBuoyOperationService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTransmittingBuoyOperationService(); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUIModel.java deleted file mode 100644 index 7c3fc2a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectTransmittingBuoyOperationUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.seine.FloatingObjectTransmittingBuoyDto; -import fr.ird.observe.ui.content.ContentUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class FloatingObjectTransmittingBuoyOperationUIModel extends ContentUIModel<FloatingObjectTransmittingBuoyDto> { - - private static final long serialVersionUID = 1L; - - public FloatingObjectTransmittingBuoyOperationUIModel() { - super(FloatingObjectTransmittingBuoyDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectUI.jaxx deleted file mode 100644 index dcccd91..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectUI.jaxx +++ /dev/null @@ -1,136 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ContentUI superGenericType='FloatingObjectDto' contentTitle='{n("observe.content.floatingObject.title")}'> - - <import> - fr.ird.observe.services.dto.seine.FloatingObjectDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.seine.ObjectFateDto - fr.ird.observe.services.dto.referential.seine.ObjectOperationDto - fr.ird.observe.services.dto.referential.seine.ObjectTypeDto - fr.ird.observe.ui.actions.shared.CancelCreateUIAction - fr.ird.observe.ui.actions.shared.DeleteDataUIAction - fr.ird.observe.ui.actions.shared.ResetEditUIAction - fr.ird.observe.ui.actions.shared.SaveEditUIAction - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - java.awt.Dimension - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <FloatingObjectUIHandler id='handler'/> - - <!-- model --> - <FloatingObjectUIModel id='model'/> - - <!-- edit bean --> - <FloatingObjectDto id='bean'/> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' context='ui-create' - beanClass='fr.ird.observe.services.dto.seine.FloatingObjectDto' - errorTableModel='{getErrorTableModel()}'/> - - <!-- formulaire --> - <JPanel id="body" layout='{new BorderLayout()}'> - <Table fill='both' constraints="BorderLayout.CENTER"> - <row> - <cell anchor='west'> - <JLabel id='objectOperationLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='objectOperation' constructorParams='this' genericType='ReferentialReference<ObjectOperationDto>' _entityClass='ObjectOperationDto.class'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='objectTypeLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='objectType' constructorParams='this' genericType='ReferentialReference<ObjectTypeDto>' _entityClass='ObjectTypeDto.class'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='objectFateLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='objectFate' constructorParams='this' genericType='ReferentialReference<ObjectFateDto>' _entityClass='ObjectFateDto.class'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='daysAtSeaCountLabel'/> - </cell> - <cell anchor='east' weightx="1"> - <NumberEditor id='daysAtSeaCount' constructorParams='this'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='supportVesselNameLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel layout='{new BorderLayout()}'> - <JToolBar id='supportVesselNameToolbar' constraints='BorderLayout.WEST'> - <JButton id='resetSupportVesselName' constraints='BorderLayout.WEST' styleClass='resetButton'/> - </JToolBar> - <JTextField id='supportVesselName' constraints='BorderLayout.CENTER'/> - </JPanel> - </cell> - </row> - <row> - <cell columns='2' fill="both" weighty="0.7"> - <JScrollPane id='comment' - onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2' - onKeyReleased='getBean().setComment(comment2.getText())'/> - </JScrollPane> - </cell> - </row> - </Table> - </JPanel> - - <!-- actions --> - <Table id="actions" fill='both' weightx='1' insets='0'> - <row> - <cell weightx="0.5" fill="both"> - <JButton id='cancel'/> - </cell> - <cell weightx="0.5"> - <JButton id='reset'/> - </cell> - <cell weightx="0.5"> - <JButton id='save'/> - </cell> - <cell weightx="0.5"> - <JButton id='delete'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectUI.jcss deleted file mode 100644 index 18af31c..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectUI.jcss +++ /dev/null @@ -1,126 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -BeanComboBox { - bean:{bean}; - showReset:true; -} - -#model { - editable:true; - modified:{validator.isChanged()}; - valid:{validator.isValid()}; - enabled:{!model.isReadingMode()}; -} - -#objectOperationLabel { - text:"observe.common.objectOperation"; - labelFor:{objectOperation}; -} - -#objectOperation { - property:{FloatingObjectDto.PROPERTY_OBJECT_OPERATION}; - selectedItem:{bean.getObjectOperation()}; -} - -#objectTypeLabel { - text:"observe.common.objectType"; - labelFor:{objectType}; -} - -#objectType { - property:{FloatingObjectDto.PROPERTY_OBJECT_TYPE}; - selectedItem:{bean.getObjectType()}; -} - -#objectFateLabel { - text:"observe.common.objectFate"; - labelFor:{objectFate}; -} - -#objectFate { - property:{FloatingObjectDto.PROPERTY_OBJECT_FATE}; - selectedItem:{bean.getObjectFate()}; -} - -#daysAtSeaCountLabel { - text:"observe.common.daysAtSeaCount"; - labelFor:{daysAtSeaCount}; -} - -#daysAtSeaCount { - bean:{bean}; - property:{FloatingObjectDto.PROPERTY_DAYS_AT_SEA_COUNT}; - model:{bean.getDaysAtSeaCount()}; - autoPopup:{config.isAutoPopupNumberEditor()}; - showPopupButton:{config.isShowNumberEditorButton()}; - showReset:true; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; -} - -#supportVesselNameLabel { - text:"observe.common.supportVesselName"; - labelFor:{supportVesselName}; -} - -#supportVesselName { - _propertyName:{FloatingObjectDto.PROPERTY_SUPPORT_VESSEL_NAME}; - text:{getStringValue(bean.getSupportVesselName())}; - _validatorLabel:{"observe.common.supportVesselName"}; -} - -#resetSupportVesselName{ - toolTipText:"observe.content.action.reset.supportVesselName.tip"; - _resetPropertyName:{FloatingObjectDto.PROPERTY_SUPPORT_VESSEL_NAME}; -} - -#comment { - columnHeaderView:{new JLabel(t("observe.common.comment.floatingObject"))}; - minimumSize:{new Dimension(10,50)}; -} - -#comment2 { - text:{getStringValue(bean.getComment())}; -} - -#cancel { - _observeAction:{CancelCreateUIAction.ACTION_NAME}; - visible:{model.isCreatingMode()}; -} - -#reset { - _observeAction:{ResetEditUIAction.ACTION_NAME}; - visible:{model.isUpdatingMode()}; - enabled:{model.isModified()}; -} - -#save { - _observeAction:{SaveEditUIAction.ACTION_NAME}; - visible:{!model.isReadingMode()}; - enabled:{model.isModified() && model.isValid()}; -} - -#delete { - _observeAction:{DeleteDataUIAction.ACTION_NAME}; - visible:{model.isUpdatingMode()}; - _toolTipText:{t("observe.action.delete.floatingObject.tip")}; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectUIHandler.java deleted file mode 100644 index 93d2313..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectUIHandler.java +++ /dev/null @@ -1,225 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.impl.seine; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.services.dto.seine.FloatingObjectDto; -import fr.ird.observe.services.dto.seine.FloatingObjectDtos; -import fr.ird.observe.services.service.seine.FloatingObjectService; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.ContentUIHandler; -import fr.ird.observe.ui.content.ContentUIModel; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.validator.NuitonValidatorScope; - -import static org.nuiton.i18n.I18n.t; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class FloatingObjectUIHandler extends ContentUIHandler<FloatingObjectDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(FloatingObjectUIHandler.class); - - public FloatingObjectUIHandler(FloatingObjectUI ui) { - super(ui, DataContextType.ActivitySeine, DataContextType.FloatingObject); - } - - @Override - public FloatingObjectUI getUi() { - return (FloatingObjectUI) super.getUi(); - } - - @Override - protected boolean computeCanWrite(ObserveSwingDataSource source) { - return source.canWriteData(); - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - String dcpId = getSelectedId(); - - if (dcpId == null) { - - // mode création - return ContentMode.CREATE; - } - - // dcp existant - - if (getOpenDataManager().isOpenActivitySeine(dataContext.getSelectedActivitySeineId())) { - - // mode mise a jour - return ContentMode.UPDATE; - } - - // l'activité n'est pas ouverte - addMessage( - getUi(), - NuitonValidatorScope.INFO, - getEntityLabel(ActivitySeineDto.class), - t("observe.storage.activitySeine.message.not.open")); - - return ContentMode.READ; - } - - @Override - public void openUI() { - super.openUI(); - - String activityId = getSelectedParentId(); - String dcpId = getSelectedId(); - - if (log.isInfoEnabled()) { - log.info("activityId = " + activityId); - log.info("dcpId = " + dcpId); - } - - ContentMode mode = computeContentMode(); - - FloatingObjectDto bean = getBean(); - - Form<FloatingObjectDto> form; - if (dcpId == null) { - - // create mode - form = getFloatingObjectService().preCreate(activityId); - - } else { - - // update mode - form = getFloatingObjectService().loadForm(dcpId); - - } - loadReferentialReferenceSetsInModel(form); - - getModel().setForm(form); - FloatingObjectDtos.copyFloatingObjectDto(form.getObject(), bean); - - // utilisation du mode requis - setContentMode(mode); - - if (mode != ContentMode.READ) { - getUi().startEdit(null); - } - } - - @Override - public void startEditUI(String... binding) { - ContentUIModel<FloatingObjectDto> contentUIModel = getModel(); - boolean create = contentUIModel.getMode() == ContentMode.CREATE; - String contextName = getValidatorContextName(contentUIModel.getMode()); - getUi().getValidator().setContext(contextName); - if (create) { - addMessage(getUi(), - NuitonValidatorScope.INFO, - getEntityLabel(FloatingObjectDto.class), - t("observe.content.floatingObject.message.creating")); - } else { - addMessage(getUi(), - NuitonValidatorScope.INFO, - getEntityLabel(FloatingObjectDto.class), - t("observe.content.floatingObject.message.updating")); - } - super.startEditUI(FloatingObjectUI.BINDING_DAYS_AT_SEA_COUNT_MODEL, - FloatingObjectUI.BINDING_OBJECT_TYPE_SELECTED_ITEM, - FloatingObjectUI.BINDING_OBJECT_FATE_SELECTED_ITEM, - FloatingObjectUI.BINDING_SUPPORT_VESSEL_NAME_TEXT, - FloatingObjectUI.BINDING_COMMENT2_TEXT); - contentUIModel.setModified(create); - } - - @Override - protected boolean doSave(FloatingObjectDto bean) throws Exception { - - String activityId = getSelectedParentId(); - - SaveResultDto saveResult = getFloatingObjectService().save(activityId, bean); - saveResult.toDto(bean); - - return true; - - } - - @Override - protected void afterSave(boolean refresh) { - super.afterSave(refresh); - FloatingObjectDto bean = getBean(); - - ObserveTreeHelper treeHelper = getTreeHelper(getUi()); - - ObserveNode node = treeHelper.getSelectedNode(); - boolean create = node.getId() == null; - - if (create) { - - getModel().setMode(ContentMode.UPDATE); - - // remove old node and recreate new node - ObserveNode parentNode = treeHelper.removeNode(node); - - DataReference<FloatingObjectDto> beanRef = ObserveSwingApplicationContext.get().getReferenceBinderEngine().transformDataDtoToReference(getDecoratorService().getReferentialLocale(), bean); - node = treeHelper.addFloatingObject(parentNode, beanRef); - stopEditUI(); - if (refresh) { - treeHelper.selectNode(node); - } - } else { - - // select ancestor node -// treeHelper.refreshNode(node, false); - treeHelper.reloadSelectedNode(false, false); - } - } - - @Override - protected boolean doDelete(FloatingObjectDto bean) { - - if (askToDelete(bean)) { - return false; - } - - if (bean.getId() != null) { - - String activityId = getSelectedParentId(); - getFloatingObjectService().delete(activityId, bean.getId()); - } - return true; - } - - protected FloatingObjectService getFloatingObjectService() { - return getDataSource().newFloatingObjectService(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectUIModel.java deleted file mode 100644 index 594a484..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/FloatingObjectUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.seine.FloatingObjectDto; -import fr.ird.observe.ui.content.ContentUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class FloatingObjectUIModel extends ContentUIModel<FloatingObjectDto> { - - private static final long serialVersionUID = 1L; - - public FloatingObjectUIModel() { - super(FloatingObjectDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/SetSeineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/SetSeineUI.jaxx deleted file mode 100644 index 9c13fb7..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/SetSeineUI.jaxx +++ /dev/null @@ -1,255 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ContentUI superGenericType='SetSeineDto' contentTitle='{n("observe.content.setSeine.title")}'> - - <import> - fr.ird.observe.services.dto.CommentableDto - fr.ird.observe.services.dto.seine.SetSeineDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.seine.ReasonForNullSetDto - fr.ird.observe.ui.actions.shared.CancelCreateUIAction - fr.ird.observe.ui.actions.shared.DeleteDataUIAction - fr.ird.observe.ui.actions.shared.ResetEditUIAction - fr.ird.observe.ui.actions.shared.SaveEditUIAction - fr.ird.observe.ui.util.BooleanEditor - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - org.nuiton.jaxx.widgets.datetime.DateTimeEditor - - org.jdesktop.swingx.JXDatePicker - - java.awt.Dimension - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <style source="../../Common.jcss"/> - - <!-- handler --> - <SetSeineUIHandler id='handler'/> - - <!-- model --> - <SetSeineUIModel id='model'/> - - <!-- edit bean --> - <SetSeineDto id='bean'/> - - <!-- validator --> - <BeanValidator id='validator' - autoField='true' - beanClass='fr.ird.observe.services.dto.seine.SetSeineDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update'> - </BeanValidator> - - <!-- formulaire --> - <JPanel id="body" layout='{new BorderLayout()}'> - <Table insets="0" fill="both" constraints='BorderLayout.CENTER'> - <row> - <cell anchor="north" weightx="1"> - <JTabbedPane id='fishingOperationTabPane'> - <tab id='generalTab'> - <Table fill="both"> - <row> - <cell weightx="1" columns="2"> - <DateTimeEditor id='startTime' constructorParams='this'/> - </cell> - </row> - <row> - <cell weightx="1" columns="2"> - <DateTimeEditor id='endPursingTimeStamp' constructorParams='this'/> - </cell> - </row> - <row> - <cell weightx="1" columns="2"> - <DateTimeEditor id='endSetTimeStamp' constructorParams='this'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='reasonForNullSetLabel'/> - </cell> - <cell anchor='east' fill='both'> - <BeanComboBox id='reasonForNullSet' genericType='ReferentialReference<ReasonForNullSetDto>' _entityClass='ReasonForNullSetDto.class' constructorParams='this'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='supportVesselNameLabel'/> - </cell> - <cell anchor='east' fill="both"> - <JPanel layout='{new BorderLayout()}'> - <JToolBar id='supportVesselNameToolbar' constraints='BorderLayout.WEST'> - <JButton id='resetSupportVesselName' constraints='BorderLayout.WEST' styleClass='resetButton'/> - </JToolBar> - <JTextField id='supportVesselName' constraints='BorderLayout.CENTER'/> - </JPanel> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='targetDiscardedLabel'/> - </cell> - <cell anchor='east' fill="both"> - <BooleanEditor id='targetDiscarded'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='nonTargetDiscardedLabel'/> - </cell> - <cell anchor='east' fill="both"> - <BooleanEditor id='nonTargetDiscarded'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='schoolTypeLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JLabel id="schoolType"/> - </cell> - </row> - </Table> - </tab> - <tab id='measurementsTab'> - <Table fill="both" weightx="1"> - <row> - <cell columns='2'> - <Table id='sonarUsedAvantSetPane'> - <row> - <cell anchor='west'> - <JLabel id='schoolThicknessLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <NumberEditor id='schoolThickness' constructorParams='this'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='schoolMeanDepthLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <NumberEditor id='schoolMeanDepth' constructorParams='this'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='schoolTopDepthLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <NumberEditor id='schoolTopDepth' constructorParams='this'/> - </cell> - </row> - </Table> - </cell> - </row> - - <row> - <cell columns='2'> - <Table> - <row> - <cell anchor='west'> - <JLabel id='currentSpeedLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <NumberEditor id='currentSpeed' constructorParams='this'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='currentDirectionLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <NumberEditor id='currentDirection' constructorParams='this'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='currentMeasureDepthLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <NumberEditor id='currentMeasureDepth' constructorParams='this'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='maxGearDepthLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <NumberEditor id='maxGearDepth' constructorParams='this'/> - </cell> - </row> - <row> - <cell columns='2' anchor="west"> - <JCheckBox id='sonarUsed'/> - </cell> - </row> - </Table> - </cell> - </row> - - <row> - <cell columns="2" weighty="1"> - <JLabel/> - </cell> - </row> - </Table> - </tab> - - </JTabbedPane> - </cell> - </row> - - <row> - <cell columns='2' fill="both" weighty="1"> - <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2'/> - </JScrollPane> - </cell> - </row> - </Table> - </JPanel> - - <!-- actions --> - <Table id="actions" fill='both' weightx='1' insets='0'> - <row> - <cell weightx="0.5" fill="both"> - <JButton id='cancel'/> - </cell> - <cell weightx="0.5"> - <JButton id='reset'/> - </cell> - <cell weightx="0.5"> - <JButton id='save'/> - </cell> - <cell weightx="0.5"> - <JButton id='delete'/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/SetSeineUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/SetSeineUI.jcss deleted file mode 100644 index aa69bd4..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/SetSeineUI.jcss +++ /dev/null @@ -1,226 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#model { - editable:true; - modified:{validator.isChanged()}; - valid:{validator.isValid()}; - enabled:{!model.isReadingMode()}; -} - -#generalTab { - title:{t("observe.content.setSeine.tab.general")}; - icon:{getHandler().getErrorIconIfFalse(model.isGeneralTabValid())}; -} - -#measurementsTab { - title:{t("observe.content.setSeine.tab.measurements")}; - icon:{getHandler().getErrorIconIfFalse(model.isMeasurementsTabValid())}; -} - -#startTime { - propertyDate:{SetSeineDto.PROPERTY_START_TIME}; - label:{t("observe.content.setSeine.startTime")}; - date:{bean.getStartTime()}; - dateEditable:false; - _validatorLabel:{"observe.content.setSeine.startTime"}; -} - -#endPursingTimeStamp { - propertyDate: {SetSeineDto.PROPERTY_END_PURSING_TIME_STAMP}; - propertyDayDate: {SetSeineDto.PROPERTY_END_PURSING_DATE}; - propertyTimeDate: {SetSeineDto.PROPERTY_END_PURSING_TIME}; - label:{t("observe.content.setSeine.endPursingTimeStamp")}; - date:{bean.getEndPursingTimeStamp()}; - _validatorLabel:{t("observe.content.setSeine.endPursingTimeStamp")}; -} - -#endSetTimeStamp { - propertyDate: {SetSeineDto.PROPERTY_END_SET_TIME_STAMP}; - propertyDayDate: {SetSeineDto.PROPERTY_END_SET_DATE}; - propertyTimeDate: {SetSeineDto.PROPERTY_END_SET_TIME}; - label:{t("observe.content.setSeine.endSetTimeStamp")}; - date:{bean.getEndSetTimeStamp()}; - _validatorLabel:{t("observe.content.setSeine.endSetTimeStamp")}; -} - -#reasonForNullSetLabel { - text:"observe.content.setSeine.reasonForNullSet"; - labelFor:{reasonForNullSet}; -} - -#reasonForNullSet { - property:{SetSeineDto.PROPERTY_REASON_FOR_NULL_SET}; - selectedItem:{bean.getReasonForNullSet()}; - _validatorLabel:{t("observe.content.setSeine.reasonForNullSet")}; -} - -#supportVesselNameLabel { - text:"observe.content.setSeine.supportVesselName"; - labelFor:{supportVesselName}; -} - -#supportVesselName { - _propertyName:{SetSeineDto.PROPERTY_SUPPORT_VESSEL_NAME}; - text:{getStringValue(bean.getSupportVesselName())}; - _validatorLabel:{t("observe.content.setSeine.supportVesselName")}; -} - -#resetSupportVesselName{ - toolTipText:"observe.content.action.reset.supportVesselName.tip"; - _resetPropertyName:{SetSeineDto.PROPERTY_SUPPORT_VESSEL_NAME}; -} - -#targetDiscardedLabel { - text:"observe.content.setSeine.targetDiscarded"; - labelFor:{targetDiscarded}; -} - -#targetDiscarded { - _propertyName:{SetSeineDto.PROPERTY_TARGET_DISCARDED}; - booleanValue:{bean.getTargetDiscarded()}; - _validatorLabel:{t("observe.content.setSeine.targetDiscarded")}; -} - -#nonTargetDiscardedLabel { - text:"observe.content.setSeine.nonTargetDiscarded"; - labelFor:{nonTargetDiscarded}; -} - -#nonTargetDiscarded { - _propertyName:{SetSeineDto.PROPERTY_NON_TARGET_DISCARDED}; - booleanValue:{bean.getNonTargetDiscarded()}; - _validatorLabel:{t("observe.content.setSeine.nonTargetDiscarded")}; -} - -#schoolTypeLabel { - actionIcon:information; - text:"observe.content.setSeine.schoolType"; - toolTipText:"observe.content.setSeine.message.information.schoolType"; - labelFor:{schoolType}; -} - -#schoolType { - font-weight:bold; - text:{getHandler().updateTypeValue(bean.getSchoolType())}; - _validatorLabel:{t("observe.content.setSeine.schoolType")}; -} - -#sonarUsedAvantSetPane { - border:{new TitledBorder(null, t("observe.content.setSeine.sonarUsedAvantSet", 1, 0, getFont()))}; -} - -#schoolThicknessLabel { - text:"observe.content.setSeine.schoolThickness"; - labelFor:{schoolThickness}; -} - -#schoolThickness { - property:{SetSeineDto.PROPERTY_SCHOOL_THICKNESS}; - model:{bean.getSchoolThickness()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.setSeine.schoolThickness")}; -} - -#schoolMeanDepthLabel { - text:"observe.content.setSeine.schoolMeanDepth"; - labelFor:{schoolMeanDepth}; -} - -#schoolMeanDepth { - property:{SetSeineDto.PROPERTY_SCHOOL_MEAN_DEPTH}; - model:{bean.getSchoolMeanDepth()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.setSeine.schoolMeanDepth")}; -} - -#schoolTopDepthLabel { - text:"observe.content.setSeine.schoolTopDepth"; - labelFor:{schoolTopDepth}; -} - -#schoolTopDepth { - property:{SetSeineDto.PROPERTY_SCHOOL_TOP_DEPTH}; - model:{bean.getSchoolTopDepth()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.setSeine.schoolTopDepth")}; -} - -#currentMeasureDepthLabel { - text:"observe.content.setSeine.currentMeasureDepth"; - labelFor:{currentMeasureDepth}; -} - -#currentMeasureDepth { - property:{SetSeineDto.PROPERTY_CURRENT_MEASURE_DEPTH}; - model:{bean.getCurrentMeasureDepth()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.setSeine.currentMeasureDepth")}; -} - -#currentSpeedLabel { - text:"observe.content.setSeine.currentSpeed"; - labelFor:{currentSpeed}; -} - -#currentSpeed { - property:{SetSeineDto.PROPERTY_CURRENT_SPEED}; - model:{bean.getCurrentSpeed()}; - useFloat:true; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL1_PATTERN}; - _validatorLabel:{t("observe.content.setSeine.currentSpeed")}; -} - -#currentDirectionLabel { - text:"observe.content.setSeine.currentDirection"; - labelFor:{currentDirection}; -} - -#currentDirection { - property:{SetSeineDto.PROPERTY_CURRENT_DIRECTION}; - model:{bean.getCurrentDirection()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_3_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.setSeine.currentDirection")}; -} - -#maxGearDepthLabel { - text:"observe.content.setSeine.maxGearDepth"; - labelFor:{maxGearDepth}; -} - -#maxGearDepth { - property:{SetSeineDto.PROPERTY_MAX_GEAR_DEPTH}; - model:{bean.getMaxGearDepth()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.setSeine.maxGearDepth")}; -} - -#sonarUsed { - _propertyName:{SetSeineDto.PROPERTY_SONAR_USED}; - text:"observe.content.setSeine.sonarUsed"; - selected:{bean.isSonarUsed()}; - _validatorLabel:{t("observe.content.setSeine.sonarUsed")}; -} - -#delete { - _toolTipText:{t("observe.action.delete.set.tip")}; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/SetSeineUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/SetSeineUIHandler.java deleted file mode 100644 index 5230c9d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/SetSeineUIHandler.java +++ /dev/null @@ -1,345 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.impl.seine; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.constants.seine.SchoolType; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.services.dto.seine.SetSeineDto; -import fr.ird.observe.services.dto.seine.SetSeineDtos; -import fr.ird.observe.services.service.seine.RouteService; -import fr.ird.observe.services.service.seine.SetSeineService; -import fr.ird.observe.services.util.I18nEnumUtil; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.ContentUIHandler; -import fr.ird.observe.ui.content.ContentUIModel; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import jaxx.runtime.swing.HidorButton; -import jaxx.runtime.validator.swing.SwingValidatorMessage; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; -import jaxx.runtime.validator.swing.SwingValidatorUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.util.DateUtil; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.event.TableModelListener; -import java.beans.PropertyChangeListener; -import java.util.Date; -import java.util.HashSet; -import java.util.Set; - -import static org.nuiton.i18n.I18n.t; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class SetSeineUIHandler extends ContentUIHandler<SetSeineDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(SetSeineUIHandler.class); - - // Compute valid state of tab from the error table - protected final TableModelListener computeTabValidStateListener; - - // Change toogle target visible on all TimeEditors - protected final PropertyChangeListener onToogleTimeEditorSliderChangedListener; - - protected boolean toogleTimeEditorSliderIsChanging; - - public SetSeineUIHandler(SetSeineUI ui) { - super(ui, DataContextType.ActivitySeine, DataContextType.SetSeine); - computeTabValidStateListener = e -> { - - SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); - computeTabValidState(source); - - }; - onToogleTimeEditorSliderChangedListener = evt -> { - Boolean newValue = (Boolean) evt.getNewValue(); - onToogleTimeEditorSliderChanged(newValue); - }; - } - - @Override - public SetSeineUI getUi() { - return (SetSeineUI) super.getUi(); - } - - public String updateTypeValue(SchoolType schoolType) { - if (schoolType == null) { - return t("observe.content.setSeine.schoolType.not.fill"); - } - return I18nEnumUtil.getLabel(schoolType); - } - - @Override - protected boolean computeCanWrite(ObserveSwingDataSource source) { - return source.canWriteData(); - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - String setId = getSelectedId(); - - if (setId == null) { - - // mode creation - return ContentMode.CREATE; - } - - if (getOpenDataManager().isOpenActivitySeine(dataContext.getSelectedActivitySeineId())) { - - // l'activity est ouverte, mode édition - return ContentMode.UPDATE; - } - - // l'activity n'est pas ouverte, mode lecture - addMessage(getUi(), - NuitonValidatorScope.INFO, - getEntityLabel(ActivitySeineDto.class), - t("observe.storage.activitySeine.message.not.open")); - return ContentMode.READ; - } - - @Override - public void initUI() { - - super.initUI(); - - // To be sure always remove listener (could prevent some leaks) - getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); - // listen messages to see if required to add - getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); - - getUi().getStartTime().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); - getUi().getEndPursingTimeStamp().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); - getUi().getEndSetTimeStamp().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); - - } - - @Override - public void openUI() { - super.openUI(); - - String activityId = getSelectedParentId(); - String setId = getSelectedId(); - String selectedRouteId = getDataContext().getSelectedRouteId(); - - if (log.isInfoEnabled()) { - log.info("activityId = " + activityId); - log.info("setId = " + setId); - } - ContentMode mode = computeContentMode(); - - SetSeineDto bean = getBean(); - - Form<SetSeineDto> form; - if (setId == null) { - - // create mode - form = getSetSeineService().preCreate(selectedRouteId, activityId); - - } else { - - // update mode - form = getSetSeineService().loadForm(setId); - - } - - // utilisation du mode requis - setContentMode(mode); - - loadReferentialReferenceSetsInModel(form); - - getModel().setForm(form); - SetSeineDtos.copySetSeineDto(form.getObject(), bean); - - RouteService routeService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newRouteService(); - - RouteDto route = routeService.loadDto(selectedRouteId); - - Date time = bean.getStartTime(); - - Date date = route.getDate(); - - Date dateAndTime = DateUtil.getDateAndTime(date, time, false, false); - - getUi().getStartTime().setDate(dateAndTime); - - SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); - computeTabValidState(errorTableModel); - - if (mode != ContentMode.READ) { - getUi().startEdit(null); - } - } - - @Override - public void startEditUI(String... binding) { - ContentUIModel<SetSeineDto> model = getModel(); - boolean create = model.getMode() == ContentMode.CREATE; - String contextName = getValidatorContextName(model.getMode()); - getUi().getValidator().setContext(contextName); - if (create) { - addInfoMessage(t("observe.content.setSeine.message.creating")); - } else { - addInfoMessage(t("observe.content.setSeine.message.updating")); - } - - super.startEditUI(SetSeineUI.BINDING_SUPPORT_VESSEL_NAME_TEXT, - SetSeineUI.BINDING_COMMENT2_TEXT, - SetSeineUI.BINDING_START_TIME_DATE, - SetSeineUI.BINDING_END_SET_TIME_STAMP_DATE, - SetSeineUI.BINDING_END_SET_TIME_STAMP_DATE, - SetSeineUI.BINDING_END_PURSING_TIME_STAMP_DATE, - SetSeineUI.BINDING_CURRENT_SPEED_MODEL, - SetSeineUI.BINDING_CURRENT_DIRECTION_MODEL, - SetSeineUI.BINDING_REASON_FOR_NULL_SET_SELECTED_ITEM, - SetSeineUI.BINDING_SONAR_USED_SELECTED, - SetSeineUI.BINDING_CURRENT_SPEED_MODEL, - SetSeineUI.BINDING_NON_TARGET_DISCARDED_BOOLEAN_VALUE, - SetSeineUI.BINDING_TARGET_DISCARDED_BOOLEAN_VALUE, - SetSeineUI.BINDING_SCHOOL_THICKNESS_MODEL, - SetSeineUI.BINDING_SCHOOL_TYPE_TEXT, - SetSeineUI.BINDING_MAX_GEAR_DEPTH_MODEL, - SetSeineUI.BINDING_SCHOOL_MEAN_DEPTH_MODEL, - SetSeineUI.BINDING_SCHOOL_TOP_DEPTH_MODEL); - model.setModified(create); - } - - @Override - protected boolean doSave(SetSeineDto bean) throws Exception { - - String activityId = getSelectedParentId(); - - SaveResultDto saveResult = getSetSeineService().save(activityId, bean); - saveResult.toDto(bean); - - return true; - } - - @Override - protected void afterSave(boolean refresh) { - - super.afterSave(refresh); - - SetSeineDto bean = getBean(); - - SwingValidatorUtil.setValidatorChanged(getUi(), false); - - ObserveTreeHelper treeHelper = getTreeHelper(getUi()); - - ObserveNode node = treeHelper.getSelectedNode(); - boolean create = node.getId() == null; - - if (create) { - getModel().setMode(ContentMode.UPDATE); - - // remove old node and recreate new node - ObserveNode parentNode = treeHelper.removeNode(node); - - DataReference<SetSeineDto> beanRef = ObserveSwingApplicationContext.get().getReferenceBinderEngine().transformDataDtoToReference(getDecoratorService().getReferentialLocale(), bean); - node = treeHelper.addSetSeine(parentNode, beanRef); - - stopEditUI(); - treeHelper.selectNode(node); - } else { - // select ancestor node -// treeHelper.refreshNode(node, false); - treeHelper.reloadSelectedNode(false, false); - } - } - - protected boolean doDelete(SetSeineDto bean) { - - if (askToDelete(bean)) { - return false; - } - - String activityId = getSelectedParentId(); - getSetSeineService().delete(activityId, bean.getId()); - return true; - } - - protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { - - Set<String> errorProperties = new HashSet<>(); - int rowCount = errorTableModel.getRowCount(); - for (int i = 0; i < rowCount; i++) { - - SwingValidatorMessage row = errorTableModel.getRow(i); - if (NuitonValidatorScope.ERROR.equals(row.getScope())) { - errorProperties.add(row.getField()); - } - } - - boolean generalTabValid = !errorProperties.removeAll(SetSeineUIModel.GENERAL_TAB_PROPERTIES); - boolean measurementsTabValid = !errorProperties.removeAll(SetSeineUIModel.MEASUREMENTS_TAB_PROPERTIES); - - SetSeineUIModel model = (SetSeineUIModel) getModel(); - model.setGeneralTabValid(generalTabValid); - model.setMeasurementsTabValid(measurementsTabValid); - - } - - protected void onToogleTimeEditorSliderChanged(boolean newValue) { - - if (!toogleTimeEditorSliderIsChanging) { - - toogleTimeEditorSliderIsChanging = true; - - try { - - getUi().getStartTime().getSliderHidor().setSelected(!newValue); - getUi().getStartTime().getSliderHidor().setTargetVisible(newValue); - - getUi().getEndPursingTimeStamp().getSliderHidor().setSelected(!newValue); - getUi().getEndPursingTimeStamp().getSliderHidor().setTargetVisible(newValue); - - getUi().getEndSetTimeStamp().getSliderHidor().setSelected(!newValue); - getUi().getEndSetTimeStamp().getSliderHidor().setTargetVisible(newValue); - - } finally { - - toogleTimeEditorSliderIsChanging = false; - - } - - } - - } - - protected SetSeineService getSetSeineService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newSetSeineService(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/SetSeineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/SetSeineUIModel.java deleted file mode 100644 index efa026a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/impl/seine/SetSeineUIModel.java +++ /dev/null @@ -1,94 +0,0 @@ -package fr.ird.observe.ui.content.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.ImmutableSet; -import fr.ird.observe.services.dto.seine.SetSeineDto; -import fr.ird.observe.ui.content.ContentUIModel; - -import java.util.Set; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class SetSeineUIModel extends ContentUIModel<SetSeineDto> { - - public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; - - public static final String PROPERTY_MEASUREMENTS_TAB_VALID = "measurementsTabValid"; - - public static final Set<String> GENERAL_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(SetSeineDto.PROPERTY_START_TIME, - SetSeineDto.PROPERTY_END_PURSING_TIME_STAMP, - SetSeineDto.PROPERTY_END_SET_TIME_STAMP, - SetSeineDto.PROPERTY_REASON_FOR_NULL_SET, - SetSeineDto.PROPERTY_SUPPORT_VESSEL_NAME, - SetSeineDto.PROPERTY_TARGET_DISCARDED, - SetSeineDto.PROPERTY_NON_TARGET_DISCARDED, - SetSeineDto.PROPERTY_SCHOOL_TYPE).build(); - - public static final Set<String> MEASUREMENTS_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(SetSeineDto.PROPERTY_SCHOOL_THICKNESS, - SetSeineDto.PROPERTY_SCHOOL_MEAN_DEPTH, - SetSeineDto.PROPERTY_SCHOOL_TOP_DEPTH, - SetSeineDto.PROPERTY_CURRENT_SPEED, - SetSeineDto.PROPERTY_CURRENT_DIRECTION, - SetSeineDto.PROPERTY_CURRENT_MEASURE_DEPTH, - SetSeineDto.PROPERTY_MAX_GEAR_DEPTH, - SetSeineDto.PROPERTY_SONAR_USED).build(); - - private static final long serialVersionUID = 1L; - - protected boolean generalTabValid; - - protected boolean measurementsTabValid; - - - public SetSeineUIModel() { - super(SetSeineDto.class); - } - - public boolean isMeasurementsTabValid() { - return measurementsTabValid; - } - - public void setMeasurementsTabValid(boolean measurementsTabValid) { - Object oldValue = isMeasurementsTabValid(); - this.measurementsTabValid = measurementsTabValid; - firePropertyChange(PROPERTY_MEASUREMENTS_TAB_VALID, oldValue, measurementsTabValid); - } - - public boolean isGeneralTabValid() { - return generalTabValid; - } - - public void setGeneralTabValid(boolean generalTabValid) { - Object oldValue = isGeneralTabValid(); - this.generalTabValid = generalTabValid; - firePropertyChange(PROPERTY_GENERAL_TAB_VALID, oldValue, generalTabValid); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/ContentListUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/ContentListUI.jaxx deleted file mode 100644 index d5d3801..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/ContentListUI.jaxx +++ /dev/null @@ -1,119 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ContentUI - abstract='true' - superGenericType='E' - genericType='E extends IdDto, C extends DataDto'> - - <import> - fr.ird.observe.ui.actions.shared.ReOpenUIAction - fr.ird.observe.ui.actions.shared.SelectNodeUIAction - - fr.ird.observe.services.dto.IdDto - fr.ird.observe.services.dto.DataDto - fr.ird.observe.services.dto.DataReference - - jaxx.runtime.swing.editor.bean.BeanListHeader - - java.awt.Dimension - - javax.swing.DefaultListSelectionModel - javax.swing.ListSelectionModel - - java.util.List - - static org.nuiton.i18n.I18n.t - </import> - <java.lang.String id='listText' javaBean='""'/> - - <java.lang.String id='emptyListMessage' javaBean='""'/> - - <ContentListUIModel id='model' genericType='E, C'/> - - <ListSelectionModel id='listSelectionModel' - initializer='new DefaultListSelectionModel()' - onValueChanged='if (!event.getValueIsAdjusting()) getModel().setSelectedDatas(getSelectedDatas());'/> - - <ContentListUIHandler id='handler' genericType='E, C'/> - - <script><![CDATA[ - -public final DataReference<C> getSelectedData() { - return (DataReference<C>) getSelectedBean(list); -} - -public final List<DataReference<C>> getSelectedDatas() { - return (List<DataReference<C>>) list.getSelectedValuesList(); -} - -]]></script> - - <JPanel id='body'> - - <JScrollPane id='listPane' constraints='BorderLayout.CENTER' - onFocusGained='list.requestFocus()' - columnHeaderView='{listHeader}'> - - <JList id='list' onMouseClicked='getHandler().onDataSelected(event)'/> - - <BeanListHeader id='listHeader' genericType='DataReference< C >' _entityClass="getModel().getChildType()"/> - - </JScrollPane> - - </JPanel> - - <Table id="actions" fill='both' weightx='1' insets='0'> - <row> - <cell fill='both' columns="3"> - <JButton id='gotoSelectedChild'/> - </cell> - </row> - <row> - <cell fill='both' columns="3"> - <JButton id='reopenChild'/> - </cell> - </row> - <row weighty="1" weightx="1" fill="both"> - <cell> - <JButton id='gotoOpenChild'/> - </cell> - <cell> - <JButton id='gotoOpenChild2'/> - </cell> - <cell> - <JButton id='createChild' onActionPerformed='getHandler().addChild()'/> - </cell> - </row> - <row> - <cell fill="both" columns="3"> - <Table id='extraActions' fill="both" weightx="1" insets='2'/> - </cell> - </row> - <row> - <cell fill='both' columns="3"> - <JButton id='moveSelectedChildren'/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/ContentListUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/ContentListUIHandler.java deleted file mode 100644 index 94fdb2e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/ContentListUIHandler.java +++ /dev/null @@ -1,283 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.list; - -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.AbstractReference; -import fr.ird.observe.services.dto.DataDto; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.ui.actions.shared.SelectNodeUIAction; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.ContentUIHandler; -import fr.ird.observe.ui.tree.AbstractObserveTreeCellRenderer; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import jaxx.runtime.swing.editor.bean.BeanListHeader; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.Icon; -import javax.swing.JButton; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.ListCellRenderer; -import java.awt.Color; -import java.awt.Component; -import java.awt.event.MouseEvent; -import java.util.List; - -import static org.nuiton.i18n.I18n.t; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.5 - */ -public abstract class ContentListUIHandler<E extends IdDto, C extends DataDto> extends ContentUIHandler<E> { - - /** Logger */ - private static final Log log = LogFactory.getLog(ContentListUIHandler.class); - - public ContentListUIHandler(ContentListUI<E, C> ui, - DataContextType parentType, - DataContextType type) { - super(ui, parentType, type); - } - - /** - * Obtain the list of entities to display on ui from his container - * {@code bean}. - * - * @param parentId the parent id of entities to display - * @return the list of entities to display - */ - protected abstract List<DataReference<C>> getChilds(String parentId); - - @Override - protected boolean computeCanWrite(ObserveSwingDataSource source) { - return source.canWriteData(); - } - - @Override - public ContentListUI<E, C> getUi() { - return (ContentListUI<E, C>) super.getUi(); - } - - @Override - public final ContentListUIModel<E, C> getModel() { - return (ContentListUIModel<E, C>) super.getModel(); - } - - @Override - public void initUI() { - super.initUI(); - - // on installe un renderer sur la liste pour afficher les couleurs + - // icones comme dans l'arbre - ListCellRenderer renderer = getUi().getList().getCellRenderer(); - ObserveTreeHelper treeHelper = getTreeHelper(getUi()); - - ListCellRenderer renderer2 = new EntityListCellRenderer(renderer, treeHelper); - - getUi().getList().setCellRenderer(renderer2); - } - - @Override - public final void openUI() { - - super.openUI(); - - // init renderer - EntityListCellRenderer renderer = (EntityListCellRenderer) - getUi().getList().getCellRenderer(); - renderer.init(); - - ContentListUIModel<E, C> model = getModel(); - - String selectedId = getSelectedParentId(); - - if (log.isInfoEnabled()) { - log.info(prefix + "selectedId = " + selectedId); - } - - ContentMode mode = computeContentMode(); - - if (log.isInfoEnabled()) { - log.info(prefix + "content mode = " + mode); - } - - // We want to force the bindings on "mode" to be triggered each time we open a list ui. - // - // The ui mode can already be set to the mode we're currently applying now. - // As the state of the buttons is bound to that mode, - // we need to force a mode change to ensure the buttons state will be refreshed. - // - // For example : - // The button of the activities list of a route "Go to the open activity of another road" may need to disapear - // because that road has just been deleted.. - // - // As the ui state of the buttons is usually only bound to the mode of the model - // and as the state of those buttons usually not only depends on that mode (but also on attributes of the data context for instance, such as a route/activity/trip is open or not), - // we need to force the buttons to recompute their state by forcing the mode's listeners to be triggered. - model.setMode(null); - model.setMode(mode); - - boolean canReopen = mode == ContentMode.CREATE; - if (log.isInfoEnabled()) { - log.info(prefix + "canReopen = " + canReopen); - } - model.setCanReopen(canReopen); - - // il n'est pas nécessaire de charger le bean car seuls ses enfants nous sont utile dans cette ecran - - List<DataReference<C>> data = getChilds(getSelectedParentId()); - - model.setData(data); - - if (!model.isEmpty()) { - - // select first data - getUi().getListSelectionModel().setSelectionInterval(0, 0); - - } - - // finalize openUI with specified code - finalizeOpenUI(); - } - - public void addChild() { - addChild(getModel().getChildType()); - } - - /** - * When a data has been selected in the list. - * - * @param event the mouse event fired - */ - public void onDataSelected(MouseEvent event) { - DataReference<C> selectedData = getUi().getSelectedData(); - if (event.getClickCount() > 1) { - gotoChild(selectedData); - return; - } - ObserveNode node = null; - if (selectedData != null) { - - // obtain the node corresponding to the selected data - String id = selectedData.getId(); - ObserveTreeHelper helper = getTreeHelper(getUi()); - ObserveNode selectedNode = helper.getSelectedNode(); - node = helper.findNode(selectedNode, id); - } - - // attach the node to action - JButton button = getUi().getGotoSelectedChild(); - button.putClientProperty(SelectNodeUIAction.NODE, node); - } - - public <E> List<E> updateList(BeanListHeader<E> list, List<E> data) { - String message = t(getUi().getEmptyListMessage()); - return updateList(list, data, message); - } - - /** - * Pour effectuer un traitement supplémantaire à la fin de la méthode - * {@link #openUI()}. - */ - protected void finalizeOpenUI() { - // rien par default - } - - /** - * Un renderer de liste d'entité qui reprendre la cosmétique de l'arbre - * de navigation. - * - * @since 1.5 - */ - private static class EntityListCellRenderer extends DefaultListCellRenderer { - - private static final long serialVersionUID = 1L; - - protected final transient ListCellRenderer delegate; - - protected final transient ObserveTreeHelper treeHelper; - - protected final AbstractObserveTreeCellRenderer treeRenderer; - - protected ObserveNode containerNode; - - public EntityListCellRenderer(ListCellRenderer delegate, - ObserveTreeHelper treeHelper) { - this.delegate = delegate; - this.treeHelper = treeHelper; - this.treeRenderer = treeHelper.getTreeCellRenderer(); - } - - public void init() { - containerNode = treeHelper.getSelectedNode(); - } - - @Override - public Component getListCellRendererComponent(JList list, - Object value, - int index, - boolean isSelected, - boolean cellHasFocus) { - - // obtain the text from the delegate renderer - JLabel comp = (JLabel) - delegate.getListCellRendererComponent(list, - value, - index, - isSelected, - cellHasFocus - ); - - if (value == null || - !(value instanceof AbstractReference) || - containerNode == null) { - - // rien de plus a faire - return comp; - } - - // recuperation du noeud correspondant dans l'arbre - ObserveNode node = - treeHelper.findNode(containerNode, ((AbstractReference) value).getId()); - - if (node == null) { - - // noeud non trouve (cela ne devrait jamais arrive - return comp; - } - - Icon icon = treeRenderer.getNavigationIcon(node); - comp.setIcon(icon); - Color color = treeRenderer.getNavigationTextColor(node); - comp.setForeground(color); - return comp; - } - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/ContentListUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/ContentListUIModel.java deleted file mode 100644 index 69d8a53..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/ContentListUIModel.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.list; - -import fr.ird.observe.services.dto.DataDto; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.ui.content.ContentUIModel; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.List; - -/** - * Le modèle pour un écran d'édition avec des fils. - * - * @author Tony Chemit - chemit@codelutin.com - * @since .14 - */ -public abstract class ContentListUIModel<E extends IdDto, C extends DataDto> extends ContentUIModel<E> { - - public static final String PROPERTY_DATA = "data"; - - public static final String PROPERTY_SELECTED_DATAS = "selectedDatas"; - public static final String PROPERTY_ONE_SELECTED_DATA = "oneSelectedData"; - public static final String PROPERTY_ONE_OR_MORE_SELECTED_DATA = "oneOrMoreSelectedData"; - - public static final String PROPERTY_EMPTY = "empty"; - - public static final String PROPERTY_CAN_REOPEN = "canReopen"; - - private static final long serialVersionUID = 1L; - - /** Logger */ - static private final Log log = LogFactory.getLog(ContentListUIModel.class); - - /** type des entites */ - protected final Class<C> childType; - - /** liste des entites */ - protected List<DataReference<C>> data; - - /** entités sélectionnées dans la liste */ - protected List<DataReference<C>> selectedDatas; - - /** un drapeau pour savoir si on peut reouvrir l'un des données de la liste. */ - protected boolean canReopen; - - public ContentListUIModel(Class<E> beanType, Class<C> childType) { - super(beanType); - this.childType = childType; - } - - public Class<C> getChildType() { - return childType; - } - - public List<DataReference<C>> getData() { - return data; - } - - public void setData(List<DataReference<C>> data) { - boolean wasEmpty = isEmpty(); - this.data = data; - // on force toujours la propagation de la liste - firePropertyChange(PROPERTY_DATA, null, data); - firePropertyChange(PROPERTY_EMPTY, wasEmpty, isEmpty()); - setSelectedDatas(null); - } - - public DataReference<C> getSelectedData() { - return CollectionUtils.isNotEmpty(selectedDatas) ? selectedDatas.get(0) : null; - } - - public List<DataReference<C>> getSelectedDatas() { - return selectedDatas; - } - - public void setSelectedDatas(List<DataReference<C>> selectedDatas) { - boolean oldOneSelectedData = isOneSelectedData(); - boolean oldOneOrMoreSelectedData = isOneOrMoreSelectedData(); - List<DataReference<C>> old = getSelectedDatas(); - this.selectedDatas = selectedDatas; - if (log.isDebugEnabled()) { - log.debug("New selected datas : " + selectedDatas); - } - firePropertyChange(PROPERTY_SELECTED_DATAS, old, selectedDatas); - firePropertyChange(PROPERTY_ONE_SELECTED_DATA, oldOneSelectedData, isOneSelectedData()); - firePropertyChange(PROPERTY_ONE_OR_MORE_SELECTED_DATA, oldOneOrMoreSelectedData, isOneOrMoreSelectedData()); - } - - public boolean isOneSelectedData() { - return selectedDatas != null && selectedDatas.size() == 1; - } - - public boolean isOneOrMoreSelectedData() { - return CollectionUtils.isNotEmpty(selectedDatas ); - } - - public boolean isCanReopen() { - return canReopen; - } - - public void setCanReopen(boolean canReopen) { - boolean old = isCanReopen(); - this.canReopen = canReopen; - firePropertyChange(PROPERTY_CAN_REOPEN, old, canReopen); - } - - public boolean isEmpty() { - return data == null || data.isEmpty(); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/ActivityLonglinesUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/ActivityLonglinesUI.jaxx deleted file mode 100644 index 3816466..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/ActivityLonglinesUI.jaxx +++ /dev/null @@ -1,69 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.list.ContentListUI superGenericType='TripLonglineDto, ActivityLonglineDto' - contentTitle='{n("observe.storage.activityLonglines.title")}' listText='{n("observe.common.activities.list")}' - emptyListMessage='{n("observe.message.no.activity.for.trip")}'> - - <import> - fr.ird.observe.services.dto.longline.ActivityLonglineDto - fr.ird.observe.services.dto.longline.TripLonglineDto - fr.ird.observe.ui.actions.shared.CloseAndCreateUIAction - fr.ird.observe.ui.actions.shared.CloseOpenUIAction - fr.ird.observe.ui.actions.shared.SelectOpenNodeUIAction - fr.ird.observe.ui.actions.shared.MoveActivityLonglinesUIAction - - static org.nuiton.i18n.I18n.n - </import> - - <style source="CommonListUI.jcss"/> - - <!-- handler --> - <ActivityLonglinesUIHandler id='handler' constructorParams='this'/> - - <!-- model --> - <ActivityLonglinesUIModel id='model'/> - - <!-- edit bean --> - <TripLonglineDto id='bean'/> - - <!-- override generic actions --> - <JButton id='gotoSelectedChild'/> - <JButton id='reopenChild'/> - <JButton id='gotoOpenChild' styleClass='gotoOpenActivity'/> - <JButton id='gotoOpenChild2' styleClass='gotoOpenActivity2'/> - <JButton id='createChild'/> - <JButton id='moveSelectedChildren'/> - - <!-- extra actions --> - <Table id='extraActions' fill="both" weightx="1" insets='2'> - <row> - <cell weightx="0.5" fill="both"> - <JButton id='close'/> - </cell> - <cell weightx="0.5"> - <JButton id='closeAndCreate'/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.list.ContentListUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/ActivityLonglinesUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/ActivityLonglinesUIHandler.java deleted file mode 100644 index 3161270..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/ActivityLonglinesUIHandler.java +++ /dev/null @@ -1,126 +0,0 @@ -package fr.ird.observe.ui.content.list.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.DataReferenceSet; -import fr.ird.observe.services.dto.longline.ActivityLonglineDto; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.service.longline.ActivityLonglineService; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.list.ContentListUIHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.ArrayList; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; - -/** - * Created on 8/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class ActivityLonglinesUIHandler extends ContentListUIHandler<TripLonglineDto, ActivityLonglineDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(ActivityLonglinesUIHandler.class); - - public ActivityLonglinesUIHandler(ActivityLonglinesUI ui) { - super(ui, DataContextType.TripLongline, DataContextType.ActivityLongline); - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - String openTripLonglineId = dataContext.getOpenTripId(); - - if (openTripLonglineId == null) { - - // pas de marée ouverte, donc on ne peut pas ouvrir une activité - addInfoMessage(n("observe.content.tripLongline.message.no.active.found")); - return ContentMode.READ; - } - - // - // il existe une marée ouverte - // - - boolean openActivity = dataContext.isOpenActivity(); - - if (dataContext.isSelectedOpen(TripLonglineDto.class)) { - - // - // la marée courante est ouverte - // - - // l'activité courante est ouverte - if (openActivity) { - - // il existe une activite d'ouverte dans la maree courante - addInfoMessage(n("observe.storage.activityLongline.message.active.found")); - return ContentMode.UPDATE; - } - - // pas d'activité ouverte, on peut en ouvrir une - addInfoMessage(n("observe.storage.activityLongline.message.no.active.found")); - return ContentMode.CREATE; - } - - // - // la marée ouverte n'est pas la marée courante - // - - if (openActivity) { - - // il existe une activité ouverte dans la marée ouverte - addInfoMessage(n("observe.storage.activityLongline.message.active.found.for.other.trip")); - } else { - - // il n'existe pas d'activité ouverte dans la marée ouverte - addInfoMessage(n("observe.storage.activityLongline.message.no.active.found.for.other.trip")); - } - - return ContentMode.READ; - - } - - @Override - protected List<DataReference<ActivityLonglineDto>> getChilds(String parentId) { - - ActivityLonglineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivityLonglineService(); - DataReferenceSet<ActivityLonglineDto> activityLonglineStubByRoute = service.getActivityLonglineByTripLongline(parentId); - - if (log.isDebugEnabled()) { - log.debug("Will use " + activityLonglineStubByRoute.sizeReference() + " activities."); - } - - return new ArrayList<>(activityLonglineStubByRoute.getReferences()); - - } -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/ActivityLonglinesUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/ActivityLonglinesUIModel.java deleted file mode 100644 index 2f54ec9..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/ActivityLonglinesUIModel.java +++ /dev/null @@ -1,43 +0,0 @@ -package fr.ird.observe.ui.content.list.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.longline.ActivityLonglineDto; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.ui.content.list.ContentListUIModel; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ActivityLonglinesUIModel extends ContentListUIModel<TripLonglineDto, ActivityLonglineDto> { - - private static final long serialVersionUID = 1L; - - public ActivityLonglinesUIModel() { - super(TripLonglineDto.class, ActivityLonglineDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/TripLonglinesUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/TripLonglinesUI.jaxx deleted file mode 100644 index 92b1b2b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/TripLonglinesUI.jaxx +++ /dev/null @@ -1,67 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.list.ContentListUI superGenericType='ProgramDto, TripLonglineDto' - listText='{n("observe.common.trips.list")}' - emptyListMessage='{n("observe.message.no.trip.for.program")}'> - - <import> - fr.ird.observe.services.dto.longline.ActivityLonglineDto - fr.ird.observe.services.dto.longline.TripLonglineDto - fr.ird.observe.services.dto.referential.ProgramDto - fr.ird.observe.ui.actions.shared.SelectOpenNodeUIAction - fr.ird.observe.ui.actions.shared.MoveTripLonglinesUIAction - - static org.nuiton.i18n.I18n.n - </import> - - <style source="CommonListUI.jcss"/> - - <!-- handler --> - <TripLonglinesUIHandler id='handler' constructorParams='this'/> - - <!-- model --> - <TripLonglinesUIModel id='model'/> - - <!-- edit bean --> - <ProgramDto id='bean'/> - - <!-- override generic actions --> - <JButton id='gotoSelectedChild'/> - <JButton id='reopenChild'/> - <JButton id='gotoOpenChild' styleClass='gotoOpenTrip'/> - <JButton id='gotoOpenChild2' styleClass='gotoOpenTrip2'/> - <JButton id='createChild'/> - <JButton id='moveSelectedChildren'/> - - <!-- extra actions --> - <Table id="extraActions" fill='both' weightx='1' weighty='1' insets='0'> - <row weighty="1" weightx="1"> - <cell> - <JButton id='gotoOpenActivity' styleClass='gotoOpenActivity'/> - </cell> - <cell> - <JButton id='gotoOpenActivity2' styleClass='gotoOpenActivity2'/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.list.ContentListUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/TripLonglinesUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/TripLonglinesUIHandler.java deleted file mode 100644 index a3dbfba..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/TripLonglinesUIHandler.java +++ /dev/null @@ -1,112 +0,0 @@ -package fr.ird.observe.ui.content.list.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.DataReferenceSet; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.service.longline.TripLonglineService; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.list.ContentListUIHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.ArrayList; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; - -/** - * Created on 8/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class TripLonglinesUIHandler extends ContentListUIHandler<ProgramDto, TripLonglineDto> { - - /** Logger */ - static private final Log log = LogFactory.getLog(TripLonglinesUIHandler.class); - - public TripLonglinesUIHandler(TripLonglinesUI ui) { - super(ui, DataContextType.Program, DataContextType.TripLongline); - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - String openProgramId = dataContext.getOpenProgramId(); - - if (openProgramId == null) { - - // pas de program ouvert (donc pas de maree ouverte) - // on peut reouvrir une maree - addInfoMessage(n("observe.content.tripLongline.message.no.active.found")); - return ContentMode.CREATE; - } - - // - // il existe un maree ouverte - // - - if (dataContext.isSelectedOpen(ProgramDto.class)) { - - // le programme courant a une maree ouverte - addInfoMessage(n("observe.content.tripLongline.message.active.found")); - return ContentMode.UPDATE; - } - - // - // la marée ouverte est dans un autre programme - // - - addInfoMessage(n("observe.content.tripLongline.message.active.found.for.other.program")); - return ContentMode.READ; - } - - @Override - protected void finalizeOpenUI() { - Class referenceType = ProgramDto.class; - ReferentialReference<ProgramDto> programRef = getDataSource().getReferentialReference(referenceType, getSelectedParentId()); - String title = getDecoratorService().getReferentialReferenceDecorator(referenceType).toString(programRef); - getUi().setContentTitle(title); - } - - @Override - protected List<DataReference<TripLonglineDto>> getChilds(String parentId) { - - TripLonglineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripLonglineService(); - DataReferenceSet<TripLonglineDto> tripLonglineByProgram = service.getTripLonglineByProgram( parentId); - - if (log.isDebugEnabled()) { - log.debug("Will use " + tripLonglineByProgram.sizeReference() + " trips."); - } - - return new ArrayList<>(tripLonglineByProgram.getReferences()); - } -} - diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/TripLonglinesUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/TripLonglinesUIModel.java deleted file mode 100644 index ae7b15b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/longline/TripLonglinesUIModel.java +++ /dev/null @@ -1,51 +0,0 @@ -package fr.ird.observe.ui.content.list.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.ui.content.list.ContentListUIModel; - -import java.util.List; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class TripLonglinesUIModel extends ContentListUIModel<ProgramDto, TripLonglineDto> { - - private static final long serialVersionUID = 1L; - - public TripLonglinesUIModel() { - super(ProgramDto.class, TripLonglineDto.class); - } - - @Override - public void setData(List<DataReference<TripLonglineDto>> data) { - super.setData(data); - setSelectedDatas(null); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/ActivitySeinesUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/ActivitySeinesUI.jaxx deleted file mode 100644 index 3353e08..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/ActivitySeinesUI.jaxx +++ /dev/null @@ -1,69 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.list.ContentListUI superGenericType='RouteDto, ActivitySeineDto' - contentTitle='{n("observe.storage.activitySeines.title")}' listText='{n("observe.common.activities.list")}' - emptyListMessage='{n("observe.message.no.activity.for.route")}'> - - <import> - fr.ird.observe.services.dto.seine.ActivitySeineDto - fr.ird.observe.services.dto.seine.RouteDto - fr.ird.observe.ui.actions.shared.CloseAndCreateUIAction - fr.ird.observe.ui.actions.shared.CloseOpenUIAction - fr.ird.observe.ui.actions.shared.SelectOpenNodeUIAction - fr.ird.observe.ui.actions.shared.MoveActivitySeinesUIAction - - static org.nuiton.i18n.I18n.n - </import> - - <style source="CommonListUI.jcss"/> - - <!-- handler --> - <ActivitySeinesUIHandler id='handler' constructorParams='this'/> - - <!-- model --> - <ActivitySeinesUIModel id='model'/> - - <!-- edit bean --> - <RouteDto id='bean'/> - - <!-- override generic actions --> - <JButton id='gotoSelectedChild'/> - <JButton id='reopenChild'/> - <JButton id='gotoOpenChild' styleClass='gotoOpenActivity'/> - <JButton id='gotoOpenChild2' styleClass='gotoOpenActivity2'/> - <JButton id='createChild'/> - <JButton id='moveSelectedChildren'/> - - <!-- extra actions --> - <Table id='extraActions' fill="both" weightx="1" insets='2'> - <row> - <cell weightx="0.5" fill="both"> - <JButton id='close'/> - </cell> - <cell weightx="0.5"> - <JButton id='closeAndCreate'/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.list.ContentListUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/ActivitySeinesUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/ActivitySeinesUIHandler.java deleted file mode 100644 index c8eac64..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/ActivitySeinesUIHandler.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.list.impl.seine; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.DataReferenceSet; -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.services.service.seine.ActivitySeineService; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.list.ContentListUIHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.ArrayList; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class ActivitySeinesUIHandler extends ContentListUIHandler<RouteDto, ActivitySeineDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(ActivitySeinesUIHandler.class); - - public ActivitySeinesUIHandler(ActivitySeinesUI ui) { - super(ui, DataContextType.Route, DataContextType.ActivitySeine); - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - String openRouteId = dataContext.getOpenRouteId(); - - if (openRouteId == null) { - - // pas de route ouverte, donc on ne peut pas ouvrir une activité - addInfoMessage(n("observe.content.route.message.no.active.found")); - return ContentMode.READ; - } - - // - // il existe une route ouverte - // - - boolean openActivity = dataContext.isOpenActivity(); - - - if (dataContext.isSelectedOpen(RouteDto.class)) { - - // - // la route courante est ouverte - // - - // la route courante est ouverte - if (openActivity) { - - // il existe une activité ouverte dans la route courante - addInfoMessage(n("observe.storage.activitySeine.message.active.found")); - return ContentMode.UPDATE; - } - - // pas d'activité ouverte, on peut en ouvrir une - addInfoMessage(n("observe.storage.activitySeine.message.no.active.found")); - return ContentMode.CREATE; - } - - // - // la route ouverte est dans une autre maree - // - - if (openActivity) { - - // il existe une activité ouverte dans la route ouverte - addInfoMessage(n("observe.storage.activitySeine.message.active.found.for.other.route")); - } else { - - // il n'existe pas d'activité ouverte dans la route ouverte - addInfoMessage(n("observe.storage.activitySeine.message.no.active.found.for.other.route")); - } - - return ContentMode.READ; - - } - - @Override - protected List<DataReference<ActivitySeineDto>> getChilds(String parentId) { - - ActivitySeineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivitySeineService(); - DataReferenceSet<ActivitySeineDto> activitySeineByRoute = service.getActivitySeineByRoute(parentId); - - if (log.isDebugEnabled()) { - log.debug("Will use " + activitySeineByRoute.sizeReference() + " activities."); - } - - return new ArrayList<>(activitySeineByRoute.getReferences()); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/ActivitySeinesUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/ActivitySeinesUIModel.java deleted file mode 100644 index 5ed9d2e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/ActivitySeinesUIModel.java +++ /dev/null @@ -1,43 +0,0 @@ -package fr.ird.observe.ui.content.list.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.ui.content.list.ContentListUIModel; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ActivitySeinesUIModel extends ContentListUIModel<RouteDto, ActivitySeineDto> { - - private static final long serialVersionUID = 1L; - - public ActivitySeinesUIModel() { - super(RouteDto.class, ActivitySeineDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/RoutesUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/RoutesUI.jaxx deleted file mode 100644 index 7797f98..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/RoutesUI.jaxx +++ /dev/null @@ -1,68 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.list.ContentListUI superGenericType='TripSeineDto, RouteDto' - contentTitle='{n("observe.content.routes.title")}' listText='{n("observe.common.routes.list")}' - emptyListMessage='{n("observe.message.no.route.for.maree")}'> - - <import> - fr.ird.observe.services.dto.seine.ActivitySeineDto - fr.ird.observe.services.dto.seine.TripSeineDto - fr.ird.observe.services.dto.seine.RouteDto - fr.ird.observe.ui.actions.shared.SelectOpenNodeUIAction - fr.ird.observe.ui.actions.shared.MoveRoutesUIAction - - static org.nuiton.i18n.I18n.n - </import> - - <style source="CommonListUI.jcss"/> - - <!-- handler --> - <RoutesUIHandler id='handler' constructorParams='this'/> - - <!-- model --> - <RoutesUIModel id='model'/> - - <!-- edit bean --> - <TripSeineDto id='bean'/> - - <!-- override generic actions --> - <JButton id='gotoSelectedChild'/> - <JButton id='reopenChild'/> - <JButton id='gotoOpenChild' styleClass='gotoOpenRoute'/> - <JButton id='gotoOpenChild2' styleClass='gotoOpenRoute2'/> - <JButton id='createChild'/> - <JButton id='moveSelectedChildren'/> - - <!-- extra actions --> - <Table id='extraActions' fill="both" weightx="1" insets='2'> - <row weighty="1" weightx="1"> - <cell> - <JButton id='gotoOpenActivity' styleClass='gotoOpenActivity'/> - </cell> - <cell> - <JButton id='gotoOpenActivity2' styleClass='gotoOpenActivity2'/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.list.ContentListUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/RoutesUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/RoutesUIHandler.java deleted file mode 100644 index ec2a0e9..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/RoutesUIHandler.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.list.impl.seine; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.DataReferenceSet; -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.services.service.seine.RouteService; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.list.ContentListUIHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.ArrayList; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class RoutesUIHandler extends ContentListUIHandler<TripSeineDto, RouteDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(RoutesUIHandler.class); - - public RoutesUIHandler(RoutesUI ui) { - super(ui, DataContextType.TripSeine, DataContextType.Route); - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - // autorisé à écrire - - String openTripId = dataContext.getOpenTripId(); - - if (openTripId == null) { - - // pas de marée d'ouverte, donc on ne peut pas ouvrir une route - addInfoMessage(n("observe.content.tripSeine.message.no.active.found")); - return ContentMode.READ; - } - - // - // il existe une marée ouverte - // - - boolean openRoute = dataContext.isOpenRoute(); - - if (dataContext.isSelectedOpen(TripSeineDto.class)) { - - // la marée courante est ouverte - - if (openRoute) { - - // il existe une route ouverte dans la marée courante - addInfoMessage(n("observe.content.route.message.active.found")); - return ContentMode.UPDATE; - } - - // pas de route ouverte, on peut en ouvrir une - addInfoMessage(n("observe.content.route.message.no.active.found")); - return ContentMode.CREATE; - } - - // - // la marée ouverte est dans un autre program - // - - if (openRoute) { - - //il existe une route existe dans la maree ouverte - addInfoMessage(n("observe.content.route.message.active.found.for.other.trip")); - } else { - - // pas de route ouverte dans la maree ouverte - addInfoMessage(n("observe.content.route.message.no.active.found.for.other.trip")); - } - - return ContentMode.READ; - } - - @Override - protected List<DataReference<RouteDto>> getChilds(String parentId) { - - RouteService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newRouteService(); - DataReferenceSet<RouteDto> routeByTripSeine = service.getRouteByTripSeine(parentId); - - if (log.isDebugEnabled()) { - log.debug("Will use " + routeByTripSeine.sizeReference() + " routes."); - } - - return new ArrayList<>(routeByTripSeine.getReferences()); - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/RoutesUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/RoutesUIModel.java deleted file mode 100644 index c56922e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/RoutesUIModel.java +++ /dev/null @@ -1,43 +0,0 @@ -package fr.ird.observe.ui.content.list.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.ui.content.list.ContentListUIModel; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class RoutesUIModel extends ContentListUIModel<TripSeineDto, RouteDto> { - - private static final long serialVersionUID = 1L; - - public RoutesUIModel() { - super(TripSeineDto.class, RouteDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/TripSeinesUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/TripSeinesUI.jaxx deleted file mode 100644 index 07f9412..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/TripSeinesUI.jaxx +++ /dev/null @@ -1,77 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.list.ContentListUI - superGenericType='ProgramDto, TripSeineDto' - listText='{n("observe.common.trips.list")}' - emptyListMessage='{n("observe.message.no.trip.for.program")}'> - - <import> - fr.ird.observe.services.dto.seine.ActivitySeineDto - fr.ird.observe.services.dto.seine.TripSeineDto - fr.ird.observe.services.dto.seine.RouteDto - fr.ird.observe.services.dto.referential.ProgramDto - fr.ird.observe.ui.actions.shared.SelectOpenNodeUIAction - fr.ird.observe.ui.actions.shared.MoveTripSeinesUIAction - - static org.nuiton.i18n.I18n.n - </import> - - <style source="CommonListUI.jcss"/> - - <!-- handler --> - <TripSeinesUIHandler id='handler' constructorParams='this'/> - - <!-- model --> - <TripSeinesUIModel id='model'/> - - <!-- edit bean --> - <ProgramDto id='bean'/> - - <!-- override generic actions --> - <JButton id='gotoSelectedChild'/> - <JButton id='reopenChild'/> - <JButton id='gotoOpenChild' styleClass='gotoOpenTrip'/> - <JButton id='gotoOpenChild2' styleClass='gotoOpenTrip2'/> - <JButton id='createChild'/> - <JButton id='moveSelectedChildren'/> - - <!-- extra actions --> - <Table id="extraActions" fill='both' weightx='1' weighty='1' insets='0'> - <row weighty="1" weightx="1"> - <cell> - <JButton id='gotoOpenRoute' styleClass='gotoOpenRoute'/> - </cell> - <cell> - <JButton id='gotoOpenRoute2' styleClass='gotoOpenRoute2'/> - </cell> - </row> - <row weighty="1" weightx="1"> - <cell> - <JButton id='gotoOpenActivity' styleClass='gotoOpenActivity'/> - </cell> - <cell> - <JButton id='gotoOpenActivity2' styleClass='gotoOpenActivity2'/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.list.ContentListUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/TripSeinesUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/TripSeinesUIHandler.java deleted file mode 100644 index deed9f9..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/TripSeinesUIHandler.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.list.impl.seine; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.DataReferenceSet; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.services.service.seine.TripSeineService; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.list.ContentListUIHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.ArrayList; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class TripSeinesUIHandler extends ContentListUIHandler<ProgramDto, TripSeineDto> { - - /** Logger */ - static private final Log log = LogFactory.getLog(TripSeinesUIHandler.class); - - public TripSeinesUIHandler(TripSeinesUI ui) { - super(ui, DataContextType.Program, DataContextType.TripSeine); - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - String openProgramId = dataContext.getOpenProgramId(); - - if (openProgramId == null) { - - // pas de program ouvert (donc pas de maree ouverte) - // on peut reouvrir une maree - addInfoMessage(n("observe.content.tripSeine.message.no.active.found")); - return ContentMode.CREATE; - } - - // - // il existe un maree ouverte - // - - if (dataContext.isSelectedOpen(ProgramDto.class)) { - - // le program courant a une maree ouverte - addInfoMessage(n("observe.content.tripSeine.message.active.found")); - return ContentMode.UPDATE; - } - - // - // la marée ouverte est dans un autre program - // - - addInfoMessage(n("observe.content.tripSeine.message.active.found.for.other.program")); - return ContentMode.READ; - } - - @Override - protected void finalizeOpenUI() { - Class referenceType = ProgramDto.class; - ReferentialReference<ProgramDto> programRef = getDataSource().getReferentialReference(referenceType, getSelectedParentId()); - String title = getDecoratorService().getReferentialReferenceDecorator(referenceType).toString(programRef); - getUi().setContentTitle(title); - } - - @Override - protected List<DataReference<TripSeineDto>> getChilds(String parentId) { - - TripSeineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripSeineService(); - DataReferenceSet<TripSeineDto> tripSeineByProgram = service.getTripSeineByProgram(parentId); - - if (log.isDebugEnabled()) { - log.debug("Will use " + tripSeineByProgram.sizeReference() + " trips."); - } - - return new ArrayList<>(tripSeineByProgram.getReferences()); - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/TripSeinesUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/TripSeinesUIModel.java deleted file mode 100644 index a245b37..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/list/impl/seine/TripSeinesUIModel.java +++ /dev/null @@ -1,52 +0,0 @@ -package fr.ird.observe.ui.content.list.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.ui.content.list.ContentListUIModel; - -import java.util.List; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class TripSeinesUIModel extends ContentListUIModel<ProgramDto, TripSeineDto> { - - private static final long serialVersionUID = 1L; - - public TripSeinesUIModel() { - super(ProgramDto.class, TripSeineDto.class); - } - - @Override - public void setData(List<DataReference<TripSeineDto>> data) { - super.setData(data); - setSelectedDatas(null); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/ContentOpenableUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/ContentOpenableUI.jaxx deleted file mode 100644 index b7cf93e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/ContentOpenableUI.jaxx +++ /dev/null @@ -1,114 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ContentUI - abstract='true' - superGenericType='E' - genericType='E extends IdDto' - > - - <import> - fr.ird.observe.services.dto.AbstractObserveDto - fr.ird.observe.services.dto.IdDto - - fr.ird.observe.ui.actions.shared.CancelCreateUIAction - fr.ird.observe.ui.actions.shared.CloseAndCreateUIAction - fr.ird.observe.ui.actions.shared.CloseOpenUIAction - fr.ird.observe.ui.actions.shared.DeleteDataUIAction - fr.ird.observe.ui.actions.shared.ReOpenUIAction - fr.ird.observe.ui.actions.shared.ResetEditUIAction - fr.ird.observe.ui.actions.shared.SaveEditUIAction - - javax.swing.SwingConstants - - </import> - - <!-- handler --> - <ContentOpenableUIHandler id='handler' genericType='E'/> - - <!-- model --> - <ContentOpenableUIModel id='model' genericType='E' - enabled='{!model.isReadingMode()}'/> - - <script><![CDATA[ - - public void openData() { - getHandler().openDataUI(); - } - - public void closeData() { - getHandler().closeDataUI(); - } - - public void closeAndCreateData() { - getHandler().closeAndCreateDataUI(); - } - ]]> - </script> - - <!-- actions --> - <Table id="actions" weightx='1' insets='0'> - <row> - <cell fill="both"> - <Table id='editActions' fill="both" weightx="1" insets='2'> - <row> - <cell weightx="0.5" fill="both"> - <JButton id='cancel'/> - </cell> - <cell weightx="0.5"> - <JButton id='reset'/> - </cell> - <cell weightx="0.5"> - <JButton id='save'/> - </cell> - <cell weightx="0.5"> - <JButton id='delete'/> - </cell> - </row> - </Table> - </cell> - </row> - <row insets='0'> - <cell fill='both'> - <Table id='extraActions' fill="both" weightx="1" insets='2' - visible='{model.isUpdatingMode()}'/> - </cell> - </row> - <row> - <cell fill="both"> - <Table id='openActions' fill="both" weightx="1" insets='2'> - <row> - <cell weightx="0.5"> - <JButton id='reopen'/> - </cell> - <cell weightx="0.5" fill="both"> - <JButton id='close'/> - </cell> - <cell weightx="0.5"> - <JButton id='closeAndCreate'/> - </cell> - </row> - </Table> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/ContentOpenableUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/ContentOpenableUIHandler.java deleted file mode 100644 index 16ffa3d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/ContentOpenableUIHandler.java +++ /dev/null @@ -1,314 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.open; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.ContentUIHandler; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.validation.ValidationContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.validator.NuitonValidatorScope; - -import static org.nuiton.i18n.I18n.t; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public abstract class ContentOpenableUIHandler<E extends IdDto> extends ContentUIHandler<E> { - - protected static final String POSITION_OPENABLE = "positionOpenable"; - - /** Logger */ - static private final Log log = LogFactory.getLog(ContentOpenableUIHandler.class); - - protected final String closeMessage; - - public ContentOpenableUIHandler(ContentOpenableUI<E> ui, - DataContextType parentType, - DataContextType type, - String closeMessage) { - super(ui, parentType, type); - this.closeMessage = closeMessage; - } - - protected abstract boolean obtainCanReopen(boolean create); - - @Override - public ContentOpenableUI<E> getUi() { - return (ContentOpenableUI<E>) super.getUi(); - } - - @Override - public ContentOpenableUIModel<E> getModel() { - return (ContentOpenableUIModel<E>) super.getModel(); - } - - @Override - protected boolean computeCanWrite(ObserveSwingDataSource source) { - return source.canWriteData(); - } - - protected abstract boolean doOpenData(); - - public final void openDataUI() { - boolean ok = false; - try { - ok = doOpenData(); - } catch (Exception e) { - UIHelper.handlingError(e); - } finally { - - if (ok) { - afterOpenData(); - } - } - } - - public final void afterOpenData() { - - ContentOpenableUI<E> ui = getUi(); - - // On charge les ensembles de références utilisées dans les combobox - updateUiWithReferenceSetsFromModel(); - - // on repaint le parent (le program devient alors ouvert) - ObserveTreeHelper treeHelper = getTreeHelper(ui); - treeHelper.reloadSelectedNode(true, true); -// ObserveNode node = treeHelper.getSelectedNode(); -// treeHelper.refreshNode(node.getParent(), true); - - // on chage l'état 'canReopen' du model - ui.getModel().setCanReopen(false); - - // on lance l'édition - ui.restartEdit(); - } - - public final void closeDataUI() { - boolean ok = false; - try { - ok = doCloseData(); - } catch (Exception e) { - UIHelper.handlingError(e); - } finally { - - if (ok) { - afterCloseData(); - } - } - } - - public abstract boolean doCloseData(); - - public final void afterCloseData() { - - ContentOpenableUI<E> ui = getUi(); - - ContentOpenableUIModel<E> model = getModel(); - - model.setCanReopen(true); - E bean = getBean(); - - ui.stopEdit(); - model.setMode(ContentMode.READ); - - removeAllMessages(ui); - addMessage(ui, NuitonValidatorScope.INFO, - getEntityLabel(bean.getClass()), t(closeMessage)); - - ObserveTreeHelper treeHelper = getTreeHelper(ui); -// ObserveNode selectedNode = treeHelper.getSelectedNode(); -// if (bean instanceof Trip) { -// // le program peut change d'etat open -// selectedNode = selectedNode.getParent(); -// } -// treeHelper.refreshNode(selectedNode, true); - treeHelper.reloadSelectedNode(bean instanceof TripSeineDto || bean instanceof TripLonglineDto, true); - updateActions(); - } - - @Override - protected void afterSave(boolean refresh) { - - super.afterSave(refresh); - - ContentOpenableUI<E> ui = getUi(); - - int position = ui.getContextValue(Integer.class, POSITION_OPENABLE); - ObserveTreeHelper treeHelper = getTreeHelper(ui); - - ObserveNode node = treeHelper.getSelectedNode(); - ObserveNode parentNode = node.getParent(); - boolean create = node.getId() == null; - - E bean = getBean(); - - int oldPosition; - if (create) { - oldPosition = parentNode.getChildCount(); - } else { - oldPosition = parentNode.getIndex(node); - } - - if (create) { - - // on passe en mode mise à jour - getModel().setMode(ContentMode.UPDATE); - - // on supprime le noeud temporaire - treeHelper.removeNode(node); - - // on crée le noeud final de la marée - node = treeHelper.addOpenable(parentNode, bean); - - // arrêt de l'édition de l'écran courant - stopEditUI(); - - if (oldPosition != position) { - - // on doit repositionner le noeud - treeHelper.moveNode(parentNode, node, position); - } - - // on sélectionne le nouveau noeud - treeHelper.selectNode(node); - } else { - if (oldPosition != position) { - - // on doit repositionner le noeud - treeHelper.moveNode(parentNode, node, position); - - // et le selectionner - treeHelper.selectNode(node); - } - - // on repaint le noeud et ses enfants -// treeHelper.refreshNode(node, true); - treeHelper.reloadSelectedNode(false, true); - -// treeHelper.refreshNode(node, false); - } - } - - /** - * Clôturer la marée ouverte puis en créer une nouvelle. - * - * @since 1.5 - */ - public final void closeAndCreateDataUI() { - - // fermeture de la donnée - try { - boolean b = doCloseData(); - if (!b) { - - // la fermeture a ete abandonnee - if (log.isInfoEnabled()) { - log.info(prefix + "Stop closing data..."); - } - return; - } - } catch (Exception eee) { - UIHelper.handlingError("Could not close current data", eee); - } - - stopEditUI(); - - // création d'une nouvelle donnée - - ObserveTreeHelper treeHelper = getTreeHelper(getUi()); - - treeHelper.reloadSelectedNode(false, true); - - ObserveNode parentNode = treeHelper.getSelectedNode().getParent(); - if (log.isDebugEnabled()) { - log.debug("PARENT NODE = " + parentNode); - } - treeHelper.addUnsavedNode(parentNode, getBeanType()); - } - - protected final void obtainChildPosition(E bean){ - - String containerId = getSelectedParentId(); - - int position = getOpenablePosition(containerId, bean); - - if (log.isDebugEnabled()) { - log.debug("Position of child : " + position); - } - - getUi().setContextValue(position, POSITION_OPENABLE); - } - - protected abstract int getOpenablePosition(String parentId, E bean); - - protected final void finalizeOpenUI(ContentMode mode, boolean create) { - -// // utilisation du mode requis -// setContentMode(mode); - - boolean historicalData = false; - - ContentOpenableUIModel<E> model = getUi().getModel(); - - if (!create) { - - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ValidationContext context = applicationContext.getValidationContext(); - TripSeineDto currentTripSeine = context.getCurrentTripSeine(); - - if (currentTripSeine != null && currentTripSeine.isHistoricalData()) { - - if (log.isInfoEnabled()) { - log.info(prefix + "Using a historical fish trip " + currentTripSeine.getId()); - } - historicalData = true; - } - - } - - model.setHistoricalData(historicalData); - - boolean canReopen = obtainCanReopen(create); - - if (log.isInfoEnabled()) { - log.info(prefix + "historical data ? = " + historicalData); - log.info(prefix + "can reopen ? = " + canReopen); - } - model.setCanReopen(canReopen); - - if (mode != ContentMode.READ) { - getUi().startEdit(null); - } - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/ContentOpenableUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/ContentOpenableUIModel.java deleted file mode 100644 index c7bad89..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/ContentOpenableUIModel.java +++ /dev/null @@ -1,68 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.open; - -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.ui.content.ContentUIModel; - -/** - * Le modèle pour un écran d'édition avec des fils. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.5 - */ -public abstract class ContentOpenableUIModel<E extends IdDto> extends ContentUIModel<E> { - - public static final String PROPERTY_CAN_REOPEN = "canReopen"; - - public static final String PROPERTY_HISTORICAL_DATA = "historicalData"; - - private static final long serialVersionUID = 1L; - - protected boolean canReopen; - - protected boolean historicalData; - - public ContentOpenableUIModel(Class<E> beanType) { - super(beanType); - } - - public boolean isCanReopen() { - return canReopen; - } - - public void setCanReopen(boolean canReopen) { - boolean old = isCanReopen(); - this.canReopen = canReopen; - firePropertyChange(PROPERTY_CAN_REOPEN, old, canReopen); - } - - public boolean isHistoricalData() { - return historicalData; - } - - public void setHistoricalData(boolean historicalData) { - boolean old = isHistoricalData(); - this.historicalData = historicalData; - firePropertyChange(PROPERTY_HISTORICAL_DATA, old, historicalData); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/ActivityLonglineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/ActivityLonglineUI.jaxx deleted file mode 100644 index 8e14c2e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/ActivityLonglineUI.jaxx +++ /dev/null @@ -1,147 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.open.ContentOpenableUI superGenericType='ActivityLonglineDto' - contentTitle='{n("observe.storage.activityLongline.title")}'> - - <style source="../../../Common.jcss"/> - - <import> - fr.ird.observe.services.dto.CommentableDto - fr.ird.observe.services.dto.longline.ActivityLonglineDto - fr.ird.observe.services.dto.longline.SetLonglineDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.FpaZoneDto - fr.ird.observe.services.dto.referential.longline.VesselActivityLonglineDto - fr.ird.observe.ui.actions.shared.DeleteDataUIAction - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - org.nuiton.jaxx.widgets.datetime.DateTimeEditor - org.nuiton.jaxx.widgets.gis.absolute.CoordinatesEditor - - java.awt.Dimension - - javax.swing.SwingConstants - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <ActivityLonglineUIHandler id='handler'/> - - <!-- model --> - <ActivityLonglineUIModel id='model'/> - - <!-- edit bean --> - <ActivityLonglineDto id='bean'/> - - <!-- validator --> - <BeanValidator id='validator' - autoField='true' - beanClass='fr.ird.observe.services.dto.longline.ActivityLonglineDto' - errorTableModel='{getErrorTableModel()}' - context='ui-create'> - - <field name='longitude' component='coordinatesEditor'/> - <field name='latitude' component='coordinatesEditor'/> - <field name='quadrant' component='coordinatesEditor'/> - - </BeanValidator> - - <!-- formulaire --> - <JPanel id="body" layout='{new BorderLayout()}'> - <Table fill='both' constraints="BorderLayout.CENTER"> - - <!-- date - time --> - <row> - <cell columns="2" weightx="1"> - <DateTimeEditor id='timeStamp' constructorParams='this'/> - </cell> - </row> - - <!-- position --> - <row> - <cell columns="2" weightx="1"> - <CoordinatesEditor id='coordinatesEditor' constructorParams='this'/> - </cell> - </row> - - <!-- activity vessel --> - <row> - <cell anchor='west'> - <JLabel id='vesselActivityLonglineLabel'/> - </cell> - <cell anchor='east' fill="both"> - <BeanComboBox id='vesselActivityLongline' genericType='ReferentialReference<VesselActivityLonglineDto>' _entityClass='VesselActivityLonglineDto.class' constructorParams='this'/> - </cell> - </row> - - <row> - <cell anchor='west'> - <JLabel id='fpaZoneLabel'/> - </cell> - <cell anchor='east' fill="both"> - <BeanComboBox id='fpaZone' genericType='ReferentialReference<FpaZoneDto>' _entityClass='FpaZoneDto.class' constructorParams='this'/> - </cell> - </row> - - <!-- température de surface --> - <row> - <cell anchor='west'> - <JLabel id='seaSurfaceTemperatureLabel'/> - </cell> - <cell anchor='east' fill="both"> - <NumberEditor id='seaSurfaceTemperature' constructorParams='this'/> - </cell> - </row> - - <!-- comment --> - <row> - <cell columns='2' weighty="1"> - <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2'/> - </JScrollPane> - </cell> - </row> - </Table> - </JPanel> - - <!-- surcharge des actions (pour appliquer la css specifique) --> - <JButton id='delete'/> - <JButton id='reopen'/> - <JButton id='close'/> - <JButton id='closeAndCreate'/> - <JButton id='actionDown'/> - - <Table id='extraActions' fill="both" weightx="1" insets='2' visible='{model.isUpdatingMode()}'> - <row> - <cell weightx="0.5" fill="both"> - <JButton id='addSet' - onActionPerformed='getHandler().addChild(SetLonglineDto.class)'/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.open.ContentOpenableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/ActivityLonglineUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/ActivityLonglineUI.jcss deleted file mode 100644 index 0f9c74b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/ActivityLonglineUI.jcss +++ /dev/null @@ -1,100 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#model { - editable:true; - modified:{validator.isChanged()}; - valid:{validator.isValid()}; -} - -#timeStamp { - propertyDate:{ActivityLonglineDto.PROPERTY_TIME_STAMP}; - propertyDayDate:{ActivityLonglineUIModel.PROPERTY_DATE}; - propertyTimeDate:{ActivityLonglineUIModel.PROPERTY_TIME}; - label:{t("observe.storage.activityLongline.timeStamp")}; - date:{bean.getTimeStamp()}; -} - -#coordinatesEditor { - propertyLatitude:{ActivityLonglineDto.PROPERTY_LATITUDE}; - propertyLongitude:{ActivityLonglineDto.PROPERTY_LONGITUDE}; - propertyQuadrant:{ActivityLonglineDto.PROPERTY_QUADRANT}; -} - -#vesselActivityLonglineLabel { - text:"observe.storage.activityLongline.vesselActivityLongline"; - labelFor:{vesselActivityLongline}; -} - -#vesselActivityLongline { - property:{ActivityLonglineDto.PROPERTY_VESSEL_ACTIVITY_LONGLINE}; - selectedItem:{bean.getVesselActivityLongline()}; - enabled:{!model.isUpdatingMode()}; -} - -#fpaZoneLabel { - text:"observe.storage.activityLongline.fpaZone"; - labelFor:{fpaZone}; -} - -#fpaZone { - property:{ActivityLonglineDto.PROPERTY_FPA_ZONE}; - selectedItem:{bean.getFpaZone()}; -} - -#seaSurfaceTemperatureLabel { - text:"observe.storage.activityLongline.seaSurfaceTemperature"; - labelFor:{seaSurfaceTemperature}; -} - -#seaSurfaceTemperature { - property:{ActivityLonglineDto.PROPERTY_SEA_SURFACE_TEMPERATURE}; - model:{bean.getSeaSurfaceTemperature()}; - useFloat:true; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL2_PATTERN}; -} - -#reopen { - _toolTipText:{t("observe.content.action.reopen.activity.tip")}; -} - -#close { - enabled:{!model.isModified() && (model.isHistoricalData() || model.isValid())}; - _toolTipText:{t("observe.action.close.activity.tip")}; -} - -#closeAndCreate { - enabled:{!model.isModified() && (model.isHistoricalData() || model.isValid())}; - _text:{t("observe.content.action.closeAndCreate.activity")}; - _toolTipText:{t("observe.content.action.closeAndCreate.activity.tip")}; -} - -#delete { - _toolTipText:{t("observe.action.delete.activity.tip")}; -} - -#addSet { - actionIcon:add; - text:"observe.action.add.setLongline"; - toolTipText:"observe.action.add.setLongline.tip"; - enabled:{!model.isModified() && model.isValid() && model.isSetOperation() && ! bean.isHasSetLongline()}; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/ActivityLonglineUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/ActivityLonglineUIHandler.java deleted file mode 100644 index 0aefb66..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/ActivityLonglineUIHandler.java +++ /dev/null @@ -1,363 +0,0 @@ -package fr.ird.observe.ui.content.open.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.longline.ActivityLonglineDto; -import fr.ird.observe.services.dto.longline.ActivityLonglineDtos; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.dto.result.TripChildSaveResultDto; -import fr.ird.observe.services.service.longline.ActivityLonglineService; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.ContentUIModel; -import fr.ird.observe.ui.content.open.ContentOpenableUIHandler; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.validator.NuitonValidatorScope; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 8/29/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class ActivityLonglineUIHandler extends ContentOpenableUIHandler<ActivityLonglineDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(ActivityLonglineUIHandler.class); - - static { - - n("observe.common.latitude"); - n("observe.common.longitude"); - - } - -// static ImmutableSet<String> COORDINATES_PROPERTIES = ImmutableSet.of(ActivityLongline.PROPERTY_QUADRANT, -// ActivityLongline.PROPERTY_LATITUDE, -// ActivityLongline.PROPERTY_LONGITUDE); - -// private LogPropertyChanges logCoordinatesChanges; - - public ActivityLonglineUIHandler(ActivityLonglineUI ui) { - super(ui, - DataContextType.TripLongline, - DataContextType.ActivityLongline, - n("observe.storage.activityLongline.message.not.open")); -// this.logCoordinatesChanges = new LogPropertyChanges(COORDINATES_PROPERTIES); - } - - @Override - public ActivityLonglineUI getUi() { - return (ActivityLonglineUI) super.getUi(); - } - - @Override - protected boolean doOpenData() { - boolean result = getOpenDataManager().canOpenActivityLongline(getSelectedParentId()); - if (result) { - getOpenDataManager().openActivityLongline(getSelectedParentId(), getSelectedId()); - } - return result; - } - - @Override - public boolean doCloseData() { - boolean result = getOpenDataManager().isOpenActivityLongline(getSelectedId()); - if (result) { - getOpenDataManager().closeActivityLongline(getSelectedId()); - } - return result; - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - String activityId = getSelectedId(); - - if (activityId == null) { - - // mode creation - return ContentMode.CREATE; - } - - // l'activity existe en base - if (getOpenDataManager().isOpenActivityLongline(getSelectedId())) { - - // l'activity est ouverte, donc modifiable - return ContentMode.UPDATE; - } - - ActivityLonglineUI ui = getUi(); - - // l'activity n'est pas ouverte, donc pas éditable - if (!getOpenDataManager().isOpenTripLongline(getSelectedParentId())) { - - // la marée n'est pas ouverte - addMessage(ui, - NuitonValidatorScope.INFO, - getEntityLabel(TripLonglineDto.class), - t("observe.content.tripLongline.message.not.open")); - - if (getModel().isHistoricalData()) { - - addInfoMessage(t("observe.message.historical.data")); - } - - } else { - - // seule l'activity n'est pas ouverte - addInfoMessage(t(closeMessage)); - } - - return ContentMode.READ; - } - -// @Override -// public void initUI() { -// super.initUI(); -// getBean().removePropertyChangeListener(logCoordinatesChanges); -// getBean().addPropertyChangeListener(logCoordinatesChanges); -// } - - @Override - public void openUI() { - super.openUI(); - - getUi().getCoordinatesEditor().resetModel(); - - String tripId = getSelectedParentId(); - String activityId = getSelectedId(); - - if (log.isInfoEnabled()) { - log.info(prefix + "tripId = " + tripId); - log.info(prefix + "activityId = " + activityId); - } - - ContentMode mode = computeContentMode(); - if (log.isInfoEnabled()) { - log.info(prefix + "content mode " + mode); - } - ActivityLonglineDto bean = getBean(); - - boolean create = activityId == null; - - Form<ActivityLonglineDto> form; - if (create) { - - // create mode - form = getActivityLonglineService().preCreate(tripId); - - } else { - - // update mode - form = getActivityLonglineService().loadForm(activityId); - - } - - setContentMode(mode); - - loadReferentialReferenceSetsInModel(form); - - getModel().setForm(form); - ActivityLonglineDtos.copyActivityLonglineDto(form.getObject(), bean); - - if (log.isDebugEnabled()) { - log.debug(" long - lat = " + bean.getLongitude() + - " - " + bean.getLatitude()); - } - finalizeOpenUI(mode, create); - - // Mise à jour du composant de coordonnées - // 1. Mise à jour latitude/longitude: - getUi().getCoordinatesEditor().setLatitudeAndLongitude(bean.getLatitude(), bean.getLongitude()); - - // 2. Mise à jour du quadrant : - // Si le bean de données contient un quadrant, on met simplement à jour le composant de coordonnées pour sélectionner le quadrant voulu - // sinon, on réinitialise les quadrants du composant afin qu'aucun d'eux ne soit sélectionné (par exemple dans le cas de la création de la première activité d'une marée) - if (bean.getQuadrant() != null) { - getUi().getCoordinatesEditor().setQuadrant(bean.getQuadrant()); - } else { - resetQuadrant(getUi().getCoordinatesEditor()); - } - - getUi().getCoordinatesEditor().setQuadrant(bean.getQuadrant()); - - // on annule la modification engendree par ce binding - getModel().setModified(create); - } - - @Override - public void startEditUI(String... binding) { - ActivityLonglineUI ui = getUi(); - - ContentUIModel<ActivityLonglineDto> model = getModel(); - - boolean create = model.getMode() == ContentMode.CREATE; - String contextName = getValidatorContextName(model.getMode()); - ui.getValidator().setContext(contextName); - if (create) { - addMessage(ui, - NuitonValidatorScope.INFO, - getEntityLabel(ActivityLonglineDto.class), - t("observe.storage.activityLongline.message.creating")); - } else { - addMessage(ui, - NuitonValidatorScope.INFO, - getEntityLabel(ActivityLonglineDto.class), - t("observe.storage.activityLongline.message.updating")); - } - - super.startEditUI( - ActivityLonglineUI.BINDING_TIME_STAMP_DATE, - ActivityLonglineUI.BINDING_SEA_SURFACE_TEMPERATURE_MODEL, - ActivityLonglineUI.BINDING_COMMENT2_TEXT, - ActivityLonglineUI.BINDING_VESSEL_ACTIVITY_LONGLINE_SELECTED_ITEM, - ActivityLonglineUI.BINDING_FPA_ZONE_SELECTED_ITEM, - ActivityLonglineUI.BINDING_CLOSE_ENABLED, - ActivityLonglineUI.BINDING_CLOSE_AND_CREATE_ENABLED); - model.setModified(create); - } - - @Override - protected boolean doSave(ActivityLonglineDto bean) throws Exception { - - boolean notPersisted = bean.isNotPersisted(); - - if (log.isDebugEnabled()) { - log.debug(" long - lat = " + bean.getLongitude() + " - " + bean.getLatitude()); - } - - String tripId = getSelectedParentId(); - - TripChildSaveResultDto saveResult = getActivityLonglineService().save(tripId, getModel().getBean()); - saveResult.toDto(bean); - - setUpdateMareeNodeTag(saveResult.isTripEndDateUpdated()); - - obtainChildPosition(bean); - - // ouverture de l'activité après création - if (notPersisted) { - getOpenDataManager().openActivityLongline(getSelectedParentId(), bean.getId()); - } - - return true; - } - - @Override - protected int getOpenablePosition(String parentId, ActivityLonglineDto bean) { - int position = getActivityLonglineService().getActivityLonglinePositionInTripLongline(parentId, bean.getId()); - return position; - } - - @Override - protected boolean doDelete(ActivityLonglineDto bean) { - - if (askToDelete(bean)) { - return false; - } - if (log.isInfoEnabled()) { - log.info("Will delete Activity " + bean.getId()); - } - - String tripId = getSelectedParentId(); - boolean wasTripEndDateUpdated = getActivityLonglineService().delete(tripId, bean.getId()); - if (log.isInfoEnabled()) { - log.info("Delete done for Activity " + bean.getId()); - } - getOpenDataManager().closeActivityLongline(bean.getId()); - - setUpdateMareeNodeTag(wasTripEndDateUpdated); - return true; - - } - - @Override - protected void afterSave(boolean refresh) { - super.afterSave(refresh); - repaintTripNode(); - } - - @Override - protected void afterDelete() { - super.afterDelete(); - repaintTripNode(); - } - - @Override - protected boolean obtainCanReopen(boolean create) { - - boolean canReopen = !create && getOpenDataManager().canOpenActivityLongline(getSelectedParentId()); - return canReopen; - - } - - public static final String UPDATE_TRIP_NODE = "updateTripNode"; - - protected void setUpdateMareeNodeTag(boolean wasUpdated) { - - if (wasUpdated) { - - // la date de fin a ete modifiee, il faut : redessiner le noeud de la maree le repositionner - getUi().setContextValue(Boolean.TRUE, UPDATE_TRIP_NODE); - - } else { - - getUi().removeContextValue(Boolean.class, UPDATE_TRIP_NODE); - - } - - } - - protected void repaintTripNode() { - - Boolean updateTripNode = getUi().getContextValue(Boolean.class, UPDATE_TRIP_NODE); - - getUi().removeContextValue(Boolean.class, UPDATE_TRIP_NODE); - - if (updateTripNode == null || !updateTripNode) { - return; - } - - ObserveTreeHelper treeHelper = getTreeHelper(getUi()); - ObserveNode tripNode = treeHelper.getSelectedNode().getParent().getParent(); - if (log.isInfoEnabled()) { - log.info("Refresh trip node : " + tripNode); - } - treeHelper.reloadNode(tripNode, false); - - } - - protected ActivityLonglineService getActivityLonglineService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivityLonglineService(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/ActivityLonglineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/ActivityLonglineUIModel.java deleted file mode 100644 index 7978825..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/ActivityLonglineUIModel.java +++ /dev/null @@ -1,89 +0,0 @@ -package fr.ird.observe.ui.content.open.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.longline.ActivityLonglineDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.longline.VesselActivityLonglineDto; -import fr.ird.observe.services.dto.referential.longline.VesselActivityLonglineDtos; -import fr.ird.observe.ui.content.open.ContentOpenableUIModel; -import org.nuiton.util.DateUtil; - -import java.util.Date; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ActivityLonglineUIModel extends ContentOpenableUIModel<ActivityLonglineDto> { - - private static final long serialVersionUID = 1L; - - public static final String PROPERTY_SET_OPERATION = "setOperation"; - - public static final String PROPERTY_DATE = "date"; - - public static final String PROPERTY_TIME = "time"; - - public ActivityLonglineUIModel() { - super(ActivityLonglineDto.class); - - getBean().addPropertyChangeListener(ActivityLonglineDto.PROPERTY_VESSEL_ACTIVITY_LONGLINE, evt -> { - boolean oldValue = VesselActivityLonglineDtos.isSetOperation((ReferentialReference<VesselActivityLonglineDto>) evt.getOldValue()); - boolean newValue = VesselActivityLonglineDtos.isSetOperation((ReferentialReference<VesselActivityLonglineDto>) evt.getNewValue()); - firePropertyChange(PROPERTY_SET_OPERATION, oldValue, newValue); - }); - } - - public boolean isSetOperation() { - return VesselActivityLonglineDtos.isSetOperation(bean.getVesselActivityLongline()); - } - - public Date getDate() { - Date timeStamp = bean.getTimeStamp(); - return timeStamp == null ? null : DateUtil.getDay(timeStamp); - } - - public Date getTime() { - Date timeStamp = bean.getTimeStamp(); - return timeStamp == null ? null : DateUtil.getTime(timeStamp, false, false); - } - - public void setDate(Date date) { - Date timeStamp = bean.getTimeStamp(); - if (timeStamp != null) { - Date dateAndTime = date == null ? timeStamp : DateUtil.getDateAndTime(date, timeStamp, true, false); - bean.setTimeStamp(dateAndTime); - } - } - - public void setTime(Date time) { - Date timeStamp = bean.getTimeStamp(); - if (timeStamp != null) { - Date dateAndTime = time == null ? timeStamp : DateUtil.getDateAndTime(timeStamp, time, false, false); - bean.setTimeStamp(dateAndTime); - } - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/TripLonglineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/TripLonglineUI.jaxx deleted file mode 100644 index d638103..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/TripLonglineUI.jaxx +++ /dev/null @@ -1,242 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.open.ContentOpenableUI superGenericType='TripLonglineDto' - contentTitle='{n("observe.content.tripLongline.title")}'> - - <style source="../../../Common.jcss"/> - - <import> - fr.ird.observe.services.dto.CommentableDto - fr.ird.observe.services.dto.longline.TripLonglineDto - fr.ird.observe.services.dto.longline.ActivityLonglineDto - fr.ird.observe.services.dto.longline.TripLonglineActivityDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.HarbourDto - fr.ird.observe.services.dto.referential.PersonDtos - fr.ird.observe.services.dto.referential.VesselDto - fr.ird.observe.services.dto.referential.VesselDtos - fr.ird.observe.services.dto.referential.PersonDto - fr.ird.observe.services.dto.referential.OceanDto - fr.ird.observe.services.dto.referential.longline.TripTypeDto - fr.ird.observe.ui.actions.shared.DeleteDataUIAction - fr.ird.observe.ui.util.tripMap.TripMapUI - - org.jdesktop.swingx.JXDatePicker - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - java.awt.Dimension - java.beans.PropertyChangeEvent - java.beans.PropertyChangeListener - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.apache.commons.lang3.StringUtils.isEmpty - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <TripLonglineUIHandler id='handler'/> - - <!-- model --> - <TripLonglineUIModel id='model'/> - - <!-- edit bean --> - <TripLonglineDto id='bean'/> - - <!-- validator --> - <BeanValidator id='validator' - beanClass='fr.ird.observe.services.dto.longline.TripLonglineDto' - errorTableModel='{getErrorTableModel()}' - autoField='true' - context='ui-update'> - <field name='activityLongline' component='{actionDown}'/> - </BeanValidator> - - <script><![CDATA[ - -protected boolean canEditOcean(java.util.LinkedHashSet<TripLonglineActivityDto> activities) { - return activities == null || activities.isEmpty(); -} - -]]> - </script> - - <!-- formulaire --> - <JPanel id="body" layout='{new BorderLayout()}'> - <JTabbedPane id='tripLonglineTabPane' constraints='BorderLayout.CENTER'> - <tab id='generalTab'> - <Table fill="both"> - - <!-- tripType --> - <row> - <cell anchor='west'> - <JLabel id='tripTypeLabel'/> - </cell> - <cell anchor='east'> - <BeanComboBox id='tripType' constructorParams='this' genericType='ReferentialReference<TripTypeDto>' _entityClass='TripTypeDto.class'/> - </cell> - </row> - - <!-- captain --> - <row> - <cell anchor='west'> - <JLabel id='captainLabel'/> - </cell> - <cell anchor='east'> - <BeanComboBox id='captain' constructorParams='this' genericType='ReferentialReference<PersonDto>' _entityClass='PersonDto.class'/> - </cell> - </row> - - <!-- observer --> - <row> - <cell anchor='west'> - <JLabel id='observerLabel'/> - </cell> - <cell anchor='east'> - <BeanComboBox id='observer' constructorParams='this' genericType='ReferentialReference<PersonDto>' _entityClass='PersonDto.class'/> - </cell> - </row> - - <!-- dataEntryOperator --> - <row> - <cell anchor='west'> - <JLabel id='dataEntryOperatorLabel'/> - </cell> - <cell anchor='east'> - <BeanComboBox id='dataEntryOperator' constructorParams='this' genericType='ReferentialReference<PersonDto>' _entityClass='PersonDto.class'/> - </cell> - </row> - - <!-- vessel --> - <row> - <cell anchor='west'> - <JLabel id='vesselLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='vessel' constructorParams='this' genericType='ReferentialReference<VesselDto>' _entityClass='VesselDto.class'/> - </cell> - </row> - - <!-- ocean (editable uniquement si pas de route saisie) --> - <row> - <cell anchor='west'> - <JLabel id='oceanLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='ocean' genericType='ReferentialReference<OceanDto>' _entityClass='OceanDto.class' constructorParams='this'/> - </cell> - </row> - - <!-- departureHarbour --> - <row> - <cell anchor='west'> - <JLabel id='departureHarbourLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='departureHarbour' genericType='ReferentialReference<HarbourDto>' _entityClass='HarbourDto.class' constructorParams='this'/> - </cell> - </row> - - <!-- landingHarbour --> - <row> - <cell anchor='west'> - <JLabel id='landingHarbourLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='landingHarbour' genericType='ReferentialReference<HarbourDto>' _entityClass='HarbourDto.class' constructorParams='this'/> - </cell> - </row> - - <!-- homeId --> - <row> - - <cell anchor='west'> - <JLabel id='homeIdLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel layout='{new BorderLayout()}'> - <JToolBar id='homeIdToolbar' constraints='BorderLayout.WEST'> - <JButton id='resetHomeId' styleClass='resetButton'/> - </JToolBar> - <JTextField id='homeId' constraints='BorderLayout.CENTER'/> - </JPanel> - </cell> - </row> - - <!-- totalFishingOperationsNumber --> - <row> - <cell anchor='west'> - <JLabel id='totalFishingOperationsNumberLabel'/> - </cell> - <cell anchor='west' weightx="0.5"> - <NumberEditor id='totalFishingOperationsNumber' constructorParams='this'/> - </cell> - </row> - - <!-- startDate --> - <row> - <cell anchor='west'> - <JLabel id='startDateLabel'/> - </cell> - <cell anchor='west' weightx="0.5"> - <JXDatePicker id='startDate'/> - </cell> - </row> - - <!-- endDate --> - <row> - <cell anchor='west'> - <JLabel id='endDateLabel'/> - </cell> - <cell anchor='west' weightx="0.5"> - <JXDatePicker id='endDate'/> - </cell> - </row> - - <!-- comment --> - <row> - <cell columns='2' fill='both' weighty="1"> - <JScrollPane id='comment' - onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2' - onKeyReleased='getModel().getBean().setComment(comment2.getText())'/> - </JScrollPane> - </cell> - </row> - </Table> - </tab> - <tab id="mapTab"> - <TripMapUI id="tripMap"/> - </tab> - </JTabbedPane> - </JPanel> - - <!-- surcharge des actions (pour appliquer la css specifique) --> - <JButton id='delete'/> - <JButton id='reopen'/> - <JButton id='close'/> - <JButton id='closeAndCreate'/> - <JButton id='actionDown'/> - -</fr.ird.observe.ui.content.open.ContentOpenableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/TripLonglineUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/TripLonglineUI.jcss deleted file mode 100644 index a97bd65..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/TripLonglineUI.jcss +++ /dev/null @@ -1,196 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -NumberEditor { - bean:{bean}; - useFloat:false; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; -} - -#generalTab { - title: {t("observe.content.tripLongline.tab.general")}; -} - -#mapTab { - title: {t("observe.content.tripLongline.tab.map")}; -} - -#model { - editable:true; - modified:{validator.isChanged()}; - valid:{validator.isValid()}; -} - -#observerLabel { - text:"observe.content.tripLongline.observer"; - labelFor:{observer}; -} - -#observer { - property:{TripLonglineDto.PROPERTY_OBSERVER}; - selectedItem:{bean.getObserver()}; -} - -#captainLabel { - text:"observe.content.tripLongline.captain"; - labelFor:{captain}; -} - -#captain { - property:{TripLonglineDto.PROPERTY_CAPTAIN}; - selectedItem:{bean.getCaptain()}; -} - -#dataEntryOperatorLabel { - text:"observe.content.tripLongline.dataEntryOperator"; - labelFor:{dataEntryOperator}; -} - -#dataEntryOperator { - property:{TripLonglineDto.PROPERTY_DATA_ENTRY_OPERATOR}; - selectedItem:{bean.getDataEntryOperator()}; -} - -#tripTypeLabel{ - text:"observe.content.tripLongline.tripType"; - labelFor:{tripType}; -} - -#tripType { - property:{TripLonglineDto.PROPERTY_TRIP_TYPE}; - selectedItem:{bean.getTripType()}; -} - -#vesselLabel{ - text:"observe.content.tripLongline.vessel"; - labelFor:{vessel}; -} - -#vessel { - property:{TripLonglineDto.PROPERTY_VESSEL}; - selectedItem:{bean.getVessel()}; -} - -#oceanLabel{ - text:"observe.content.tripLongline.ocean"; - labelFor:{ocean}; -} - -#ocean { - property:{TripLonglineDto.PROPERTY_OCEAN}; - selectedItem:{bean.getOcean()}; - enabled:{canEditOcean(bean.getActivityLongline())}; -} - -#departureHarbourLabel { - text:"observe.common.departureHarbour"; - labelFor:{departureHarbour}; -} - -#departureHarbour { - property:{TripLonglineDto.PROPERTY_DEPARTURE_HARBOUR}; - selectedItem:{bean.getDepartureHarbour()}; -} - -#landingHarbourLabel { - text:"observe.common.landingHarbour"; - labelFor:{landingHarbour}; -} - -#landingHarbour { - property:{TripLonglineDto.PROPERTY_LANDING_HARBOUR}; - selectedItem:{bean.getLandingHarbour()}; -} - -#totalFishingOperationsNumberLabel{ - text:"observe.content.tripLongline.totalFishingOperationsNumber"; - labelFor:{totalFishingOperationsNumber}; -} - -#totalFishingOperationsNumber { - property:{TripLonglineDto.PROPERTY_TOTAL_FISHING_OPERATIONS_NUMBER}; - model:{bean.getTotalFishingOperationsNumber()}; - useFloat:false; -} - -#homeIdLabel { - text:"observe.content.tripLongline.homeId"; - labelFor:{homeId}; -} - -#resetHomeId { - toolTipText:"observe.content.action.reset.homeId.tip"; - _resetPropertyName: {TripLonglineDto.PROPERTY_HOME_ID}; -} - -#homeId { - text:{getStringValue(bean.getHomeId())}; - _propertyName: {TripLonglineDto.PROPERTY_HOME_ID}; -} - -#startDateLabel { - text:"observe.content.tripLongline.startDate"; - labelFor:{startDate}; -} - -#startDate { - date:{bean.getStartDate()}; - _propertyName: {TripLonglineDto.PROPERTY_START_DATE}; -} - -#endDateLabel { - text:"observe.content.tripLongline.endDate"; - labelFor:{endDate}; -} - -#endDate { - date:{bean.getEndDate()}; - _propertyName: {TripLonglineDto.PROPERTY_END_DATE}; -} - -#comment { - columnHeaderView:{new JLabel(t("observe.common.comment"))}; - minimumSize:{new Dimension(10,50)}; -} - -#comment2 { - text:{getStringValue(bean.getComment())}; -} - -#reopen { - _toolTipText:{t("observe.content.action.reopen.maree.tip")}; -} - -#close { - enabled:{!model.isModified() && (model.isHistoricalData() || model.isValid()) && !dataContext.isOpenActivity()}; - _toolTipText:{t("observe.action.close.maree.tip")}; -} - -#closeAndCreate { - enabled:{!model.isModified() && (model.isHistoricalData() || model.isValid()) && !dataContext.isOpenActivity()}; - _text:{t("observe.content.action.closeAndCreate.maree")}; - _toolTipText:{t("observe.content.action.closeAndCreate.maree.tip")}; -} - -#delete { - _toolTipText:{t("observe.action.delete.maree.tip")}; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/TripLonglineUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/TripLonglineUIHandler.java deleted file mode 100644 index 1af8492..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/TripLonglineUIHandler.java +++ /dev/null @@ -1,373 +0,0 @@ -package fr.ird.observe.ui.content.open.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.TripMapDto; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.dto.longline.TripLonglineDtos; -import fr.ird.observe.services.dto.referential.PersonDtos; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.VesselDtos; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.service.longline.TripLonglineService; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.open.ContentOpenableUIHandler; -import fr.ird.observe.ui.content.open.ContentOpenableUIModel; -import fr.ird.observe.ui.util.tripMap.TripMapUI; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.util.DateUtil; - -import javax.swing.JTabbedPane; -import javax.swing.SwingUtilities; -import java.util.Collection; -import java.util.Date; -import java.util.LinkedList; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 8/27/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class TripLonglineUIHandler extends ContentOpenableUIHandler<TripLonglineDto> { - - /** Logger */ - static private final Log log = LogFactory.getLog(TripLonglineUIHandler.class); - - protected boolean buildTripMap = true; - - public TripLonglineUIHandler(TripLonglineUI ui) { - super(ui, - DataContextType.Program, - DataContextType.TripLongline, - n("observe.content.tripLongline.message.not.open")); - } - - @Override - public TripLonglineUI getUi() { - return (TripLonglineUI) super.getUi(); - } - - @Override - public boolean doCloseData() { - boolean result = getOpenDataManager().isOpenTripLongline(getSelectedId()); - if (result) { - getOpenDataManager().closeTripLongline(getSelectedId()); - } - return result; - } - - @Override - public void initUI() { - super.initUI(); - - TripLonglineUI ui = getUi(); - TripMapUI tripMap = ui.getTripMap(); - ObserveSwingApplicationConfig config = ObserveSwingApplicationContext.get().getConfig(); - - tripMap.getHandler().setConfig(config); - - getUi().getTripLonglineTabPane().addChangeListener(e -> { - JTabbedPane tripLonglineTabPane = (JTabbedPane) e.getSource(); - TripLonglineUI ui1 = getUi(); - TripMapUI tripMap1 = ui1.getTripMap(); - if (tripLonglineTabPane.getSelectedComponent().equals(tripMap1)) { - ui1.getActions().setVisible(false); - - if (buildTripMap) { - SwingUtilities.invokeLater(() -> { - - TripLonglineUI ui11 = getUi(); - TripMapUI tripMap11 = ui11.getTripMap(); - - TripMapDto tripLonglineMap = getTripLonglineService().getTripLonglineMap(getSelectedId()); - - tripMap11.getHandler().doOpenMap(tripLonglineMap); - }); - buildTripMap = false; - } - - } else { - ui1.getActions().setVisible(true); - } - }); - - } - - @Override - public void openUI() { - super.openUI(); - - ContentMode mode = computeContentMode(); - - String programId = getSelectedParentId(); - String tripId = getSelectedId(); - - if (log.isInfoEnabled()) { - log.info(prefix + "programId = " + programId); - log.info(prefix + "tripId = " + tripId); - log.info(prefix + "mode = " + mode); - } - - TripLonglineDto bean = getBean(); - - boolean create = tripId == null; - - Form<TripLonglineDto> form; - if (create) { - - if (log.isInfoEnabled()) { - log.info(prefix + "create a new trip"); - } - // create mode - form = getTripLonglineService().preCreate(programId); - - } else { - - // update mode - if (log.isInfoEnabled()) { - log.info(prefix + "using existing trip " + tripId); - } - - // update mode - form = getTripLonglineService().loadForm(tripId); - } - - setContentMode(mode); - - loadReferentialReferenceSetsInModel(form); - - getModel().setForm(form); - TripLonglineDtos.copyTripLonglineDto(form.getObject(), bean); - - getUi().getTripLonglineTabPane().setSelectedIndex(0); - getUi().getTripMap().getHandler().doCloseMap(); - buildTripMap = true; - - finalizeOpenUI(mode, create); - } - - @Override - public void startEditUI(String... binding) { - - TripLonglineUI ui = getUi(); - - ContentOpenableUIModel<TripLonglineDto> model = getModel(); - - ContentMode mode = model.getMode(); - - boolean create = mode == ContentMode.CREATE; - - String contextName = getValidatorContextName(mode); - ui.getValidator().setContext(contextName); - - if (create) { - addInfoMessage(t("observe.content.tripLongline.message.creating")); - } else { - addInfoMessage(t("observe.content.tripLongline.message.updating")); - if (model.isHistoricalData()) { - - addInfoMessage(t("observe.message.historical.data")); - } - } - // date is current day - if (model.getMode() == ContentMode.UPDATE) { - if (getBean().getEndDate() == null) { - Date date = DateUtil.getEndOfDay(new Date()); - getBean().setEndDate(date); - if (log.isDebugEnabled()) { - log.debug("date fin " + date); - } - } - } - - super.startEditUI(TripLonglineUI.BINDING_VESSEL_SELECTED_ITEM, - TripLonglineUI.BINDING_OBSERVER_SELECTED_ITEM, - TripLonglineUI.BINDING_CAPTAIN_SELECTED_ITEM, - TripLonglineUI.BINDING_TRIP_TYPE_SELECTED_ITEM, - TripLonglineUI.BINDING_DATA_ENTRY_OPERATOR_SELECTED_ITEM, - TripLonglineUI.BINDING_TOTAL_FISHING_OPERATIONS_NUMBER_MODEL, - TripLonglineUI.BINDING_OCEAN_SELECTED_ITEM, - TripLonglineUI.BINDING_START_DATE_DATE, - TripLonglineUI.BINDING_END_DATE_DATE, - TripLonglineUI.BINDING_COMMENT2_TEXT, - TripLonglineUI.BINDING_HOME_ID_TEXT, - TripLonglineUI.BINDING_CLOSE_ENABLED, - TripLonglineUI.BINDING_CLOSE_AND_CREATE_ENABLED); - model.setModified(create); - } - - @Override - protected boolean doOpenData() { - boolean result = getOpenDataManager().canOpenTripLongline(); - if (result) { - getOpenDataManager().openTripLongline(getSelectedParentId(), getSelectedId()); - } - return result; - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - String tripLongLineId = getSelectedId(); - - if (tripLongLineId == null) { - - // maree en cours de creation - return ContentMode.CREATE; - } - - if (getOpenDataManager().isOpenTripLongline(tripLongLineId)) { - - // maree ouverte - return ContentMode.UPDATE; - } - - addInfoMessage(t(closeMessage)); - return ContentMode.READ; - } - - @Override - protected boolean doSave(TripLonglineDto bean) throws Exception { - - boolean notPersisted = bean.isNotPersisted(); - - // on force toujours la date a etre sans heure, minute,... - Date startDate = DateUtil.getDay(bean.getStartDate()); - if (log.isDebugEnabled()) { - log.debug("startDate = " + startDate); - } - bean.setStartDate(startDate); - - Date endDate = bean.getEndDate(); - if (log.isDebugEnabled()) { - log.debug("endDate = " + endDate); - } - - SaveResultDto saveResult = getTripLonglineService().save(bean); - saveResult.toDto(bean); - - // recuperation de la position de la maree dans le program - obtainChildPosition(bean); - - // ouverture de la marée - if (notPersisted) { - getOpenDataManager().openTripLongline(getSelectedParentId(), bean.getId()); - } - return true; - } - - @Override - protected int getOpenablePosition(String parentId, TripLonglineDto bean) { - - int position = getTripLonglineService().getTripLonglinePositionInProgram(parentId, bean.getId()); - - return position; - } - - @Override - protected boolean doDelete(TripLonglineDto bean) { - - if (askToDelete(bean)) { - return false; - } - if (log.isInfoEnabled()) { - log.info("Will delete Trip " + bean.getId()); - } - - getTripLonglineService().delete(bean.getId()); - getOpenDataManager().closeTripLongline(bean.getId()); - - if (log.isInfoEnabled()) { - log.info("Delete done for Trip " + bean.getId()); - } - return true; - } - - @Override - protected boolean obtainCanReopen(boolean create) { - - return !create && getOpenDataManager().canOpenTripLongline(); - - } - - @Override - protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { - - Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); - - switch (propertyName) { - - case TripLonglineDto.PROPERTY_CAPTAIN: { - result = (List) PersonDtos.filterCaptainReferences((List) result); - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - } - break; - - case TripLonglineDto.PROPERTY_OBSERVER: { - result = (List) PersonDtos.filterObserverReferences((List) result); - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - } - break; - - case TripLonglineDto.PROPERTY_DATA_ENTRY_OPERATOR: { - result = (List) PersonDtos.filterDataEntryOperatorReferences((List) result); - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - } - break; - - case TripLonglineDto.PROPERTY_VESSEL: { - ObserveSwingApplicationConfig config = ObserveSwingApplicationContext.get().getConfig(); - result = (List) VesselDtos.filterVesselReferencesByVesselTypeIds((List) result, config.getLonglineVesselTypeIds()); - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - } - break; - - } - - return result; - } - - protected TripLonglineService getTripLonglineService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripLonglineService(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/TripLonglineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/TripLonglineUIModel.java deleted file mode 100644 index aaceab0..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/longline/TripLonglineUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.open.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.ui.content.open.ContentOpenableUIModel; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class TripLonglineUIModel extends ContentOpenableUIModel<TripLonglineDto> { - - private static final long serialVersionUID = 1L; - - public TripLonglineUIModel() { - super(TripLonglineDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/ActivitySeineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/ActivitySeineUI.jaxx deleted file mode 100644 index 422faea..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/ActivitySeineUI.jaxx +++ /dev/null @@ -1,290 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.open.ContentOpenableUI superGenericType='ActivitySeineDto' - contentTitle='{n("observe.storage.activitySeine.title")}'> - - <style source="../../../Common.jcss"/> - - <import> - fr.ird.observe.services.dto.CommentableDto - fr.ird.observe.services.dto.seine.ActivitySeineDto - fr.ird.observe.services.dto.seine.SetSeineDto - fr.ird.observe.services.dto.seine.FloatingObjectDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.FpaZoneDto - fr.ird.observe.services.dto.referential.seine.VesselActivitySeineDto - fr.ird.observe.services.dto.referential.seine.SurroundingActivityDto - fr.ird.observe.services.dto.referential.seine.ReasonForNoFishingDto - fr.ird.observe.services.dto.referential.seine.DetectionModeDto - fr.ird.observe.services.dto.referential.seine.WindDto - - fr.ird.observe.ui.actions.shared.DeleteDataUIAction - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - jaxx.runtime.swing.CardLayout2Ext - - org.nuiton.jaxx.widgets.datetime.TimeEditor - org.nuiton.jaxx.widgets.gis.absolute.CoordinatesEditor - - java.awt.Dimension - - javax.swing.SwingConstants - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <ActivitySeineUIHandler id='handler' constructorParams='this'/> - - <!-- model --> - <ActivitySeineUIModel id='model'/> - - <!-- edit bean --> - <ActivitySeineDto id='bean'/> - - <!-- validator --> - <BeanValidator id='validator' - autoField='true' - beanClass='fr.ird.observe.services.dto.seine.ActivitySeineDto' - errorTableModel='{getErrorTableModel()}' - context='ui-create'> - - <field name='observedSystemEmpty' component='{actionDown}'/> - <field name='observedSystemDistance' component='{actionDown}'/> - <field name='longitude' component='coordinatesEditor'/> - <field name='latitude' component='coordinatesEditor'/> - <field name='quadrant' component='coordinatesEditor'/> - <field name='floatingObjectEmpty' component='addDCP'/> - - </BeanValidator> - - <script><![CDATA[ - -void $afterCompleteSetup() { - String label = getHandler().getActivity6Label(); - String text = t("observe.common.vesselActivitySeine.comment", label); - vesselActivityInformation.setText(text); - vesselActivityInformation.setToolTipText(text); -} - -]]> - </script> - - <!-- formulaire --> - <JPanel id="body" layout='{new BorderLayout()}'> - <Table insets="0" fill="both" constraints='BorderLayout.CENTER'> - <row> - <cell anchor="north" weightx="1"> - <JTabbedPane id='fishingOperationTabPane'> - <tab id='generalTab'> - <Table fill="both"> - <!-- heure observation --> - <row> - <cell columns="2" weightx="1"> - <TimeEditor id='time' constructorParams='this'/> - </cell> - </row> - - <!-- position --> - <row> - <cell anchor='west'> - <JLabel id='coordinatesLabel'/> - </cell> - <cell anchor='east' fill="both"> - <CoordinatesEditor id='coordinatesEditor' constructorParams='this'/> - </cell> - </row> - - <!-- activity vessel --> - <row> - <cell anchor='west' columns="2"> - <JLabel id='vesselActivityInformation'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='vesselActivitySeineLabel'/> - </cell> - <cell anchor='east' weightx="1"> - <BeanComboBox id='vesselActivitySeine' genericType='ReferentialReference<VesselActivitySeineDto>' _entityClass='VesselActivitySeineDto.class' constructorParams='this'/> - </cell> - </row> - - <!-- activity environnante --> - <row> - <cell anchor='west'> - <JLabel id='surroundingActivityLabel'/> - </cell> - <cell anchor='east' weightx="1"> - <BeanComboBox id='surroundingActivity' constructorParams='this' genericType='ReferentialReference<SurroundingActivityDto>' _entityClass='SurroundingActivityDto.class'/> - </cell> - </row> - - <!-- previousFpaZone --> - <row> - <cell anchor='west'> - <JLabel id='previousFpaZoneLabel'/> - </cell> - <cell anchor='east' weightx="1"> - <BeanComboBox id='previousFpaZone' constructorParams='this' genericType='ReferentialReference<FpaZoneDto>' _entityClass='FpaZoneDto.class'/> - </cell> - </row> - - <!-- currentFpaZone --> - <row> - <cell anchor='west'> - <JLabel id='currentFpaZoneLabel'/> - </cell> - <cell anchor='east' weightx="1"> - <BeanComboBox id='currentFpaZone' constructorParams='this' genericType='ReferentialReference<FpaZoneDto>' _entityClass='FpaZoneDto.class'/> - </cell> - </row> - - <!-- nextFpaZone --> - <row> - <cell anchor='west'> - <JLabel id='nextFpaZoneLabel'/> - </cell> - <cell anchor='east' weightx="1"> - <BeanComboBox id='nextFpaZone' constructorParams='this' genericType='ReferentialReference<FpaZoneDto>' _entityClass='FpaZoneDto.class'/> - </cell> - </row> - - <!-- id ers --> - <row> - - <cell anchor='west'> - <JLabel id='ersIdLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel layout='{new BorderLayout()}'> - <JToolBar id='ersIdToolbar' constraints='BorderLayout.WEST'> - <JButton id='resetErsId' constraints='BorderLayout.WEST' styleClass='resetButton'/> - </JToolBar> - <JTextField id='ersId' constraints='BorderLayout.CENTER'/> - </JPanel> - </cell> - </row> - </Table> - </tab> - - <tab id='measurementsTab'> - <Table fill="both"> - <!-- vitesse vessel --> - <row> - <cell anchor='west'> - <JLabel id='vesselSpeedLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <NumberEditor id='vesselSpeed' constructorParams='this'/> - </cell> - </row> - - <!-- température de surface --> - <row> - <cell anchor='west'> - <JLabel id='seaSurfaceTemperatureLabel'/> - </cell> - <cell anchor='east' fill="both"> - <NumberEditor id='seaSurfaceTemperature' constructorParams='this'/> - </cell> - </row> - - <!-- vent beaufort --> - <row> - <cell anchor='west'> - <JLabel id='windLabel'/> - </cell> - <cell anchor='east'> - <BeanComboBox id='wind' genericType='ReferentialReference<WindDto>' _entityClass='WindDto.class' constructorParams='this'/> - </cell> - </row> - - <!-- mode de détection --> - <row> - <cell anchor='west'> - <JLabel id='detectionModeLabel'/> - </cell> - <cell anchor='east'> - <BeanComboBox id='detectionMode' genericType='ReferentialReference<DetectionModeDto>' _entityClass='DetectionModeDto.class' constructorParams='this'/> - </cell> - </row> - - <!-- cause non coups senne --> - <row> - <cell anchor='west'> - <JLabel id='reasonForNoFishingLabel'/> - </cell> - <cell anchor='east'> - <BeanComboBox id='reasonForNoFishing' genericType='ReferentialReference<ReasonForNoFishingDto>' _entityClass='ReasonForNoFishingDto.class' constructorParams='this'/> - </cell> - </row> - <row> - <cell columns="2" weighty="1"> - <JLabel/> - </cell> - </row> - </Table> - </tab> - - </JTabbedPane> - </cell> - </row> - - <!-- comment --> - <row> - <cell columns='2' weighty="1"> - <JScrollPane id='comment' - onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2' - onKeyReleased='getBean().setComment(comment2.getText())'/> - </JScrollPane> - </cell> - </row> - </Table> - </JPanel> - - <!-- surcharge des actions (pour appliquer la css specifique --> - <JButton id='delete'/> - <JButton id='reopen'/> - <JButton id='close'/> - <JButton id='closeAndCreate'/> - <JButton id='actionDown'/> - - <Table id='extraActions' fill="both" weightx="1" insets='2' - visible='{model.isUpdatingMode()}'> - <row> - <cell weightx="0.5" fill="both"> - <JButton id='addSet' - onActionPerformed='getHandler().addChild(SetSeineDto.class)'/> - </cell> - <cell weightx="0.5" fill="both"> - <JButton id='addDCP' - onActionPerformed='getHandler().addChild(FloatingObjectDto.class)'/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.open.ContentOpenableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/ActivitySeineUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/ActivitySeineUI.jcss deleted file mode 100644 index 6c7e9e3..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/ActivitySeineUI.jcss +++ /dev/null @@ -1,226 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#model { - editable:true; - modified:{validator.isChanged()}; - valid:{validator.isValid()}; -} - -#time { - propertyTime:{ActivitySeineDto.PROPERTY_TIME}; - bean:{bean}; - label:{t("observe.common.heureobservation")}; - time:{bean.getTime()}; - _validatorLabel:{t("observe.common.heureobservation")}; -} - -#coordinatesLabel { - text:"observe.storage.activityLongline.coordinate"; - labelFor:{coordinatesEditor}; -} - -#coordinatesEditor { - propertyLatitude:{ActivitySeineDto.PROPERTY_LATITUDE}; - propertyLongitude:{ActivitySeineDto.PROPERTY_LONGITUDE}; - propertyQuadrant:{ActivitySeineDto.PROPERTY_QUADRANT}; -} - -#generalTab { - title:{t("observe.storage.activitySeine.tab.general")}; - icon:{getHandler().getErrorIconIfFalse(model.isGeneralTabValid())}; -} - -#measurementsTab { - title:{t("observe.storage.activitySeine.tab.measurements")}; - icon:{getHandler().getErrorIconIfFalse(model.isMeasurementsTabValid())}; -} - -#vesselActivityInformation { - font-size:11; - actionIcon:"information"; -} - -#vesselActivitySeineLabel { - text:"observe.common.vesselActivitySeine"; - labelFor:{vesselActivitySeine}; -} - -#vesselActivitySeine { - property:{ActivitySeineDto.PROPERTY_VESSEL_ACTIVITY_SEINE}; - selectedItem:{bean.getVesselActivitySeine()}; - enabled:{!model.isUpdatingMode()}; -} - -#surroundingActivityLabel { - text:"observe.common.surroundingActivity"; - labelFor:{surroundingActivity}; -} - -#surroundingActivity { - property:{ActivitySeineDto.PROPERTY_SURROUNDING_ACTIVITY}; - selectedItem:{bean.getSurroundingActivity()}; -} - -#previousFpaZoneLabel { - text:"observe.common.previousFpaZone"; - labelFor:{previousFpaZone}; -} - -#previousFpaZone { - property:{ActivitySeineDto.PROPERTY_PREVIOUS_FPA_ZONE}; - selectedItem:{bean.getPreviousFpaZone()}; - enabled:{model.isChangedZoneOperation()}; -} - -#currentFpaZoneLabel { - text:"observe.common.currentFpaZone"; - labelFor:{currentFpaZone}; -} - -#currentFpaZone { - property:{ActivitySeineDto.PROPERTY_CURRENT_FPA_ZONE}; - selectedItem:{bean.getCurrentFpaZone()}; - enabled:{!model.isChangedZoneOperation()}; -} - -#nextFpaZoneLabel { - text:"observe.common.nextFpaZone"; - labelFor:{nextFpaZone}; -} - -#nextFpaZone { - property:{ActivitySeineDto.PROPERTY_NEXT_FPA_ZONE}; - selectedItem:{bean.getNextFpaZone()}; - enabled:{model.isChangedZoneOperation()}; -} - -#vesselSpeedLabel { - text:"observe.common.vesselSpeed"; - labelFor:{vesselSpeed}; -} - -#vesselSpeed { - property:{ActivitySeineDto.PROPERTY_VESSEL_SPEED}; - model:{bean.getVesselSpeed()}; - useFloat:true; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL2_PATTERN}; -} - -#ersIdLabel{ - text:"observe.common.ersId"; - labelFor:{ersId}; -} - -#resetErsId{ - toolTipText:"observe.content.action.reset.ersId.tip"; - _resetPropertyName:{ActivitySeineDto.PROPERTY_ERS_ID}; -} - -#ersId { - _propertyName:{ActivitySeineDto.PROPERTY_ERS_ID}; - text:{getStringValue(bean.getErsId())}; -} - -#seaSurfaceTemperatureLabel { - text:"observe.common.seaSurfaceTemperature"; - labelFor:{seaSurfaceTemperature}; -} - -#seaSurfaceTemperature { - property:{ActivitySeineDto.PROPERTY_SEA_SURFACE_TEMPERATURE}; - model:{bean.getSeaSurfaceTemperature()}; - useFloat:true; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL2_PATTERN}; -} - -#windLabel { - text:"observe.common.wind"; - labelFor:{wind}; -} - -#wind { - property:{ActivitySeineDto.PROPERTY_WIND}; - selectedItem:{bean.getWind()}; -} - -#detectionModeLabel { - text:"observe.common.detectionMode"; - labelFor:{detectionMode}; -} - -#detectionMode { - property:{ActivitySeineDto.PROPERTY_DETECTION_MODE}; - selectedItem:{bean.getDetectionMode()}; -} - -#reasonForNoFishingLabel { - text:"observe.common.nonCoupSenne"; - labelFor:{reasonForNoFishing}; -} - -#reasonForNoFishing { - property:{ActivitySeineDto.PROPERTY_REASON_FOR_NO_FISHING}; - selectedItem:{bean.getReasonForNoFishing()}; -} - -#comment { - columnHeaderView:{new JLabel(t("observe.common.comment"))}; - minimumSize:{new Dimension(10,50)}; -} - -#comment2 { - text:{getStringValue(bean.getComment())}; -} - -#reopen { - _toolTipText:{t("observe.content.action.reopen.activity.tip")}; -} - -#close { - enabled:{!model.isModified() && (model.isHistoricalData() || model.isValid())}; - _toolTipText:{t("observe.action.close.activity.tip")}; -} - -#closeAndCreate { - enabled:{!model.isModified() && (model.isHistoricalData() || model.isValid())}; - _text:{t("observe.content.action.closeAndCreate.activity")}; - _toolTipText:{t("observe.content.action.closeAndCreate.activity.tip")}; -} - -#delete { - _toolTipText:{t("observe.action.delete.activity.tip")}; -} - -#addSet { - enabled:{!model.isModified() && model.isValid() && model.isSetOperation() && bean.getSetSeine() == null}; - text:"observe.action.add.set"; - toolTipText:"observe.action.add.set.tip"; - actionIcon:"add"; -} - -#addDCP { - enabled:{!model.isModified() && model.isValid()}; - text:"observe.action.add.floatingObject"; - toolTipText:"observe.action.add.floatingObject.tip"; - actionIcon:"add"; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/ActivitySeineUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/ActivitySeineUIHandler.java deleted file mode 100644 index beb0055..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/ActivitySeineUIHandler.java +++ /dev/null @@ -1,378 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.open.impl.seine; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.seine.VesselActivitySeineDto; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.services.dto.seine.ActivitySeineDtos; -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.services.service.seine.ActivitySeineService; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.ContentUIModel; -import fr.ird.observe.ui.content.open.ContentOpenableUIHandler; -import jaxx.runtime.validator.swing.SwingValidatorMessage; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.event.TableModelListener; -import java.util.HashSet; -import java.util.Set; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class ActivitySeineUIHandler extends ContentOpenableUIHandler<ActivitySeineDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(ActivitySeineUIHandler.class); - - // Compute valid state of tab from the error table - protected final TableModelListener computeTabValidStateListener; - -// static ImmutableSet<String> COORDINATES_PROPERTIES = ImmutableSet.of(ActivitySeine.PROPERTY_QUADRANT, -// ActivitySeine.PROPERTY_LATITUDE, -// ActivitySeine.PROPERTY_LONGITUDE); - -// private LogPropertyChanges logCoordinatesChanges; - - - public ActivitySeineUIHandler(ActivitySeineUI ui) { - super(ui, - DataContextType.Route, - DataContextType.ActivitySeine, - n("observe.storage.activitySeine.message.not.open")); -// this.logCoordinatesChanges = new LogPropertyChanges(COORDINATES_PROPERTIES); - computeTabValidStateListener = e -> { - - SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); - computeTabValidState(source); - - }; - } - - @Override - public ActivitySeineUI getUi() { - return (ActivitySeineUI) super.getUi(); - } - - @Override - protected boolean doOpenData() { - boolean result = getOpenDataManager().canOpenActivitySeine(getSelectedParentId()); - if (result) { - getOpenDataManager().openActivitySeine(getSelectedParentId(), getSelectedId()); - } - return result; - } - - @Override - public boolean doCloseData() { - boolean result = getOpenDataManager().isOpenActivitySeine(getSelectedId()); - if (result) { - getOpenDataManager().closeActivitySeine(getSelectedId()); - } - return result; - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - String activityId = getSelectedId(); - - if (activityId == null) { - - // mode creation - return ContentMode.CREATE; - } - - // l'activity existe en base - if (getOpenDataManager().isOpenActivitySeine(getSelectedId())) { - - // l'activity est ouverte, donc modifiable - return ContentMode.UPDATE; - } - - ActivitySeineUI ui = getUi(); - - // l'activity n'est pas ouverte, donc pas éditable - if (!getOpenDataManager().isOpenRoute(getSelectedParentId())) { - - // la route n'est pas ouverte - addMessage(ui, - NuitonValidatorScope.INFO, - getEntityLabel(RouteDto.class), - t("observe.content.route.message.not.open")); - - } else if (!getOpenDataManager().isOpenTripSeine(dataContext.getSelectedTripSeineId())) { - - // la marée n'est past ouverte - addMessage(ui, - NuitonValidatorScope.INFO, - getEntityLabel(TripSeineDto.class), - t("observe.content.tripSeine.message.not.open")); - - if (getModel().isHistoricalData()) { - - addInfoMessage(t("observe.message.historical.data")); - } - - } else { - - // seule l'activity n'est pas ouverte - addInfoMessage(t(closeMessage)); - } - - return ContentMode.READ; - } - - @Override - public void initUI() { - - super.initUI(); - - // To be sure always remove listener (could prevent some leaks) - getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); - // listen messages to see if required to add - getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); - -// getBean().removePropertyChangeListener(logCoordinatesChanges); -// getBean().addPropertyChangeListener(logCoordinatesChanges); - } - - @Override - public void openUI() { - super.openUI(); - - getUi().getCoordinatesEditor().resetModel(); - - String routeId = getSelectedParentId(); - String activityId = getSelectedId(); - - if (log.isInfoEnabled()) { - log.info(prefix + "routeId = " + routeId); - log.info(prefix + "activityId = " + activityId); - } - - ContentMode mode = computeContentMode(); - if (log.isInfoEnabled()) { - log.info(prefix + "content mode " + mode); - } - ActivitySeineDto bean = getBean(); - - boolean create = activityId == null; - - Form<ActivitySeineDto> form; - if (create) { - - // create mode - form = getActivitySeineService().preCreate(routeId); - - } else { - - // update mode - form = getActivitySeineService().loadForm(activityId); - - } - - setContentMode(mode); - - loadReferentialReferenceSetsInModel(form); - - getModel().setForm(form); - ActivitySeineDtos.copyActivitySeineDto(form.getObject(), bean); - - if (log.isDebugEnabled()) { - log.debug(prefix + "long - lat = " + bean.getLongitude() + " - " + bean.getLatitude()); - } - - SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); - computeTabValidState(errorTableModel); - - finalizeOpenUI(mode, create); - - // Mise à jour du composant de coordonnées - // 1. Mise à jour latitude/longitude: - getUi().getCoordinatesEditor().setLatitudeAndLongitude(bean.getLatitude(), bean.getLongitude()); - - // 2. Mise à jour du quadrant : - // Si le bean de données contient un quadrant, on met simplement à jour le composant de coordonnées pour sélectionner le quadrant voulu - // sinon, on réinitialise les quadrants du composant afin qu'aucun d'eux ne soit sélectionné (par exemple dans le cas de la création de la première activité d'une route) - if (bean.getQuadrant() != null) { - getUi().getCoordinatesEditor().setQuadrant(bean.getQuadrant()); - } else { - resetQuadrant(getUi().getCoordinatesEditor()); - } - - // on annule la modification engendree par ce binding - getModel().setModified(create); - } - - @Override - public void startEditUI(String... binding) { - ActivitySeineUI ui = getUi(); - - ContentUIModel<ActivitySeineDto> model = getModel(); - - boolean create = model.getMode() == ContentMode.CREATE; - String contextName = getValidatorContextName(model.getMode()); - ui.getValidator().setContext(contextName); - if (create) { - addMessage(ui, - NuitonValidatorScope.INFO, - getEntityLabel(ActivitySeineDto.class), - t("observe.storage.activitySeine.message.creating")); - } else { - addMessage(ui, - NuitonValidatorScope.INFO, - getEntityLabel(ActivitySeineDto.class), - t("observe.storage.activitySeine.message.updating")); - } - - super.startEditUI(ActivitySeineUI.BINDING_TIME_TIME, - ActivitySeineUI.BINDING_VESSEL_SPEED_MODEL, - ActivitySeineUI.BINDING_SEA_SURFACE_TEMPERATURE_MODEL, - ActivitySeineUI.BINDING_COMMENT2_TEXT, - ActivitySeineUI.BINDING_VESSEL_ACTIVITY_SEINE_SELECTED_ITEM, - ActivitySeineUI.BINDING_PREVIOUS_FPA_ZONE_SELECTED_ITEM, - ActivitySeineUI.BINDING_CURRENT_FPA_ZONE_SELECTED_ITEM, - ActivitySeineUI.BINDING_NEXT_FPA_ZONE_SELECTED_ITEM, - ActivitySeineUI.BINDING_SURROUNDING_ACTIVITY_SELECTED_ITEM, - ActivitySeineUI.BINDING_CLOSE_ENABLED, - ActivitySeineUI.BINDING_ADD_SET_ENABLED, - ActivitySeineUI.BINDING_CLOSE_AND_CREATE_ENABLED); - model.setModified(create); - } - - @Override - protected boolean doSave(ActivitySeineDto bean) throws Exception { - - boolean notPersisted = bean.isNotPersisted(); - - if (log.isDebugEnabled()) { - log.debug(" long - lat = " + bean.getLongitude() + " - " + bean.getLatitude()); - } - - String routeId = getSelectedParentId(); - - bean.setOpen(true); - - SaveResultDto saveResult = getActivitySeineService().save(routeId, getModel().getBean()); - saveResult.toDto(bean); - - obtainChildPosition(bean); - - // ouverture de l'activité après création - if (notPersisted) { - getOpenDataManager().openActivitySeine(getSelectedParentId(), bean.getId()); - } - - return true; - } - - - @Override - protected int getOpenablePosition(String parentId, ActivitySeineDto bean) { - int position = getActivitySeineService().getActivitySeinePositionInRoute(parentId, bean.getId()); - return position; - } - - @Override - protected boolean doDelete(ActivitySeineDto bean) { - - if (askToDelete(bean)) { - return false; - } - if (log.isInfoEnabled()) { - log.info("Will delete Activity " + bean.getId()); - } - - String routeId = getSelectedParentId(); - getActivitySeineService().delete(routeId, bean.getId()); - getOpenDataManager().closeActivitySeine(bean.getId()); - - if (log.isInfoEnabled()) { - log.info("Delete done for Activity " + bean.getId()); - } - return true; - } - - @Override - protected boolean obtainCanReopen(boolean create) { - - boolean canReopen = !create && getOpenDataManager().canOpenActivitySeine(getSelectedParentId()); - - return canReopen; - } - - public String getActivity6Label() { - - Set<ReferentialReference<VesselActivitySeineDto>> activities = getDataSource().getReferentialReferences(VesselActivitySeineDto.class); - - for (ReferentialReference<VesselActivitySeineDto> vesselActivity : activities) { - if (ActivitySeineDto.ACTIVITY_FIN_DE_PECHE.equals(vesselActivity.getPropertyValue(VesselActivitySeineDto.PROPERTY_CODE))) { - String label = getDecoratorService().getReferentialReferenceDecorator(VesselActivitySeineDto.class).toString(vesselActivity); -// String label = getDecoratorService().decorate(VesselActivitySeineDto.class.getSimpleName(), -// vesselActivity); - return label; - } - } - throw new IllegalStateException(t("observe.error.no.activity.6")); - } - - protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { - - Set<String> errorProperties = new HashSet<>(); - int rowCount = errorTableModel.getRowCount(); - for (int i = 0; i < rowCount; i++) { - - SwingValidatorMessage row = errorTableModel.getRow(i); - if (NuitonValidatorScope.ERROR.equals(row.getScope())) { - errorProperties.add(row.getField()); - } - } - - boolean generalTabValid = !errorProperties.removeAll(ActivitySeineUIModel.GENERAL_TAB_PROPERTIES); - boolean measurementsTabValid = !errorProperties.removeAll(ActivitySeineUIModel.MEASUREMENTS_TAB_PROPERTIES); - - ActivitySeineUIModel model = (ActivitySeineUIModel) getModel(); - model.setGeneralTabValid(generalTabValid); - model.setMeasurementsTabValid(measurementsTabValid); - - } - - protected ActivitySeineService getActivitySeineService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivitySeineService(); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/ActivitySeineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/ActivitySeineUIModel.java deleted file mode 100644 index 912a676..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/ActivitySeineUIModel.java +++ /dev/null @@ -1,121 +0,0 @@ -package fr.ird.observe.ui.content.open.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.ImmutableSet; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.seine.VesselActivitySeineDto; -import fr.ird.observe.services.dto.referential.seine.VesselActivitySeineDtos; -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.ui.content.open.ContentOpenableUIModel; - -import java.util.Set; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ActivitySeineUIModel extends ContentOpenableUIModel<ActivitySeineDto> { - - public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; - - public static final String PROPERTY_MEASUREMENTS_TAB_VALID = "measurementsTabValid"; - - public static final String PROPERTY_SET_OPERATION = "setOperation"; - - public static final String PROPERTY_CHANGED_ZONE_OPERATION = "changedZoneOperation"; - - public static final Set<String> GENERAL_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(ActivitySeineDto.PROPERTY_TIME, - ActivitySeineDto.PROPERTY_LATITUDE, - ActivitySeineDto.PROPERTY_LONGITUDE, - ActivitySeineDto.PROPERTY_VESSEL_ACTIVITY_SEINE, - ActivitySeineDto.PROPERTY_SURROUNDING_ACTIVITY, - ActivitySeineDto.PROPERTY_PREVIOUS_FPA_ZONE, - ActivitySeineDto.PROPERTY_CURRENT_FPA_ZONE, - ActivitySeineDto.PROPERTY_NEXT_FPA_ZONE, - ActivitySeineDto.PROPERTY_ERS_ID).build(); - - public static final Set<String> MEASUREMENTS_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(ActivitySeineDto.PROPERTY_VESSEL_SPEED, - ActivitySeineDto.PROPERTY_SEA_SURFACE_TEMPERATURE, - ActivitySeineDto.PROPERTY_WIND, - ActivitySeineDto.PROPERTY_DETECTION_MODE, - ActivitySeineDto.PROPERTY_REASON_FOR_NO_FISHING).build(); - - private static final long serialVersionUID = 1L; - - protected boolean generalTabValid; - - protected boolean measurementsTabValid; - - public ActivitySeineUIModel() { - super(ActivitySeineDto.class); - getBean().addPropertyChangeListener(ActivitySeineDto.PROPERTY_VESSEL_ACTIVITY_SEINE, evt -> { - ReferentialReference<VesselActivitySeineDto> oldActivitySeine = (ReferentialReference<VesselActivitySeineDto>) evt.getOldValue(); - ReferentialReference<VesselActivitySeineDto> newActivitySeine = (ReferentialReference<VesselActivitySeineDto>) evt.getNewValue(); - { - boolean oldValue = VesselActivitySeineDtos.isSetOperation(oldActivitySeine); - boolean newValue = VesselActivitySeineDtos.isSetOperation(newActivitySeine); - firePropertyChange(PROPERTY_SET_OPERATION, oldValue, newValue); - } - { - boolean oldValue = VesselActivitySeineDtos.isChangedZoneOperation(oldActivitySeine); - boolean newValue = VesselActivitySeineDtos.isChangedZoneOperation(newActivitySeine); - firePropertyChange(PROPERTY_CHANGED_ZONE_OPERATION, oldValue, newValue); - } - }); - - } - - public boolean isMeasurementsTabValid() { - return measurementsTabValid; - } - - public void setMeasurementsTabValid(boolean measurementsTabValid) { - Object oldValue = isMeasurementsTabValid(); - this.measurementsTabValid = measurementsTabValid; - firePropertyChange(PROPERTY_MEASUREMENTS_TAB_VALID, oldValue, measurementsTabValid); - } - - public boolean isGeneralTabValid() { - return generalTabValid; - } - - public void setGeneralTabValid(boolean generalTabValid) { - Object oldValue = isGeneralTabValid(); - this.generalTabValid = generalTabValid; - firePropertyChange(PROPERTY_GENERAL_TAB_VALID, oldValue, generalTabValid); - } - - public boolean isSetOperation() { - return VesselActivitySeineDtos.isSetOperation(bean.getVesselActivitySeine()); - } - - public boolean isChangedZoneOperation() { - return VesselActivitySeineDtos.isChangedZoneOperation(bean.getVesselActivitySeine()); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/RouteUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/RouteUI.jaxx deleted file mode 100644 index bd17849..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/RouteUI.jaxx +++ /dev/null @@ -1,102 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.open.ContentOpenableUI superGenericType='RouteDto' contentTitle='{n("observe.content.route.title")}'> - - <import> - fr.ird.observe.services.dto.seine.RouteDto - - org.jdesktop.swingx.JXDatePicker - - jaxx.runtime.swing.editor.NumberEditor - - java.awt.Dimension - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <RouteUIHandler id='handler' constructorParams='this'/> - - <!-- model --> - <RouteUIModel id='model'/> - - <!-- edit bean --> - <RouteDto id='bean'/> - - <!-- validator --> - <BeanValidator id='validator' - autoField='true' - beanClass='fr.ird.observe.services.dto.seine.RouteDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update'> - <field name='activitySeine' component='{actionDown}'/> - </BeanValidator> - - <!-- formulaire --> - <JPanel id="body" layout='{new BorderLayout()}'> - <Table fill='both' constraints='BorderLayout.CENTER'> - <row> - <cell anchor='west'> - <JLabel id='dateLabel'/> - </cell> - <cell anchor='east' weightx="1"> - <JXDatePicker id='date'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='startLogValueLabel'/> - </cell> - <cell anchor='east' weightx="1"> - <NumberEditor id='startLogValue' constructorParams='this'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id='endLogValueLabel'/> - </cell> - <cell anchor='east' weightx="1"> - <NumberEditor id='endLogValue' constructorParams='this'/> - </cell> - </row> - <row> - <cell columns='2' fill="both" weightx="1" weighty="1"> - <JScrollPane id='comment' - onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2' - onKeyReleased='getBean().setComment(comment2.getText())'/> - </JScrollPane> - </cell> - </row> - </Table> - </JPanel> - - <!-- surcharge des actions (pour appliquer la css specifique) --> - <JButton id='delete'/> - <JButton id='reopen'/> - <JButton id='close'/> - <JButton id='closeAndCreate'/> - <JButton id='actionDown'/> - -</fr.ird.observe.ui.content.open.ContentOpenableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/RouteUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/RouteUI.jcss deleted file mode 100644 index 670e8a8..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/RouteUI.jcss +++ /dev/null @@ -1,92 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -NumberEditor { - bean:{bean}; - useFloat:true; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL2_PATTERN}; -} - -#model { - editable:true; - modified:{validator.isChanged()}; - valid:{validator.isValid()}; -} - -#dateLabel { - text:"observe.common.date"; - labelFor:{date}; -} - -#date { - date:{bean.getDate()}; - _propertyName:{RouteDto.PROPERTY_DATE}; -} - -#startLogValueLabel { - text:"observe.common.startLogValue"; - labelFor:{startLogValue}; -} - -#startLogValue { - property:{RouteDto.PROPERTY_START_LOG_VALUE}; - model:{bean.getStartLogValue()}; -} - -#endLogValueLabel { - text:"observe.common.endLogValue"; - labelFor:{endLogValue}; -} - -#endLogValue { - property:{RouteDto.PROPERTY_END_LOG_VALUE}; - model:{bean.getEndLogValue()}; - enabled:{!model.isCreatingMode()}; -} - -#comment { - columnHeaderView:{new JLabel(t("observe.common.comment"))}; - minimumSize:{new Dimension(10,50)}; -} - -#comment2 { - text:{getStringValue(bean.getComment())}; -} - -#reopen { - _toolTipText:{t("observe.content.action.reopen.route.tip")}; -} - -#close { - enabled:{!model.isModified() && (model.isHistoricalData() || model.isValid()) && !dataContext.isOpenActivity()}; - _toolTipText:{t("observe.action.close.route.tip")}; -} - -#closeAndCreate { - enabled:{!model.isModified() && (model.isHistoricalData() || model.isValid()) && !dataContext.isOpenActivity()}; - _text:{t("observe.content.action.closeAndCreate.route")}; - _toolTipText:{t("observe.content.action.closeAndCreate.route.tip")}; -} - -#delete { - _toolTipText:{t("observe.action.delete.route.tip")}; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/RouteUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/RouteUIHandler.java deleted file mode 100644 index 3eab942..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/RouteUIHandler.java +++ /dev/null @@ -1,466 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.open.impl.seine; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.seine.VesselActivitySeineDto; -import fr.ird.observe.services.dto.result.TripChildSaveResultDto; -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.services.dto.seine.RouteDtos; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.services.service.seine.RouteService; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.open.ContentOpenableUIHandler; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.util.DateUtil; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.JOptionPane; -import java.util.Date; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class RouteUIHandler extends ContentOpenableUIHandler<RouteDto> { - - public static final String UPDATE_MAREE_NODE = "updateTripNode"; - - /** Logger */ - private static final Log log = LogFactory.getLog(RouteUIHandler.class); - - public RouteUIHandler(RouteUI ui) { - super(ui, - DataContextType.TripSeine, - DataContextType.Route, - n("observe.content.route.message.not.open")); - } - - @Override - public RouteUI getUi() { - return (RouteUI) super.getUi(); - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - String routeId = getSelectedId(); - - if (routeId == null) { - - // mode creation - return ContentMode.CREATE; - } - - // route deja existante - if (getOpenDataManager().isOpenRoute(routeId)) { - - // la route est ouverte - return ContentMode.UPDATE; - } - - RouteUI ui = getUi(); - - // route non ouverte - if (!dataContext.isSelectedOpen(TripSeineDto.class)) { - - addMessage(ui, NuitonValidatorScope.INFO, - getEntityLabel(TripSeineDto.class), - t("observe.content.tripSeine.message.not.open")); - - } else { - - // la maree courante est ouverte - addMessage(ui, NuitonValidatorScope.INFO, - getEntityLabel(RouteDto.class), - t(closeMessage)); - } - return ContentMode.READ; - } - - @Override - public void openUI() { - - super.openUI(); - - String tripId = getSelectedParentId(); - String routeId = getSelectedId(); - - if (log.isInfoEnabled()) { - log.info(prefix + "tripId = " + tripId); - log.info(prefix + "routeId = " + routeId); - } - - ContentMode mode = computeContentMode(); - - if (log.isInfoEnabled()) { - log.info(prefix + "content mode = " + mode); - } - - RouteDto editBean = getBean(); - - boolean create = routeId == null; - - Form<RouteDto> form; - if (create) { - - // create mode - form = getRouteService().preCreate(tripId); - - } else { - - // update mode - form = getRouteService().loadForm(routeId); - - } - - setContentMode(mode); - - loadReferentialReferenceSetsInModel(form); - - getModel().setForm(form); - RouteDtos.copyRouteDto(form.getObject(), editBean); - - finalizeOpenUI(mode, create); - } - - @Override - public void startEditUI(String... binding) { - - boolean create = getModel().getMode() == ContentMode.CREATE; - String contextName = getValidatorContextName(getModel().getMode()); - - RouteUI ui = getUi(); - - ui.getValidator().setContext(contextName); - - if (create) { - addMessage(ui, - NuitonValidatorScope.INFO, - getEntityLabel(RouteDto.class), - t("observe.content.route.message.creating")); - } else { - addMessage(ui, - NuitonValidatorScope.INFO, - getEntityLabel(RouteDto.class), - t("observe.content.route.message.updating")); - - if (getModel().isHistoricalData()) { - - addInfoMessage(t("observe.message.historical.data")); - } - } - - super.startEditUI(RouteUI.BINDING_DATE_DATE, - RouteUI.BINDING_START_LOG_VALUE_MODEL, - RouteUI.BINDING_END_LOG_VALUE_ENABLED, - RouteUI.BINDING_COMMENT2_TEXT, - RouteUI.BINDING_CLOSE_ENABLED, - RouteUI.BINDING_CLOSE_AND_CREATE_ENABLED); - - // le formulaire est en état modifié uniquement si on est en création - getModel().setModified(create); - } - - @Override - protected boolean doSave(RouteDto bean) throws Exception { - - boolean notPersisted = bean.isNotPersisted(); - - String tripId = getSelectedParentId(); - - if (log.isInfoEnabled()) { - log.info("will save route " + bean.getId()); - } - - // on sauvegarde toujours en debut de jour - Date date = DateUtil.getDay(bean.getDate()); - bean.setDate(date); - bean.setOpen(true); - - TripChildSaveResultDto saveResult = getRouteService().save(tripId, bean); - saveResult.toDto(bean); - - setUpdateMareeNodeTag(saveResult.isTripEndDateUpdated()); - - obtainChildPosition(bean); - - // ouverture de la route - if (notPersisted) { - getOpenDataManager().openRoute(getSelectedParentId(), bean.getId()); - } - - return true; - } - - @Override - protected int getOpenablePosition(String parentId, RouteDto bean) { - int position = getRouteService().getRoutePositionInTripSeine(parentId, bean.getId()); - return position; - } - - @Override - protected void afterSave(boolean refresh) { - super.afterSave(refresh); - repaintTripNode(); - } - - @Override - protected void afterDelete() { - super.afterDelete(); - repaintTripNode(); - } - - @Override - protected boolean doDelete(RouteDto bean) { - - if (askToDelete(bean)) { - return false; - } - if (log.isInfoEnabled()) { - log.info("Will delete Route " + bean.getId()); - } - - String tripId = getSelectedParentId(); - boolean wasEndDateUpdated = getRouteService ().delete(tripId, bean.getId()); - getOpenDataManager().closeRoute(getSelectedId()); - - if (log.isInfoEnabled()) { - log.info("Delete done for Route " + bean.getId()); - } - - setUpdateMareeNodeTag(wasEndDateUpdated); - - return true; - } - - @Override - protected boolean doOpenData() { - boolean result = getOpenDataManager().canOpenRoute(getSelectedParentId()); - if (result) { - getOpenDataManager().openRoute(getSelectedParentId(), getSelectedId()); - } - return result; - } - - @Override - public boolean doCloseData() { - - RouteDto route = getBean(); - - // on doit vérifier qu'il existe une activité de fin - // de veille (type activity vessel == 16) - - boolean mustAddFinVeille = !route.isActivityFindDeVeilleFound(); - - boolean createActivityFinDeVeille = false; - boolean closeActivityFinDeVeille = false; - boolean gotoActivityFinDeVeille = false; - - ObserveTreeHelper treeHelper = getTreeHelper(getUi()); - ObserveNode routeNode = treeHelper.getSelectedNode(); - - if (mustAddFinVeille) { - - // on indique à l'observer qu'il doit créer une activité de type - // 16 - - int reponse = UIHelper.askUser( - getUi(), - t("observe.title.need.confirm"), - t("observe.message.need.fin.veille.activity"), - JOptionPane.WARNING_MESSAGE, - new Object[]{ - t("observe.choice.not.create.fin.veille.activity.and.continue"), - t("observe.choice.create.fin.veille.activity.and.continue"), - t("observe.choice.create.fin.veille.activity"), - t("observe.choice.cancel")}, - 0); - if (log.isDebugEnabled()) { - log.debug("response : " + reponse); - } - - - switch (reponse) { - case JOptionPane.CLOSED_OPTION: - case 3: - - // abandon objectOperation - return false; - case 0: - - // rien a faire - // on veut juste cloturer la route - break; - case 1: - - // creation de l'activity de fin de veille - // fermeture de l'activity de fin de veille - // fermeture de la route - createActivityFinDeVeille = true; - closeActivityFinDeVeille = true; - - break; - case 2: - - // creation de l'activity de fin de veille - // selection de cette activity de fin de veille - createActivityFinDeVeille = true; - gotoActivityFinDeVeille = true; - break; - } - } - - if (createActivityFinDeVeille) { - - // stop l'édition de la route - stopEditUI(); - - // creation de l'action de fin de veille - addActivityFinDeVeille(closeActivityFinDeVeille); - - if (gotoActivityFinDeVeille) { - - // on selection l'activity de fin de veille et on y reste - // donc on ne continue pas la fermeture de la route - return false; - } - - // on retourne sur la route - // que l'on va refermer - treeHelper.selectNode(routeNode); - } - - // fermeture de la route - getOpenDataManager().closeRoute(getSelectedId()); - return true; - } - - protected ActivitySeineUI addActivityFinDeVeille(boolean close) { - - ObserveTreeHelper treeHelper = getTreeHelper(getUi()); - - // on créee l'activity de fin de veille - ObserveNode parentNode = treeHelper.getSelectedNode(); - parentNode = treeHelper.findNode( - parentNode, - n("observe.tree.activitySeine") - ); - if (log.isDebugEnabled()) { - log.debug("PARENT NODE = " + parentNode); - } - treeHelper.addUnsavedNode(parentNode, ActivitySeineDto.class); - - // on recupère l'écran d'édition - ActivitySeineUI selectedUI = (ActivitySeineUI) ObserveSwingApplicationContext.get().getContentUIManager().getSelectedContentUI(); - - // on recupère l'activity de fin de veille - ReferentialReference<VesselActivitySeineDto> vesselActivitySeine = null; - - for (ReferentialReference<VesselActivitySeineDto> refVesselActivity : selectedUI.getVesselActivitySeine().getData()) { - - if (ActivitySeineDto.ACTIVITY_FIN_DE_VEILLE.equals(refVesselActivity.getPropertyValue(VesselActivitySeineDto.PROPERTY_CODE))) { - vesselActivitySeine = refVesselActivity; - break; - } - } - - // on la positionne sur le bean d'édition - selectedUI.getBean().setVesselActivitySeine(vesselActivitySeine); - - // on initialise la fin de veille a la dernière minute du jour - selectedUI.getBean().setTime(DateUtil.getEndOfDay(DateUtil.createDate(0, 0, 0))); - - if (close) { - - // on sauvegarde l'activity - selectedUI.save(false); - - // on ferme l'activity - selectedUI.closeData(); - - // on ferme l'écean - selectedUI.stopEdit(); - } - return selectedUI; - } - - @Override - protected boolean obtainCanReopen(boolean create) { - - // on peut reouvrir une route si : - // - pas de route ouverte - // - la maree courante est ouverte - boolean canReopen = !create && getOpenDataManager().canOpenRoute(getSelectedParentId()); - return canReopen; - } - - protected void repaintTripNode() { - Boolean updateTripNode = getUi().getContextValue(Boolean.class, UPDATE_MAREE_NODE); - - getUi().removeContextValue(Boolean.class, UPDATE_MAREE_NODE); - - if (updateTripNode == null || !updateTripNode) { - return; - } - - - ObserveTreeHelper treeHelper = getTreeHelper(getUi()); - ObserveNode tripNode = treeHelper.getSelectedNode().getParent().getParent(); - if (log.isInfoEnabled()) { - log.info("Refresh trip node : " + tripNode); - } - treeHelper.reloadNode(tripNode, false); -// treeHelper.refreshNode(tripNode, false); - } - - protected void setUpdateMareeNodeTag(boolean wasUpdated) { - - if (wasUpdated) { - - // la date de fin a ete modifiee, il faut : redessiner le noeud de la maree le repositionner - getUi().setContextValue(Boolean.TRUE, UPDATE_MAREE_NODE); - - } else { - - getUi().removeContextValue(Boolean.class, UPDATE_MAREE_NODE); - - } - - } - - protected RouteService getRouteService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newRouteService(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/RouteUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/RouteUIModel.java deleted file mode 100644 index 750f249..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/RouteUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.open.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.ui.content.open.ContentOpenableUIModel; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class RouteUIModel extends ContentOpenableUIModel<RouteDto> { - - private static final long serialVersionUID = 1L; - - public RouteUIModel() { - super(RouteDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/TripSeineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/TripSeineUI.jaxx deleted file mode 100644 index 5d5529e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/TripSeineUI.jaxx +++ /dev/null @@ -1,256 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.open.ContentOpenableUI superGenericType='TripSeineDto' - contentTitle='{n("observe.content.tripSeine.title")}'> - - <import> - fr.ird.observe.services.dto.seine.TripSeineDto - fr.ird.observe.services.dto.seine.RouteDto - fr.ird.observe.services.dto.seine.RouteStubDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.HarbourDto - fr.ird.observe.services.dto.referential.PersonDtos - fr.ird.observe.services.dto.referential.VesselDto - fr.ird.observe.services.dto.referential.VesselDtos - fr.ird.observe.services.dto.referential.PersonDto - fr.ird.observe.services.dto.referential.OceanDto - fr.ird.observe.ui.util.tripMap.TripMapUI - - org.jdesktop.swingx.JXDatePicker - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - java.awt.Dimension - java.beans.PropertyChangeEvent - java.beans.PropertyChangeListener - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.apache.commons.lang3.StringUtils.isEmpty - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <TripSeineUIHandler id='handler' constructorParams='this'/> - - <!-- model --> - <TripSeineUIModel id='model'/> - - <!-- edit bean --> - <TripSeineDto id='bean'/> - - <!-- validator --> - <BeanValidator id='validator' - beanClass='fr.ird.observe.services.dto.seine.TripSeineDto' - errorTableModel='{getErrorTableModel()}' - autoField='true' - context='ui-update'> - - <field name='route' component='{actionDown}'/> - </BeanValidator> - - <script><![CDATA[ - -protected boolean canEditOcean(java.util.LinkedHashSet<RouteStubDto> routes) { - return routes == null || routes.isEmpty(); -} - -]]> - </script> - - <!-- formulaire --> - <JPanel id="body" layout='{new BorderLayout()}'> - <JTabbedPane id='tripSeineTabPane' constraints='BorderLayout.CENTER'> - <tab id='generalTab'> - <Table insets="0" fill="both"> - - <!-- captain --> - <row> - <cell anchor='west'> - <JLabel id='captainLabel'/> - </cell> - <cell anchor='east'> - <BeanComboBox id='captain' constructorParams='this' genericType='ReferentialReference<PersonDto>' _entityClass='PersonDto.class'/> - </cell> - </row> - - <!-- observer --> - <row> - <cell anchor='west'> - <JLabel id='observerLabel'/> - </cell> - <cell anchor='east'> - <BeanComboBox id='observer' constructorParams='this' genericType='ReferentialReference<PersonDto>' _entityClass='PersonDto.class'/> - </cell> - </row> - - <!-- dataEntryOperator --> - <row> - <cell anchor='west'> - <JLabel id='dataEntryOperatorLabel'/> - </cell> - <cell anchor='east'> - <BeanComboBox id='dataEntryOperator' constructorParams='this' genericType='ReferentialReference<PersonDto>' _entityClass='PersonDto.class'/> - </cell> - </row> - - <!-- vessel --> - <row> - <cell anchor='west'> - <JLabel id='vesselLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='vessel' constructorParams='this' genericType='ReferentialReference<VesselDto>' _entityClass='VesselDto.class'/> - </cell> - </row> - - <!-- ocean (editable uniquement si pas de route saisie) --> - <row> - <cell anchor='west'> - <JLabel id='oceanLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='ocean' genericType='ReferentialReference<OceanDto>' _entityClass='OceanDto.class' constructorParams='this'/> - </cell> - </row> - - <!-- departureHarbour --> - <row> - <cell anchor='west'> - <JLabel id='departureHarbourLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='departureHarbour' genericType='ReferentialReference<HarbourDto>' _entityClass='HarbourDto.class' constructorParams='this'/> - </cell> - </row> - - <!-- landingHarbour --> - <row> - <cell anchor='west'> - <JLabel id='landingHarbourLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='landingHarbour' genericType='ReferentialReference<HarbourDto>' _entityClass='HarbourDto.class' constructorParams='this'/> - </cell> - </row> - - <!-- id ers --> - <row> - - <cell anchor='west'> - <JLabel id='ersIdLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel layout='{new BorderLayout()}'> - <JToolBar id='ersIdToolbar' constraints='BorderLayout.WEST'> - <JButton id='resetErsId' constraints='BorderLayout.WEST' styleClass='resetButton'/> - </JToolBar> - <JTextField id='ersId' constraints='BorderLayout.CENTER'/> - </JPanel> - </cell> - </row> - - <!-- startDate --> - <row> - <cell anchor='west'> - <JLabel id='startDateLabel'/> - </cell> - <cell anchor='west' weightx="0.5"> - <JXDatePicker id='startDate'/> - </cell> - </row> - - <!-- endDate --> - <row> - <cell anchor='west'> - <JLabel id='endDateLabel'/> - </cell> - <cell anchor='west' weightx="0.5"> - <JXDatePicker id='endDate'/> - </cell> - </row> - - <!-- formsUrl --> - <row> - <cell anchor="west"> - <JLabel id='formsUrlLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel layout='{new BorderLayout()}'> - <JToolBar id='formsUrlToolbar' constraints='BorderLayout.WEST'> - <JButton id='resetFormsUrl' constraints='BorderLayout.WEST' styleClass='resetButton'/> - </JToolBar> - <JTextField id='formsUrl' constraints='BorderLayout.CENTER'/> - <JToolBar id='formsUrlToolbar2' constraints='BorderLayout.EAST'> - <JButton id='openLinkFormulairesUrl' - onActionPerformed='getHandler().openLink(getModel().getBean().getFormsUrl())'/> - </JToolBar> - - </JPanel> - </cell> - </row> - - <!-- reportsUrl --> - <row> - <cell anchor="west"> - <JLabel id='reportsUrlLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel layout='{new BorderLayout()}'> - <JToolBar id='reportsUrlToolbar' constraints='BorderLayout.WEST'> - <JButton id='resetReportsUrl' constraints='BorderLayout.WEST' styleClass='resetButton'/> - </JToolBar> - <JTextField id='reportsUrl' constraints='BorderLayout.CENTER'/> - - <JToolBar id='reportsUrlToolbar2' constraints='BorderLayout.EAST'> - <JButton id='openLinkRapportsUrl' constraints='BorderLayout.EAST' - onActionPerformed='getHandler().openLink(getModel().getBean().getReportsUrl())'/> - </JToolBar> - </JPanel> - </cell> - </row> - - <!-- comment --> - <row> - <cell fill='both' weighty="1" columns="2"> - <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2' onKeyReleased='getModel().getBean().setComment(comment2.getText())'/> - </JScrollPane> - </cell> - </row> - </Table> - </tab> - <tab id="mapTab"> - <TripMapUI id="tripMap"/> - </tab> - </JTabbedPane> - </JPanel> - - <!-- surcharge des actions (pour appliquer la css specifique) --> - <JButton id='delete'/> - <JButton id='reopen'/> - <JButton id='close'/> - <JButton id='closeAndCreate'/> - <JButton id='actionDown'/> - -</fr.ird.observe.ui.content.open.ContentOpenableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/TripSeineUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/TripSeineUI.jcss deleted file mode 100644 index 8629585..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/TripSeineUI.jcss +++ /dev/null @@ -1,225 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -BeanComboBox { - bean:{bean}; -} - -NumberEditor { - bean:{bean}; - useFloat:false; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; -} - -#generalTab { - title: {t("observe.content.tripSeine.tab.general")}; -} - -#mapTab { - title: {t("observe.content.tripSeine.tab.map")}; -} - -#model { - editable:true; - modified:{validator.isChanged()}; - valid:{validator.isValid()}; -} - -#observerLabel { - text:"observe.common.observer"; - labelFor:{observer}; -} - -#observer { - property:{TripSeineDto.PROPERTY_OBSERVER}; - selectedItem:{bean.getObserver()}; -} - -#captainLabel { - text:"observe.common.captain"; - labelFor:{captain}; -} - -#captain { - property:{TripSeineDto.PROPERTY_CAPTAIN}; - selectedItem:{bean.getCaptain()}; -} - -#dataEntryOperatorLabel { - text:"observe.common.dataEntryOperator"; - labelFor:{dataEntryOperator}; -} - -#dataEntryOperator { - property:{TripSeineDto.PROPERTY_DATA_ENTRY_OPERATOR}; - selectedItem:{bean.getDataEntryOperator()}; -} - -#vesselLabel { - text:"observe.common.vessel"; - labelFor:{vessel}; -} - -#vessel { - property:{TripSeineDto.PROPERTY_VESSEL}; - selectedItem:{bean.getVessel()}; -} - -#oceanLabel { - text:"observe.common.ocean"; - labelFor:{ocean}; -} - -#ocean { - property:{TripSeineDto.PROPERTY_OCEAN}; - selectedItem:{bean.getOcean()}; - enabled:{canEditOcean(bean.getRoute())}; -} - -#departureHarbourLabel { - text:"observe.common.departureHarbour"; - labelFor:{departureHarbour}; -} - -#departureHarbour { - property:{TripSeineDto.PROPERTY_DEPARTURE_HARBOUR}; - selectedItem:{bean.getDepartureHarbour()}; -} - -#landingHarbourLabel { - text:"observe.common.landingHarbour"; - labelFor:{landingHarbour}; -} - -#landingHarbour { - property:{TripSeineDto.PROPERTY_LANDING_HARBOUR}; - selectedItem:{bean.getLandingHarbour()}; -} - -#ersIdLabel{ - text:"observe.common.ersId"; - labelFor:{ersId}; -} - -#resetErsId{ - toolTipText:"observe.content.action.reset.ersId.tip"; - _resetPropertyName:{TripSeineDto.PROPERTY_ERS_ID}; -} - -#ersId { - _propertyName:{TripSeineDto.PROPERTY_ERS_ID}; - text:{getStringValue(bean.getErsId())}; -} - -#startDateLabel { - text:"observe.common.startDate"; - labelFor:{startDate}; -} - -#startDate { - _propertyName:{TripSeineDto.PROPERTY_START_DATE}; - date:{bean.getStartDate()}; -} - -#endDateLabel { - text:"observe.common.endDate"; - labelFor:{endDate}; -} - -#endDate { - _propertyName:{TripSeineDto.PROPERTY_END_DATE}; - date:{bean.getEndDate()}; -} - -#formsUrlLabel { - text:"observe.common.formsUrl"; - labelFor:{formsUrl}; -} - -#resetFormsUrl { - _resetPropertyName:{TripSeineDto.PROPERTY_FORMS_URL}; - toolTipText:"observe.content.action.reset.formsUrl.tip"; -} - -#formsUrl { - _propertyName:{TripSeineDto.PROPERTY_FORMS_URL}; - text:{getStringValue(bean.getFormsUrl())}; -} - -#openLinkFormulairesUrl { - actionIcon:"openLink"; - opaque:false; - enabled:{!isEmpty(bean.getFormsUrl())}; - toolTipText:"observe.content.action.openLink.formsUrl.tip"; - _notBlocking:true; -} - -#reportsUrlLabel { - text:"observe.common.reportsUrl"; - labelFor:{reportsUrl}; -} - -#resetReportsUrl { - _resetPropertyName:{TripSeineDto.PROPERTY_REPORTS_URL}; - toolTipText:"observe.content.action.reset.reportsUrl.tip"; -} - -#reportsUrl { - _propertyName:{TripSeineDto.PROPERTY_REPORTS_URL}; - text:{getStringValue(bean.getReportsUrl())}; -} - -#openLinkRapportsUrl { - actionIcon:"openLink"; - opaque:false; - enabled:{!isEmpty(bean.getReportsUrl())}; - toolTipText:"observe.content.action.openLink.reportsUrl.tip"; - _notBlocking:true; -} - -#comment { - columnHeaderView:{new JLabel(t("observe.common.comment"))}; - minimumSize:{new Dimension(10,50)}; -} - -#comment2 { - text:{getStringValue(bean.getComment())}; -} - -#reopen { - _toolTipText:{t("observe.content.action.reopen.maree.tip")}; -} - -#close { - enabled:{!model.isModified() && (model.isHistoricalData() || model.isValid()) && !dataContext.isOpenRoute()}; - _toolTipText:{t("observe.action.close.maree.tip")}; -} - -#closeAndCreate { - enabled:{!model.isModified() && (model.isHistoricalData() || model.isValid()) && !dataContext.isOpenRoute()}; - _text:{t("observe.content.action.closeAndCreate.maree")}; - _toolTipText:{t("observe.content.action.closeAndCreate.maree.tip")}; -} - -#delete { - _toolTipText:{t("observe.action.delete.maree.tip")}; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/TripSeineUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/TripSeineUIHandler.java deleted file mode 100644 index 8f55cbf..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/TripSeineUIHandler.java +++ /dev/null @@ -1,370 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.open.impl.seine; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.TripMapDto; -import fr.ird.observe.services.dto.referential.PersonDtos; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.VesselDtos; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.services.dto.seine.TripSeineDtos; -import fr.ird.observe.services.service.seine.TripSeineService; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.open.ContentOpenableUIHandler; -import fr.ird.observe.ui.content.open.ContentOpenableUIModel; -import fr.ird.observe.ui.util.tripMap.TripMapUI; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.util.DateUtil; - -import javax.swing.JTabbedPane; -import javax.swing.SwingUtilities; -import java.util.Collection; -import java.util.Date; -import java.util.LinkedList; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class TripSeineUIHandler extends ContentOpenableUIHandler<TripSeineDto> { - - /** Logger */ - static private final Log log = LogFactory.getLog(TripSeineUIHandler.class); - - protected boolean buildTripMap = true; - - public TripSeineUIHandler(TripSeineUI ui) { - super(ui, - DataContextType.Program, - DataContextType.TripSeine, - n("observe.content.tripSeine.message.not.open")); - } - - - @Override - public TripSeineUI getUi() { - return (TripSeineUI) super.getUi(); - } - - @Override - public boolean doCloseData() { - boolean result = getOpenDataManager().isOpenTripSeine(getSelectedId()); - if (result) { - getOpenDataManager().closeTripSeine(getSelectedId()); - } - return result; - } - - @Override - public void initUI() { - super.initUI(); - - TripSeineUI ui = getUi(); - TripMapUI tripMap = ui.getTripMap(); - ObserveSwingApplicationConfig config = ObserveSwingApplicationContext.get().getConfig(); - - tripMap.getHandler().setConfig(config); - - getUi().getTripSeineTabPane().addChangeListener(e -> { - JTabbedPane tripSeineTabPane = (JTabbedPane) e.getSource(); - TripSeineUI ui1 = getUi(); - TripMapUI tripMap1 = ui1.getTripMap(); - if (tripSeineTabPane.getSelectedComponent().equals(tripMap1)) { - ui1.getActions().setVisible(false); - - if (buildTripMap) { - SwingUtilities.invokeLater(() -> { - - TripSeineUI ui11 = getUi(); - TripMapUI tripMap11 = ui11.getTripMap(); - TripMapDto tripSeineMap = getTripSeineService().getTripSeineMap(getSelectedId()); - - - tripMap11.getHandler().doOpenMap(tripSeineMap); - }); - buildTripMap = false; - } - - } else { - ui1.getActions().setVisible(true); - } - }); - - } - - @Override - public void openUI() { - super.openUI(); - - ContentMode mode = computeContentMode(); - - String programId = getSelectedParentId(); - final String tripId = getSelectedId(); - - if (log.isInfoEnabled()) { - log.info(prefix + "programId = " + programId); - log.info(prefix + "tripId = " + tripId); - log.info(prefix + "mode = " + mode); - } - - TripSeineDto bean = getBean(); - - boolean create = tripId == null; - - Form<TripSeineDto> form; - if (create) { - - // create mode - if (log.isInfoEnabled()) { - log.info(prefix + "create a new trip"); - } - form = getTripSeineService().preCreate(programId); - - } else { - - // update mode - if (log.isInfoEnabled()) { - log.info(prefix + "load existing trip " + tripId); - } - form = getTripSeineService().loadForm(tripId); - - } - - setContentMode(mode); - - loadReferentialReferenceSetsInModel(form); - - getModel().setForm(form); - TripSeineDtos.copyTripSeineDto(form.getObject(), bean); - - getUi().getTripSeineTabPane().setSelectedIndex(0); - getUi().getTripMap().getHandler().doCloseMap(); - buildTripMap = true; - - finalizeOpenUI(mode, create); - } - - @Override - public void startEditUI(String... binding) { - - TripSeineUI ui = getUi(); - - ContentOpenableUIModel<TripSeineDto> model = getModel(); - - ContentMode mode = model.getMode(); - - boolean create = mode == ContentMode.CREATE; - - String contextName = getValidatorContextName(mode); - ui.getValidator().setContext(contextName); - - if (create) { - - addInfoMessage(t("observe.content.tripSeine.message.creating")); - } else { - addInfoMessage(t("observe.content.tripSeine.message.updating")); - if (model.isHistoricalData()) { - - addInfoMessage(t("observe.message.historical.data")); - } - } - - // date is current day - if (model.getMode() == ContentMode.UPDATE) { - if (getBean().getEndDate() == null) { - Date date = DateUtil.getEndOfDay(new Date()); - getBean().setEndDate(date); - if (log.isDebugEnabled()) { - log.debug("end date : " + date); - } - } - } - - super.startEditUI(TripSeineUI.BINDING_VESSEL_SELECTED_ITEM, - TripSeineUI.BINDING_OBSERVER_SELECTED_ITEM, - TripSeineUI.BINDING_CAPTAIN_SELECTED_ITEM, - TripSeineUI.BINDING_DATA_ENTRY_OPERATOR_SELECTED_ITEM, - TripSeineUI.BINDING_OCEAN_SELECTED_ITEM, - TripSeineUI.BINDING_START_DATE_DATE, - TripSeineUI.BINDING_END_DATE_DATE, - TripSeineUI.BINDING_COMMENT2_TEXT, - TripSeineUI.BINDING_ERS_ID_TEXT, - TripSeineUI.BINDING_CLOSE_ENABLED, - TripSeineUI.BINDING_CLOSE_AND_CREATE_ENABLED); - model.setModified(create); - } - - @Override - protected boolean doOpenData() { - boolean result = getOpenDataManager().canOpenTripSeine(); - if (result) { - getOpenDataManager().openTripSeine(getSelectedParentId(), getSelectedId()); - } - return result; - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - String tripSeineId = getSelectedId(); - - if (tripSeineId == null) { - - // maree en cours de creation - return ContentMode.CREATE; - } - - if (getOpenDataManager().isOpenTripSeine(tripSeineId)) { - - // maree ouverte - return ContentMode.UPDATE; - } - - addInfoMessage(t(closeMessage)); - return ContentMode.READ; - - } - - @Override - protected boolean doSave(TripSeineDto bean) throws Exception { - - boolean notPersisted = bean.isNotPersisted(); - - // on force toujours la date a etre sans heure, minute,... - Date startDate = DateUtil.getDay(bean.getStartDate()); - if (log.isDebugEnabled()) { - log.debug("startDate = " + startDate); - } - bean.setStartDate(startDate); - - Date endDate = bean.getEndDate(); - if (log.isDebugEnabled()) { - log.debug("endDate = " + endDate); - } - - SaveResultDto saveResult = getTripSeineService().save(bean); - saveResult.toDto(bean); - - // recuperation de la position de la maree dans le program - obtainChildPosition(bean); - - // ouverture de la marée - if (notPersisted) { - getOpenDataManager().openTripSeine(getSelectedParentId(), bean.getId()); - } - - return true; - } - - protected int getOpenablePosition(String parentId, TripSeineDto bean) { - - int position = getTripSeineService().getTripSeinePositionInProgram(parentId, bean.getId()); - - return position; - } - - @Override - protected boolean doDelete(TripSeineDto bean) { - - if (askToDelete(bean)) { - return false; - } - if (log.isInfoEnabled()) { - log.info("Will delete Trip " + bean.getId()); - } - - getTripSeineService().delete(bean.getId()); - getOpenDataManager().closeTripSeine(bean.getId()); - - if (log.isInfoEnabled()) { - log.info("Delete done for Trip " + bean.getId()); - } - return true; - } - - @Override - protected boolean obtainCanReopen(boolean create) { - return !create && getOpenDataManager().canOpenTripSeine(); - } - - @Override - protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { - - Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); - - switch (propertyName) { - - case TripSeineDto.PROPERTY_CAPTAIN: { - result = (List) PersonDtos.filterCaptainReferences((List) result); - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - } - break; - - case TripSeineDto.PROPERTY_OBSERVER: { - result = (List) PersonDtos.filterObserverReferences((List) result); - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - } - break; - - case TripSeineDto.PROPERTY_DATA_ENTRY_OPERATOR: { - result = (List) PersonDtos.filterDataEntryOperatorReferences((List) result); - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - } - break; - - case TripSeineDto.PROPERTY_VESSEL: { - ObserveSwingApplicationConfig config = ObserveSwingApplicationContext.get().getConfig(); - result = (List) VesselDtos.filterVesselReferencesByVesselTypeIds((List) result, config.getSeineVesselTypeIds()); - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - } - break; - - } - - return result; - } - - protected TripSeineService getTripSeineService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripSeineService(); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/TripSeineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/TripSeineUIModel.java deleted file mode 100644 index 1636b6c..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/open/impl/seine/TripSeineUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.open.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.ui.content.open.ContentOpenableUIModel; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class TripSeineUIModel extends ContentOpenableUIModel<TripSeineDto> { - - private static final long serialVersionUID = 1L; - - public TripSeineUIModel() { - super(TripSeineDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ContentReferenceUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ContentReferenceUI.jaxx deleted file mode 100644 index 68190ad..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ContentReferenceUI.jaxx +++ /dev/null @@ -1,201 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ContentUI abstract='true' - superGenericType='E' - genericType='E extends ReferentialDto'> - - <import> - fr.ird.observe.services.dto.referential.ReferentialDto - fr.ird.observe.services.dto.referential.ReferentialReference - - fr.ird.observe.ui.UIHelper - fr.ird.observe.ui.actions.shared.DeleteReferenceUIAction - fr.ird.observe.ui.actions.shared.ResetEditUIAction - fr.ird.observe.ui.actions.shared.SaveEditUIAction - - jaxx.runtime.swing.editor.bean.BeanListHeader - jaxx.runtime.validator.swing.SwingValidator - - javax.swing.DefaultListModel - javax.swing.ListSelectionModel - javax.swing.JTable - javax.swing.UIManager - javax.swing.table.TableCellRenderer - </import> - - <java.lang.String id='listText' javaBean='""'/> - <java.lang.String id='createToolTip' javaBean='""'/> - <java.lang.String id='detailToolTip' javaBean='""'/> - <java.lang.String id='modifyToolTip' javaBean='""'/> - <java.lang.String id='deleteToolTip' javaBean='""'/> - <java.lang.String id='saveToolTip' javaBean='""'/> - - <ContentReferenceUIModel id='model' genericType='E'/> - - <ContentReferenceUIHandler id='handler' genericType='E' constructorParams='this'/> - - <BlockingLayerUI id='editKeyTableLayerUI'/> - - <CardLayout2Ext id='viewLayout' constructorParams='this, "body"'/> - - <script><![CDATA[ - -public static final String LIST_VIEW = "listView"; - -public static final String DETAIL_VIEW = "detailView"; - -public abstract SwingValidator<E> getValidator(); - -public void decorateUniqueKeyTable(JTable table, - TableCellRenderer renderer, - JScrollPane pane) { - table.setAutoResizeMode(JTable.AUTO_RESIZE_LAST_COLUMN); - UIHelper.fixTableColumnWidth(table, 1, 70); -} - -body.setLayout(viewLayout); -viewLayout.addLayoutComponent(listView, LIST_VIEW); -viewLayout.addLayoutComponent(editView, DETAIL_VIEW); - -]]></script> - - <JPanel id="body"> - - <JPanel id="listView" constraints="LIST_VIEW"> - <JScrollPane id='listPane' constraints='BorderLayout.CENTER' columnHeaderView='{referentialListHeader}'> - <JList id='list' - onValueChanged='if (!event.getValueIsAdjusting()) { getHandler().selectBean((ReferentialReference<E>)getSelectedBean(list)); }' - onMouseClicked='if (event.getClickCount() == 2) { getHandler().modifyUI(); }'/> - - <BeanListHeader id='referentialListHeader' genericType='ReferentialReference<E>' _entityClass="getModel().getBeanType()"/> - </JScrollPane> - </JPanel> - - <Table id="editView" insets="0" weightx="1" fill="both" - constraints="DETAIL_VIEW"> - <row> - <cell anchor='north'> - <!-- pour les autres propriétés du référentiel à editer --> - <Table id='editTable' fill='both' insets="1"/> - </cell> - </row> - <row> - <cell anchor='north'> - <!-- pour les autres propriétés du référentiel à editer --> - <Table id='editExtraTable' fill='both' insets="1"/> - </cell> - </row> - <row> - <cell anchor='north'> - <!-- pour les propriétés i18n du référentiel à editer --> - <Table id='editI18nTable' fill='both' insets="1"/> - </cell> - </row> - <row> - <cell anchor='north' weighty="1"> - <!-- pour les autres propriétés (à mettre après i18n) à editer --> - <Table id='editMoreExtraTable' fill='both' insets="1"> - <row> - <cell> - <javax.swing.Box.Filler id='filler' - constructorParams='UIHelper.newMinDimension(), UIHelper.newMinDimension(), UIHelper.newMaxXDimension()'/> - </cell> - </row> - </Table> - </cell> - </row> - <!--row> - <cell weighty="1" anchor='north'> - <javax.swing.Box.Filler id='filler' - constructorParams='UIHelper.newMinDimension(), UIHelper.newMinDimension(), UIHelper.newMaxXDimension()'/> - </cell> - </row--> - </Table> - - </JPanel> - - <Table id='actions' fill='both' weightx='1' insets='0'> - <row> - <cell> - <Table id="listActions" fill="both" weightx="1" insets="1" visible='{!model.isEditing()}'> - <row> - <cell> - <JButton id='create' onActionPerformed='getHandler().createUI()'/> - </cell> - <cell> - <JButton id='modify' onActionPerformed='getHandler().modifyUI()'/> - </cell> - <cell> - <JButton id='detail' onActionPerformed='getHandler().modifyUI()'/> - </cell> - <cell> - <JButton id='deleteFromList' styleClass='delete'/> - </cell> - </row> - </Table> - </cell> - </row> - <row> - <cell> - <Table id="detailActions" fill='both' insets="1,4,1,1" - visible='{model.isEditing()}'> - <row> - <cell fill="both" weightx="1"> - <Table fill="both" weightx="1" insets="1" visible='{!model.isReadingMode()}'> - <row> - <cell> - <JButton id='reset'/> - </cell> - <cell> - <JButton id='save'/> - </cell> - <cell> - <JButton id='deleteFromDetail' styleClass='delete'/> - </cell> - </row> - </Table> - </cell> - </row> - <row> - <cell fill="both" weightx="1"> - <JButton id='backToList' onActionPerformed='getHandler().backToList()'/> - <!--onActionPerformed='getHandelr().backToList();if (!model.isModified() || fr.ird.observe.ui.content.ContentUIHandler.checkEdit(this)) { stopEdit(); }'/--> - </cell> - </row> - </Table> - </cell> - </row> - </Table> - - <JPanel id="invisible"> - - <JButton id="showUsages" onActionPerformed='getHandler().showUsages()'/> - - <JButton id='showUniqueKeys' onActionPerformed='getHandler().showUniqueKeys((JButton) event.getSource());'/> - - <JButton id='showTechnicalInformations' - onActionPerformed='getHandler().showTechnicalInformations((JButton) event.getSource());'/> - - </JPanel> - -</fr.ird.observe.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ContentReferenceUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ContentReferenceUIHandler.java deleted file mode 100644 index 7e0eacc..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ContentReferenceUIHandler.java +++ /dev/null @@ -1,828 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.ref; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.services.dto.ReferenceMap; -import fr.ird.observe.services.dto.constants.ReferenceStatus; -import fr.ird.observe.services.dto.constants.ReferentialLocale; -import fr.ird.observe.services.dto.reference.request.ReferenceSetRequestDefinitions; -import fr.ird.observe.services.dto.referential.I18nReferentialDto; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.VesselSizeCategoryDto; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.service.DataNotFoundException; -import fr.ird.observe.services.service.ReferentialService; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.ContentUIHandler; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.ui.usage.UsagesUI; -import fr.ird.observe.ui.util.SpringUtilities; -import fr.ird.observe.validation.ValidationContext; -import jaxx.runtime.JAXXContext; -import jaxx.runtime.swing.CardLayout2Ext; -import jaxx.runtime.swing.editor.bean.BeanListHeader; -import jaxx.runtime.validator.swing.SwingValidatorUtil; -import org.apache.commons.collections4.MapUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.time.FastDateFormat; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.decorator.Decorator; -import org.nuiton.util.beans.Binder; -import org.nuiton.util.beans.BinderFactory; - -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.JToolBar; -import javax.swing.RowSorter; -import javax.swing.SortOrder; -import javax.swing.SpringLayout; -import javax.swing.SwingUtilities; -import javax.swing.border.TitledBorder; -import javax.swing.table.DefaultTableCellRenderer; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.Font; -import java.beans.Introspector; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Locale; -import java.util.Set; - -import static org.nuiton.i18n.I18n.t; - -/** - * Controleur d'un écran d'édition du référentiel. - * - * @param <E>le type d'entité - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ContentReferenceUIHandler<E extends ReferentialDto> extends ContentUIHandler<E> { - - /** Logger */ - private static final Log log = - LogFactory.getLog(ContentReferenceUIHandler.class); - - private final Runnable revalidate; - - private final ReferentialContentUIInitializer<E, ContentReferenceUI<E>> uiInitializer; - - private final FastDateFormat dateFormat; - - public ContentReferenceUIHandler(ContentReferenceUI<E> ui) { - super(ui, null, null); - uiInitializer = new ReferentialContentUIInitializer<>(ui); - Locale locale = ui.getConfig().getLocale(); - if (Locale.ENGLISH.equals(locale)) { - dateFormat = FastDateFormat.getInstance("yyyy-MM-ddZZ"); - } else { - dateFormat = FastDateFormat.getInstance("dd/MM/yyyy"); - } - - revalidate = () -> { - - // revalidate ui layout - ContentReferenceUI<E> ui1 = getUi(); - Container parent = ui1.getParent(); - if (parent == null) { - - // plus de parent donc rien a faire - return; - } - if (log.isDebugEnabled()) { - log.debug("Will revalidate " + parent.getName()); - } - ui1.revalidate(); - }; - } - - public static <E extends IdDto> void showUsagesForDelete(JAXXContext tx, - E entity, - ReferenceMap usages) { - - DecoratorService service = ObserveSwingApplicationContext.get().getDecoratorService(); - Decorator<?> decorator = service.getDecoratorByType(entity.getClass()); - String type = DecoratorService.getEntityLabel(entity.getClass()); - type = t(type); - String message = t("observe.message.show.usage.for.delete", type, decorator.toString(entity)); - String message2 = t("observe.message.show.usage.for.delete2"); - - UsagesUI usagesUI = new UsagesUI(tx); - usagesUI.init(message, message2, null, usages); - - UIHelper.askUser(null, - t("observe.title.can.not.delete.referentiel"), - usagesUI, - JOptionPane.WARNING_MESSAGE, - new Object[]{ - t("observe.choice.cancel")}, - 0); - } - - public static <E extends IdDto> boolean showUsagesForDesactivated(JAXXContext tx, - E entity, - ReferenceMap usages) { - - DecoratorService service = ObserveSwingApplicationContext.get().getDecoratorService(); - Decorator<?> decorator = service.getDecoratorByType(entity.getClass()); - String type = DecoratorService.getEntityLabel(entity.getClass()); - type = t(type); - String message = t("observe.message.show.usage.for.desactivated", type, decorator.toString(entity)); - String message2 = t("observe.message.show.usage.for.desactivated2"); - String message3 = t("observe.message.show.usage.for.desactivated3"); - - UsagesUI usagesUI = new UsagesUI(tx); - usagesUI.init(message, message2, message3, usages); - - int reponse = UIHelper.askUser(null, - t("observe.title.need.confirm.to.desactivate.referentiel"), - usagesUI, - JOptionPane.WARNING_MESSAGE, - new Object[]{ - t("observe.choice.save"), - t("observe.choice.cancel")}, - 0); - if (log.isDebugEnabled()) { - log.debug("response : " + reponse); - } - - switch (reponse) { - case 0: - // will save ui - return true; - - } - // any other case : do not save - return false; - } - - public void selectBean(ReferentialReference<E> selectedReference) { - - if (selectedReference != null) { - - Form<E> form = getReferentialService().loadForm(getBeanType(), selectedReference.getId()); - getModel().setForm(form); - - E selectedBean = form.getObject(); - - getModel().setSelectedBean(selectedBean); - - // copy right now the selected bean to the model bean to respect contract - // of parent handler (for delation or save object...) - - Binder<E, E> binder = BinderFactory.newBinder(getBeanType()); - binder.copy(selectedBean, getBean()); - - //TODO update data cache - } - - } - - @Override - public ContentReferenceUI<E> getUi() { - return (ContentReferenceUI<E>) super.getUi(); - } - - @Override - public ContentReferenceUIModel<E> getModel() { - return getUi().getModel(); - } - - @Override - protected boolean computeCanWrite(ObserveSwingDataSource source) { - return source.canWriteReferential(); - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - addInfoMessage(t("observe.message.referentiel.editable")); - - return ContentMode.UPDATE; - } - - /** - * Pour afficher une popup avec l'ensemble des clefs metiers utilisées. - * - * @param button le boutton qui a declanche l'action - */ - public void showUniqueKeys(JButton button) { - Class<E> beanType = getBeanType(); - - Set<ReferentialReference<E>> entities = getDataSource().getReferentialReferences(beanType); - List<Object[]> datas = new ArrayList<>(entities.size()); - - String[] naturalIds = getModel().getNaturalIds(); - int nbColumns = naturalIds.length + 1; - - String[] columns = new String[nbColumns]; - System.arraycopy(naturalIds, 0, columns, 1, naturalIds.length); - columns[0] = StringUtils.removeEnd(Introspector.decapitalize(beanType.getSimpleName()), "Dto"); - - DecoratorService dService = getDecoratorService(); - ReferentialReferenceDecorator<E> decorator = dService.getReferentialReferenceDecorator(beanType); - - for (ReferentialReference<E> e : entities) { - - Object[] data = new Object[nbColumns]; - int index = 0; - data[0] = decorator.toString(e); - - for (String property : naturalIds) { - Object o = null; - if (e.getPropertyNames().contains(property)) { - o = e.getPropertyValue(property); - } - if (ContentReferenceUIModel.DEFAULT_PROPERTIES[0].equals(property) && o == null) { - // cas special du code à 0, le loador ne retourne pas - // de valeur car c'est la valeur par defaut d'un type - // primitif, on force donc l'utilisation du zero. - o = 0; - } - if ("code".equals(property) && o == null) { - // cas special du code à 0, le loador ne retourne pas - // de valeur car c'est la valeur par defaut d'un type - // primitif, on force donc l'utilisation du zero. - o = 0; - } - if ("gender".equals(property) && o == null) { - // cas special du code à 0, le loador ne retourne pas - // de valeur car c'est la valeur par defaut d'un type - // primitif, on force donc l'utilisation du zero. - o = 0; - } - Object value; - if (o instanceof ReferentialDto) { - // on doit decorer la valeur - Decorator<?> d = dService.getDecoratorByType(o.getClass()); - value = d.toString(o); - } else { - value = o; - } - data[++index] = value; - } - datas.add(data); - } - - JTable table = new JTable(new UniqueKeyTableModel(columns, datas)); - - table.setAutoCreateRowSorter(true); - table.getRowSorter().setSortKeys(Collections.singletonList(new RowSorter.SortKey(0, SortOrder.ASCENDING))); - table.setFillsViewportHeight(true); - JScrollPane pane = new JScrollPane(); - - getUi().decorateUniqueKeyTable(table, new DefaultTableCellRenderer(), pane); - - pane.setViewportView(table); - pane.setVerticalScrollBarPolicy( - JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - - String title = t("observe.title.unique.key", - t(DecoratorService.getEntityLabel(beanType))); - - pane.setBorder(new TitledBorder(title)); - - JPopupMenu popup = new JPopupMenu(); - popup.setBorder(null); - popup.add(pane); - popup.pack(); - Dimension dim = popup.getPreferredSize(); - int x = (int) (button.getPreferredSize().getWidth() - dim.getWidth()); - int y = button.getHeight(); - popup.show(button, x, y); - } - - public void showUsages() { - - E bean; - - if (getModel().isEditing()) { - bean = getModel().getBean(); - } else { - bean = getModel().getSelectedBean(); - } - - // recherche des utilisation du bean dans la base - ReferenceMap usages; - try { - usages = getReferentialService().findAllUsages(bean); - - } catch (DataNotFoundException e) { - UIHelper.handlingError(e); - return; - } - - DecoratorService dService = getDecoratorService(); - Decorator<?> decorator = dService.getDecoratorByType(bean.getClass()); - String type = DecoratorService.getEntityLabel(bean.getClass()); - type = t(type); - String message = t("observe.message.show.usages", type, decorator.toString(bean)); - - ContentReferenceUI<E> ui = getUi(); - - UsagesUI usagesUI = new UsagesUI(ui); - usagesUI.init(message, null, null, usages); - - UIHelper.askUser(ui, - t("observe.title.show.usage"), - usagesUI, - JOptionPane.INFORMATION_MESSAGE, - new Object[]{t("observe.choice.quit")}, - 0); - } - - /** - * Pour afficher une popup avec l'ensemble des informations techniques. - * - * @param button le boutton qui a declanche l'action - */ - public void showTechnicalInformations(JButton button) { - - ReferentialDto bean = getModel().isEditing() ? getBean() : getModel().getSelectedBean(); - - JPanel content = new JPanel(new SpringLayout()); - - content.add(new JLabel(t("observe.common.topiaId"))); - content.add(new JLabel(bean.getId())); - - content.add(new JLabel(t("observe.common.topiaCreateDate"))); - - content.add(new JLabel(dateFormat.format(bean.getCreateDate()))); - - content.add(new JLabel(t("observe.common.lastUpdateDate"))); - - content.add(new JLabel(dateFormat.format(bean.getLastUpdateDate()))); - - content.add(new JLabel(t("observe.common.topiaVersion"))); - content.add(new JLabel(String.valueOf(bean.getVersion()))); - - SpringUtilities.makeCompactGrid(content, 4, 2, 5, 5, 5, 5); - - Decorator<E> decorator = getDecoratorService().getDecoratorByType(getBeanType()); - - String title = t("observe.title.technical.informations", - "\n" + decorator.toString(bean)); - - content.setBorder(new TitledBorder(title)); - - JPopupMenu popup = new JPopupMenu(); - popup.setBorderPainted(true); - popup.add(content); - popup.pack(); - Dimension dim = popup.getPreferredSize(); - int x = (int) (button.getPreferredSize().getWidth() - dim.getWidth()); - int y = button.getHeight(); - popup.show(button, x, y); - } - - @Override - public void initUI() { - - uiInitializer.initUI(); - - ContentReferenceUI<E> ui = getUi(); - - ui.getViewLayout().addPropertyChangeListener(CardLayout2Ext.SELECTED_PROPERTY_NAME, - evt -> SwingUtilities.invokeLater(revalidate)); - -// UIHelper.getLayer(ui.getEditKeyTable()).setUI(ui.getEditKeyTableLayerUI()); - } - - @Override - public void openUI() { - super.openUI(); - - ContentReferenceUIModel<E> model = getModel(); - - ReferenceSetRequestDefinitions requestDefinition = ReferenceSetRequestDefinitions.get(getBeanType()); - loadReferentialReferenceSetsInModel(requestDefinition.name()); - - // Chargement des données - updateUiWithReferenceSetsFromModel(); - - ContentReferenceUI<E> ui = getUi(); - - if (I18nReferentialDto.class.isAssignableFrom(model.getBeanType())) { - // on met en gras le libelle selectionne en base - - ReferentialLocale localeEnum; - localeEnum = ReferentialLocale.valueOf( - ui.getConfig().getDbLocale()); - String libelleName = localeEnum.getLibelle() + "Label"; - for (int i = 1; i <= 8; i++) { - String lib = "label" + i + "Label"; - JLabel label = (JLabel) ui.getObjectById(lib); - if (label == null) { - // not in ui actually - continue; - } - Font font = label.getFont(); - Font normalFont = font.deriveFont(Font.PLAIN); - Font boldFont = font.deriveFont(Font.BOLD); - - if (libelleName.equals(lib)) { - // on met en gras le label - font = boldFont; - } else { - // on met en normal le label - font = normalFont; - } - label.setFont(font); - ((JComponent) ui.getObjectById("label" + i)).setFont(font); - } - } - ContentMode mode = computeContentMode(); - model.setMode(mode); - if (mode != ContentMode.READ) { - //FIXME le binding ne marche pas en init - ui.processDataBinding(ContentReferenceUI.BINDING_DELETE_FROM_LIST_ENABLED); - } - } - - @Override - protected void updateToolbarActions() { - - // nettoyage de la toolbar - super.updateToolbarActions(); - - // on ajoute les deux actions showUsages et showUniqueKeys - ContentReferenceUI<E> ui = getUi(); - JToolBar toolBar = ui.getTitleRightToolBar(); - toolBar.add(ui.getShowUniqueKeys(), 2); - toolBar.add(ui.getShowTechnicalInformations(), 2); - toolBar.add(ui.getShowUsages(), 2); - } - - @Override - public void startEditUI(String... binding) { - - ContentReferenceUI<E> ui = getUi(); - - ContentReferenceUIModel<E> model = getModel(); - - E bean = model.getBean(); - ContentMode mode = model.getMode(); - boolean canEdit = mode != ContentMode.READ; - if (canEdit) { - removeAllMessages(ui); - String contextName = getValidatorContextName(mode); - if (log.isDebugEnabled()) { - log.debug("contextName = " + contextName); - } - ui.getValidator().setContext(contextName); - - if (mode == ContentMode.CREATE) { - addInfoMessage(t("observe.message.creating.referentiel")); - - // creation mode - Form<E> form = getReferentialService().preCreate(getBeanType()); - - loadReferentialReferenceSetsInModel(form); - - getModel().setForm(form); - - copyIntoBean(form.getObject(), bean); - - } else { - addInfoMessage(t("observe.message.updating.referentiel")); - } - - // do edit - super.startEditUI(model.getDataBinding()); - - if (mode == ContentMode.UPDATE) { - - // nothing has changed just after starting editing - ui.getValidator().setChanged(false); - } - } else { - - // reset all validators - SwingValidatorUtil.setValidatorBean(ui, null); - - // load bean - UIHelper.processDataBinding(ui, model.getDataBinding()); - - // pass in editing mode (without any modification possible) - model.setEditing(true); - - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ValidationContext validationContext = applicationContext.getValidationContext(); - validationContext.cleanCache(); - } - } - - protected void reloadReferentialReferenceSetsInModel(Form<E> form) { - - loadReferentialReferenceSetsInModel(form); - - updateReferentialBeanListHeader(getModel().getBeanType(), getUi().getReferentialListHeader()); - - } - - @Override - protected void prepareValidationContext() { - super.prepareValidationContext(); - BeanListHeader<ReferentialReference<E>> jList = getUi().getReferentialListHeader(); - List<ReferentialReference<E>> data = jList.getData(); - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ValidationContext validationContext = applicationContext.getValidationContext(); - if (log.isDebugEnabled()) { - log.debug("Set referentiel list [" + getBeanType().getSimpleName() + "] in validation context : " + data.size()); - } - validationContext.setEditingReferentielList(data); - } - -// @Override -// public boolean closeUI() throws Exception { -// return super.closeUI(); -// } - - public final void createUI() { - - ContentReferenceUI<E> ui = getUi(); - - // force le mode creation - getModel().setMode(ContentMode.CREATE); - - if (log.isDebugEnabled()) { - log.debug("Will create new entity [" + getModel().getBeanType() + "]"); - } - - copyIntoBean(null, getBean()); - - // on demarre l'edition - ui.startEdit(null); - } - - public void modifyUI() { - - ContentReferenceUIModel<E> model = getModel(); - if (model.getMode() != ContentMode.READ) { - - // force le mode mise a jour - model.setMode(ContentMode.UPDATE); - } - - copyIntoBean(model.getSelectedBean(), getBean()); - - getUi().startEdit(null); - } - - @Override - public void stopEditUI() { - super.stopEditUI(); - - ContentReferenceUI<E> ui = getUi(); - ContentReferenceUIModel<E> model = getModel(); - - if (model.getMode() != ContentMode.READ) { - - // on retourne en mode mise a jour sur la liste - model.setMode(ContentMode.UPDATE); - removeAllMessages(ui); - addInfoMessage(t("observe.message.referentiel.editable")); - } - - updateUiWithReferenceSetsFromModel(); - - } - - @Override - public final void resetEditUI() { - - ContentMode mode = getModel().getMode(); - super.resetEditUI(); - if (mode == ContentMode.CREATE) { - createUI(); - } else { - modifyUI(); - } - } - - public void backToList() { - ContentReferenceUIModel<E> model = getModel(); - if (!model.isModified() || checkEdit(getUi())) { - getUi().stopEdit(); - - // then resynch the selected bean to edit bean (used for example to delete)... - // repush selected bean to bean - - copyIntoBean(model.getSelectedBean(), getBean()); - } - } - - @Override - protected boolean doSave(E bean) throws Exception { - - ContentReferenceUIModel<E> model = getModel(); - - if (bean.getId() == null) { - - if (log.isInfoEnabled()) { - log.info("Create referentiel " + bean); - } - - SaveResultDto saveResult = getReferentialService().save(bean); - - saveResult.toDto(bean); - - if (bean instanceof ProgramDto) { - - // add the program in tree - ObserveTreeHelper treeHelper = getTreeHelper(getUi()); - ReferentialReference<ProgramDto> reference = ObserveSwingApplicationContext.get().getReferenceBinderEngine().transformReferentialDtoToReference(getDecoratorService().getReferentialLocale(), (ProgramDto) bean); - treeHelper.addProgram(reference); - - } - - // on met a jour le referentiel dans le cache et le model - ReferenceSetRequestDefinitions requestDefinition = ReferenceSetRequestDefinitions.get(getBeanType()); - loadReferentialReferenceSetsInModel(requestDefinition.name()); - - return true; - } - - if (log.isInfoEnabled()) { - log.info("Will update exisintg entity : " + bean.getId()); - } - // le bean original - E oldBean = model.getSelectedBean(); - - if (oldBean != null && - oldBean.getStatus() == ReferenceStatus.enabled && - bean.getStatus() == ReferenceStatus.disabled) { - - // l'entite a ete desactive - // on recherche les objets utilisant cette entitee - // on indique a l'utilisateur ce changement - if (log.isDebugEnabled()) { - log.debug("entity status was desactivated, looking " + - "for usage"); - } - - ReferenceMap usages = getReferentialService().findAllUsages(bean); - - if (usages.isEmpty()) { - if (log.isInfoEnabled()) { - log.info("No usage found, no warning to display"); - } - } else { - // some usages were found - boolean willsave = showUsagesForDesactivated(getUi(), bean, - usages); - if (!willsave) { - if (log.isDebugEnabled()) { - log.debug("User refuses to continue, skip " + - "saving..."); - } - return false; - } - } - } - - - // sauvegarde du bean d'edition dans le bean de la base - SaveResultDto saveResult = getReferentialService().save(bean); - saveResult.toDto(bean); - - if (bean instanceof ProgramDto) { - - // update the program in tree - ObserveTreeHelper treeHelper = getTreeHelper(getUi()); - treeHelper.updateProgram((ProgramDto) bean); - } - - // on met a jour le referentiel dans le cache et le model - ReferenceSetRequestDefinitions requestDefinition = ReferenceSetRequestDefinitions.get(getBeanType()); - loadReferentialReferenceSetsInModel(requestDefinition.name()); - - return true; - } - - @Override - protected boolean doDelete(E bean) { - - ContentReferenceUI<E> ui = getUi(); - ContentReferenceUIModel<E> model = getModel(); - - if (log.isInfoEnabled()) { - log.info("entity to be deleted, looking for usage"); - } - - // recherche des utilisation du bean dans la base - ReferenceMap usages = getReferentialService().findAllUsages(bean); - - if (MapUtils.isEmpty(usages)) { - if (log.isDebugEnabled()) { - log.debug("No usage found, no warning to display"); - } - } else { - - // some usages were found - if (log.isDebugEnabled()) { - log.debug("can not delete referentiel entity (found usages)"); - } - showUsagesForDelete(ui, bean, usages); - return false; - } - - if (!UIHelper.confirmForEntityDelete(ui, model.getBeanType(), bean)) { - return false; - } - - String beanId = bean.getId(); - getReferentialService().delete(getBeanType(), beanId); - - return true; - } - - @Override - protected void afterDelete() { - E bean = getBean(); - if (bean instanceof ProgramDto) { - - // remove the program in tree - ObserveTreeHelper treeHelper = getTreeHelper(getUi()); - treeHelper.removeProgram(bean.getId()); - } - - // on met a jour le referentiel dans le cache et le model - ReferenceSetRequestDefinitions requestDefinition = ReferenceSetRequestDefinitions.get(getBeanType()); - loadReferentialReferenceSetsInModel(requestDefinition.name()); - - //getModel().setSelectedBean(null); - super.afterDelete(); - } - - protected void afterSave(boolean refresh) { - super.afterSave(refresh); - getUi().stopEdit(); - } - - @Override - protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { - // No filter for referantial screen - return incomingReferences; - } - - public boolean canSeeI18nTable(E bean) { - return bean instanceof I18nReferentialDto || bean instanceof VesselSizeCategoryDto; - } - - public String updateView(boolean editing) { - if (log.isDebugEnabled()) { - log.debug("Editing has changed : " + editing); - } - return editing ? ContentReferenceUI.DETAIL_VIEW : ContentReferenceUI.LIST_VIEW; - } - - protected void copyIntoBean(E source, E target) { - Binder<E, E> binder = BinderFactory.newBinder(getBeanType()); - binder.copy(source, target); - } - - protected ReferentialService getReferentialService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newReferentialService(); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ContentReferenceUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ContentReferenceUIModel.java deleted file mode 100644 index 0023805..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ContentReferenceUIModel.java +++ /dev/null @@ -1,259 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.ref; - -import fr.ird.observe.services.dto.referential.I18nReferentialDto; -import fr.ird.observe.services.dto.referential.LengthWeightParameterDto; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.ui.content.ContentUIModel; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Le modèle pour un écran d'édition du référentiel. - * - * @author Tony Chemit - chemit@codelutin.com - * @since .14 - */ -public abstract class ContentReferenceUIModel<E extends ReferentialDto> extends ContentUIModel<E> { - - public static final String PROPERTY_EMPTY = "empty"; - - public static final String PROPERTY_SELECTED_BEAN = "selectedBean"; - - public static final String SUFFIX_TEXT = ".text"; - - public static final String SUFFIX_MODEL = ".model"; - - public static final String SUFFIX_SELECTED_INDEX = ".selectedIndex"; - - public static final String SUFFIX_SELECTED_ITEM = ".selectedItem"; - - public static final String SUFFIX_SELECTED = ".selected"; - - public static final String SUFFIX_DATE = ".date"; - - /** liste des bindings present sur tous les ecrans du referentiel */ - protected final static String[] DEFAULT_DATABINDING = { - ReferentialDto.PROPERTY_CODE + SUFFIX_TEXT, - ReferentialDto.PROPERTY_URI + SUFFIX_TEXT, - ReferentialDto.PROPERTY_STATUS + SUFFIX_SELECTED_INDEX, - ReferentialDto.PROPERTY_NEED_COMMENT + SUFFIX_SELECTED - }; - - /** liste des proprietes presents sur les entites parametrageLengthWeightAble */ - protected final static String[] DEFAULT_LENGTH_WEIGHT_PARAMETER_ABLE_DATABINDING = { - LengthWeightParameterDto.PROPERTY_START_DATE + SUFFIX_DATE, - LengthWeightParameterDto.PROPERTY_END_DATE + SUFFIX_DATE, - LengthWeightParameterDto.PROPERTY_SPECIES + SUFFIX_SELECTED_ITEM, - LengthWeightParameterDto.PROPERTY_OCEAN + SUFFIX_SELECTED_ITEM, - LengthWeightParameterDto.PROPERTY_SEX + SUFFIX_SELECTED_INDEX, - LengthWeightParameterDto.PROPERTY_LENGTH_WEIGHT_FORMULA + SUFFIX_TEXT, - LengthWeightParameterDto.PROPERTY_WEIGHT_LENGTH_FORMULA + SUFFIX_TEXT, - LengthWeightParameterDto.PROPERTY_COEFFICIENTS + SUFFIX_TEXT, - LengthWeightParameterDto.PROPERTY_MEAN_LENGTH + SUFFIX_MODEL, - LengthWeightParameterDto.PROPERTY_MEAN_WEIGHT + SUFFIX_MODEL - }; - - /** liste des bindings presents sur les entites i18n */ - protected final static String[] DEFAULT_I18N_DATABINDING = { - I18nReferentialDto.PROPERTY_LABEL1 + SUFFIX_TEXT, - I18nReferentialDto.PROPERTY_LABEL2 + SUFFIX_TEXT, - I18nReferentialDto.PROPERTY_LABEL3 + SUFFIX_TEXT, - I18nReferentialDto.PROPERTY_LABEL4 + SUFFIX_TEXT, - I18nReferentialDto.PROPERTY_LABEL5 + SUFFIX_TEXT, - I18nReferentialDto.PROPERTY_LABEL6 + SUFFIX_TEXT, - I18nReferentialDto.PROPERTY_LABEL7 + SUFFIX_TEXT, - I18nReferentialDto.PROPERTY_LABEL8 + SUFFIX_TEXT - }; - - /** liste des proprietes present sur tous les ecrans du referentiel */ - protected final static String[] DEFAULT_PROPERTIES = { - ReferentialDto.PROPERTY_CODE, - ReferentialDto.PROPERTY_URI, - ReferentialDto.PROPERTY_STATUS, - ReferentialDto.PROPERTY_NEED_COMMENT - }; - - /** liste des proprietes presents sur les entites taillePoidsAble */ - protected final static String[] DEFAULT_PARAMETRAGE_TAILLE_POIDS_ABLE_PROPERTIES = { - LengthWeightParameterDto.PROPERTY_START_DATE, - LengthWeightParameterDto.PROPERTY_END_DATE, - LengthWeightParameterDto.PROPERTY_OCEAN, - LengthWeightParameterDto.PROPERTY_SPECIES, - LengthWeightParameterDto.PROPERTY_SEX, - LengthWeightParameterDto.PROPERTY_LENGTH_WEIGHT_FORMULA, - LengthWeightParameterDto.PROPERTY_WEIGHT_LENGTH_FORMULA, - LengthWeightParameterDto.PROPERTY_COEFFICIENTS, - LengthWeightParameterDto.PROPERTY_MEAN_LENGTH, - LengthWeightParameterDto.PROPERTY_MEAN_WEIGHT - }; - - /** liste des proprietes presents sur les entites i18n */ - protected final static String[] DEFAULT_I18N_PROPERTIES = { - I18nReferentialDto.PROPERTY_LABEL1, - I18nReferentialDto.PROPERTY_LABEL2, - I18nReferentialDto.PROPERTY_LABEL3, - I18nReferentialDto.PROPERTY_LABEL4, - I18nReferentialDto.PROPERTY_LABEL5, - I18nReferentialDto.PROPERTY_LABEL6, - I18nReferentialDto.PROPERTY_LABEL7, - I18nReferentialDto.PROPERTY_LABEL8 - }; - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(ContentReferenceUIModel.class); - - /** la liste des propriétés du bean a charger */ - protected final String[] properties; - - /** la liste des propriétés faisant partie de la clef metier */ - protected final String[] naturalIds; - - /** la liste des bindings à activer lors de l'ouverture de l'ui */ - protected final String[] dataBinding; - - protected E selectedBean; - - protected ContentReferenceUIModel(Class<E> beanType) { - - this(beanType, null, null, null); - - } - - protected ContentReferenceUIModel(Class<E> beanType, - String[] extraProperties, - String[] extraBindings) { - - this(beanType, extraProperties, null, extraBindings); - - } - - protected ContentReferenceUIModel(Class<E> beanType, - String[] extraProperties, - String[] naturalIds, - String[] extraBindings) { - super(beanType); - - boolean useDefault = naturalIds == null; - - // la clef naturelle par defaut est la premiere des properties - this.naturalIds = useDefault ? new String[]{DEFAULT_PROPERTIES[0]} : naturalIds; - - List<String> properties = buildProperties(useDefault, extraProperties); - this.properties = properties.toArray(new String[properties.size()]); - - List<String> bindings = buildDataBindings(useDefault, extraBindings); - this.dataBinding = bindings.toArray(new String[bindings.size()]); - - - } - - public String[] getNaturalIds() { - return naturalIds; - } - - public String[] getDataBinding() { - return dataBinding; - } - - public E getSelectedBean() { - return selectedBean; - } - - public void setSelectedBean(E selectedBean) { - Object oldvalue = this.selectedBean; - this.selectedBean = selectedBean; - firePropertyChange(PROPERTY_SELECTED_BEAN, oldvalue, selectedBean); - } - - /** - * construction de la liste des propriétés a binder pour une entite. - * - * @param usedefault un drapeau pour savoir si on doit conserver la premiere valeur par defaut - * @param properties les propriétés supplémentaires a ajouter en plus de - * celles communes - * @return la liste des toutes les proprietes utilises sur l'entite edite dans l'ui - */ - protected final List<String> buildProperties(boolean usedefault, String[] properties) { - - List<String> result = new ArrayList<>(); - result.addAll(Arrays.asList(DEFAULT_PROPERTIES)); - if (properties != null) { - result.addAll(Arrays.asList(properties)); - } - Class<E> beanType = getBeanType(); - - if (I18nReferentialDto.class.isAssignableFrom(beanType)) { - result.addAll(Arrays.asList(DEFAULT_I18N_PROPERTIES)); - } - if (LengthWeightParameterDto.class.isAssignableFrom(beanType)) { - result.addAll(Arrays.asList(DEFAULT_PARAMETRAGE_TAILLE_POIDS_ABLE_PROPERTIES)); - } - if (!usedefault) { - - // on supprime le premiere valeur - result.remove(DEFAULT_PROPERTIES[0]); - } - return result; - - } - - /** - * construction de la liste des databindings utiliser pour une entite. - * - * @param usedefault un drapeau pour savoir si on doit conserver la premiere valeur par defaut - * @param dataBinding les bindings supplémentaires a utiliser en plus de - * ceux communs - * @return la liste de tous les databindings utilises sur l'entite edite dans l'ui - */ - protected final List<String> buildDataBindings(boolean usedefault, String[] dataBinding) { - - List<String> result = new ArrayList<>(); - result.addAll(Arrays.asList(DEFAULT_DATABINDING)); - if (dataBinding != null) { - result.addAll(Arrays.asList(dataBinding)); - } - Class<E> beanType = getBeanType(); - - if (I18nReferentialDto.class.isAssignableFrom(beanType)) { - result.addAll(Arrays.asList(DEFAULT_I18N_DATABINDING)); - } - if (LengthWeightParameterDto.class.isAssignableFrom(beanType)) { - result.addAll(Arrays.asList(DEFAULT_LENGTH_WEIGHT_PARAMETER_ABLE_DATABINDING)); - } - if (!usedefault) { - - // on supprime le premier binding - result.remove(DEFAULT_DATABINDING[0]); - } - return result; - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ReferenceHomeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ReferenceHomeUI.jaxx deleted file mode 100644 index 39417f4..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ReferenceHomeUI.jaxx +++ /dev/null @@ -1,46 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ContentUI - superGenericType='ProgramDto' - - > - - <import> - fr.ird.observe.services.dto.referential.ProgramDto - fr.ird.observe.ui.content.ContentMode - </import> - - <ReferenceHomeUIModel id='model'/> - - <ReferenceHomeUIHandler id='handler' constructorParams='this'/> - - - <Table id='body' fill='both' weighty="1"> - <row weighty="1" weightx="1"> - <cell> - <JLabel id='homeLabel'/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ReferenceHomeUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ReferenceHomeUIHandler.java deleted file mode 100644 index e8b2e85..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ReferenceHomeUIHandler.java +++ /dev/null @@ -1,53 +0,0 @@ -package fr.ird.observe.ui.content.ref; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.ContentUIHandler; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ReferenceHomeUIHandler extends ContentUIHandler<ProgramDto> { - - public ReferenceHomeUIHandler(ReferenceHomeUI ui) { - super(ui, null, null); - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - return null; - } - - @Override - protected boolean computeCanWrite(ObserveSwingDataSource source) { - return source.canWriteReferential(); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ReferenceHomeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ReferenceHomeUIModel.java deleted file mode 100644 index 1233147..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ReferenceHomeUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.ui.content.ContentUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ReferenceHomeUIModel extends ContentUIModel<ProgramDto> { - - private static final long serialVersionUID = 1L; - - public ReferenceHomeUIModel() { - super(ProgramDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ReferentialContentUIInitializer.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ReferentialContentUIInitializer.java deleted file mode 100644 index 88f9116..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/ReferentialContentUIInitializer.java +++ /dev/null @@ -1,57 +0,0 @@ -package fr.ird.observe.ui.content.ref; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.ui.content.ContentUIInitializer; - -/** - * Created on 11/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.9 - */ -public class ReferentialContentUIInitializer<E extends ReferentialDto, UI extends ContentReferenceUI<E>> extends ContentUIInitializer<E, UI> { - -// /** Logger. */ -// private static final Log log = LogFactory.getLog(ReferentialContentUIInitializer.class); - - public ReferentialContentUIInitializer(UI ui) { - super(ui); - } - - @Override - protected void initBlockLayerUI(String... doNotBlockComponentIds) { - - super.initBlockLayerUI(doNotBlockComponentIds); - - //tchemit-2014-12-29 We should use a spearate list for this, but there is no collision possible... - ui.getEditKeyTableLayerUI().setAcceptedComponentNames(doNotBlockComponentIds); - - } - -// protected Decorator<ReferenceDto> getDecorator(Class<? extends ReferentialDto> dtoClass) { -// return ObserveSwingApplicationContext.get().getDecorator(ReferenceDto.class, dtoClass.getSimpleName()); -// } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/UniqueKeyTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/UniqueKeyTableModel.java deleted file mode 100644 index 8775dd5..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/UniqueKeyTableModel.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.ref; - -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.ObserveSwingApplicationContext; - -import javax.swing.table.AbstractTableModel; -import java.util.List; - -import static org.nuiton.i18n.I18n.t; - -/** - * Un modèle de tableau pour afficher les clef metier des objets du - * référentiel. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.2 - */ -public class UniqueKeyTableModel extends AbstractTableModel { - - private static final long serialVersionUID = 1L; - - protected final String[] columns; - - protected final List<Object[]> datas; - - protected transient DecoratorService decoratorService; - - public UniqueKeyTableModel(String[] columns, List<Object[]> datas) { - this.columns = columns; - this.datas = datas; - } - - public DecoratorService getDecoratorService() { - if (decoratorService == null) { - decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); - } - return decoratorService; - } - - @Override - public int getRowCount() { - return datas.size(); - } - - @Override - public int getColumnCount() { - return columns.length; - } - - @Override - public Object getValueAt(int rowIndex, int columnIndex) { - return datas.get(rowIndex)[columnIndex]; - } - - @Override - public boolean isCellEditable(int rowIndex, int columnIndex) { - // tableau non editable - return false; - } - - @Override - public String getColumnName(int column) { - String property = columns[column]; - return t(DecoratorService.getPropertyLabel(property)); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/CountryUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/CountryUI.jaxx deleted file mode 100644 index 0840f08..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/CountryUI.jaxx +++ /dev/null @@ -1,185 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='CountryDto' - contentTitle='{n("observe.content.title.country")}' - listText='{n("observe.content.list.country")}' - createToolTip='{n("observe.content.action.country.create.tip")}' - detailToolTip='{n("observe.content.action.country.detail.tip")}' - modifyToolTip='{n("observe.content.action.country.modify.tip")}' - deleteToolTip='{n("observe.content.action.country.delete.tip")}' - saveToolTip='{n("observe.content.action.country.save.tip")}' - - > - - <style source="ReferenceEntity.jcss"/> - <style source="I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.CountryDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.CountryDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <CountryUIModel id='model'/> - - <!-- edit bean --> - <CountryDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- iso2Code --> - <row> - <cell anchor="west"> - <JLabel id='iso2CodeLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='iso2Code' - onKeyReleased='getBean().setIso2Code(iso2Code.getText())'/> - </cell> - </row> - - <!-- iso3Code --> - <row> - <cell anchor="west"> - <JLabel id='iso3CodeLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='iso3Code' - onKeyReleased='getBean().setIso3Code(iso3Code.getText())'/> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/CountryUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/CountryUIModel.java deleted file mode 100644 index dca104d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/CountryUIModel.java +++ /dev/null @@ -1,45 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.CountryDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/27/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class CountryUIModel extends ContentReferenceUIModel<CountryDto> { - - private static final long serialVersionUID = 1L; - - public CountryUIModel() { - super(CountryDto.class, - new String[]{CountryDto.PROPERTY_ISO2_CODE, CountryDto.PROPERTY_ISO3_CODE}, - new String[]{CountryUI.BINDING_ISO2_CODE_TEXT, CountryUI.BINDING_ISO3_CODE_TEXT} - ); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/FpaZoneUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/FpaZoneUI.jaxx deleted file mode 100644 index d489fd9..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/FpaZoneUI.jaxx +++ /dev/null @@ -1,181 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='FpaZoneDto' - contentTitle='{n("observe.content.title.fpaZones")}' - listText='{n("observe.content.list.fpaZone")}' - createToolTip='{n("observe.content.action.fpaZone.create.tip")}' - detailToolTip='{n("observe.content.action.fpaZone.detail.tip")}' - modifyToolTip='{n("observe.content.action.fpaZone.modify.tip")}' - deleteToolTip='{n("observe.content.action.fpaZone.delete.tip")}' - saveToolTip='{n("observe.content.action.fpaZone.save.tip")}' - - > - - <style source="ReferenceEntity.jcss"/> - <style source="I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.FpaZoneDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - org.jdesktop.swingx.JXDatePicker - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.FpaZoneDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <FpaZoneUIModel id='model'/> - - <!-- edit bean --> - <FpaZoneDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id="uriLabel"/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - - <!-- date debut - fin de validite --> - <row> - <cell anchor='west'> - <JLabel id='startDateFinValiditeLabel'/> - </cell> - <cell anchor='west' weightx="1" fill="both"> - <JPanel layout='{new GridLayout()}'> - <JXDatePicker id='startDate' - onActionPerformed='getBean().setStartDate(startDate.getDate())'/> - <JXDatePicker id='endDate' - onActionPerformed='getBean().setEndDate(endDate.getDate())'/> - </JPanel> - </cell> - </row> - </Table> - - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/FpaZoneUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/FpaZoneUIModel.java deleted file mode 100644 index a032e48..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/FpaZoneUIModel.java +++ /dev/null @@ -1,45 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.FpaZoneDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/27/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class FpaZoneUIModel extends ContentReferenceUIModel<FpaZoneDto> { - - private static final long serialVersionUID = 1L; - - public FpaZoneUIModel() { - super(FpaZoneDto.class, - new String[]{FpaZoneDto.PROPERTY_START_DATE, FpaZoneDto.PROPERTY_END_DATE}, - new String[]{FpaZoneUI.BINDING_START_DATE_DATE, FpaZoneUI.BINDING_END_DATE_DATE} - ); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearCaracteristicTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearCaracteristicTypeUI.jaxx deleted file mode 100644 index ee924f1..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearCaracteristicTypeUI.jaxx +++ /dev/null @@ -1,162 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='GearCaracteristicTypeDto' - contentTitle='{n("observe.content.title.gearCaracteristicTypes")}' - listText='{n("observe.content.list.gearCaracteristicType")}' - createToolTip='{n("observe.content.action.gearCaracteristicType.create.tip")}' - detailToolTip='{n("observe.content.action.gearCaracteristicType.detail.tip")}' - modifyToolTip='{n("observe.content.action.gearCaracteristicType.modify.tip")}' - deleteToolTip='{n("observe.content.action.gearCaracteristicType.delete.tip")}' - saveToolTip='{n("observe.content.action.gearCaracteristicType.save.tip")}'> - - <style source="ReferenceEntity.jcss"/> - <style source="I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.GearCaracteristicTypeDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.GearCaracteristicTypeDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <GearCaracteristicTypeUIModel id='model'/> - - <!-- edit bean --> - <GearCaracteristicTypeDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id="uriLabel"/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearCaracteristicTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearCaracteristicTypeUIModel.java deleted file mode 100644 index 876ff14..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearCaracteristicTypeUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.GearCaracteristicTypeDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 3/23/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.16 - */ -public class GearCaracteristicTypeUIModel extends ContentReferenceUIModel<GearCaracteristicTypeDto> { - - private static final long serialVersionUID = 1L; - - public GearCaracteristicTypeUIModel() { - super(GearCaracteristicTypeDto.class); - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearCaracteristicUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearCaracteristicUI.jaxx deleted file mode 100644 index d9163ad..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearCaracteristicUI.jaxx +++ /dev/null @@ -1,187 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='GearCaracteristicDto' - contentTitle='{n("observe.content.title.gearCaracteristics")}' - listText='{n("observe.content.list.gearCaracteristic")}' - createToolTip='{n("observe.content.action.gearCaracteristic.create.tip")}' - detailToolTip='{n("observe.content.action.gearCaracteristic.detail.tip")}' - modifyToolTip='{n("observe.content.action.gearCaracteristic.modify.tip")}' - deleteToolTip='{n("observe.content.action.gearCaracteristic.delete.tip")}' - saveToolTip='{n("observe.content.action.gearCaracteristic.save.tip")}'> - - <style source="ReferenceEntity.jcss"/> - <style source="I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.GearCaracteristicDto - fr.ird.observe.services.dto.referential.GearCaracteristicTypeDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - jaxx.runtime.swing.editor.bean.BeanComboBox - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.GearCaracteristicDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <GearCaracteristicUIModel id='model'/> - - <!-- edit bean --> - <GearCaracteristicDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id="uriLabel"/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - - <!-- gearCaracteristicType --> - <row> - <cell anchor='west'> - <JLabel id='gearCaracteristicTypeLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='gearCaracteristicType' constructorParams='this' genericType='ReferentialReference<GearCaracteristicTypeDto>' _entityClass='GearCaracteristicTypeDto.class'/> - </cell> - </row> - - <!-- unit --> - <row> - <cell anchor='west'> - <JLabel id='unitLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='unit' onKeyReleased='getBean().setUnit(unit.getText())'/> - </cell> - </row> - - </Table> - - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearCaracteristicUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearCaracteristicUIModel.java deleted file mode 100644 index 665350e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearCaracteristicUIModel.java +++ /dev/null @@ -1,49 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.GearCaracteristicDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 3/23/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.16 - */ -public class GearCaracteristicUIModel extends ContentReferenceUIModel<GearCaracteristicDto> { - - private static final long serialVersionUID = 1L; - - public GearCaracteristicUIModel() { - super(GearCaracteristicDto.class, - new String[]{ - GearCaracteristicDto.PROPERTY_GEAR_CARACTERISTIC_TYPE, - GearCaracteristicDto.PROPERTY_UNIT, - }, - new String[]{GearCaracteristicDto.PROPERTY_GEAR_CARACTERISTIC_TYPE + SUFFIX_SELECTED_ITEM, - GearCaracteristicDto.PROPERTY_UNIT + SUFFIX_TEXT} - ); - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearUI.jaxx deleted file mode 100644 index cae8535..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearUI.jaxx +++ /dev/null @@ -1,200 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='GearDto' - contentTitle='{n("observe.content.title.gears")}' - listText='{n("observe.content.list.gear")}' - createToolTip='{n("observe.content.action.gear.create.tip")}' - detailToolTip='{n("observe.content.action.gear.detail.tip")}' - modifyToolTip='{n("observe.content.action.gear.modify.tip")}' - deleteToolTip='{n("observe.content.action.gear.delete.tip")}' - saveToolTip='{n("observe.content.action.gear.save.tip")}'> - - <style source="ReferenceEntity.jcss"/> - <style source="I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.GearDto - fr.ird.observe.services.dto.referential.GearCaracteristicDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - org.nuiton.jaxx.widgets.select.FilterableDoubleList - - java.util.Collection - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.GearDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <GearUIModel id='model'/> - - <!-- edit bean --> - <GearDto id='bean'/> - - <!-- handler --> - <GearUIHandler id='handler' constructorParams="this"/> - - <Table id="editView" insets="0" fill="both"> - <row> - <cell anchor="north" weightx="1"> - <JTabbedPane id='tabPane'> - <tab id='generalTab'> - <Table fill="both"> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - - <row> - <cell columns="2"> - <Table id='editI18nTable2'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> - </cell> - </row> - <row> - <cell columns="2" weighty="1"> - <JLabel/> - </cell> - </row> - </Table> - </tab> - - <tab id='gearCaracteristicTab'> - <Table fill="both" weightx="1"> - <!-- gearCaracteristic --> - <row> - <cell weightx="1" weighty="1"> - <JScrollPane id='gearCaracteristicPane' layout='{new GridLayout(1,1)}'> - <FilterableDoubleList id='gearCaracteristic' - genericType='ReferentialReference<GearCaracteristicDto>' - _entityClass='GearCaracteristicDto.class'/> - </JScrollPane> - </cell> - </row> - </Table> - </tab> - </JTabbedPane> - </cell> - </row> - <row> - <cell columns="2" weighty="1"> - <JLabel/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearUIHandler.java deleted file mode 100644 index 599803b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearUIHandler.java +++ /dev/null @@ -1,102 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.GearDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.content.ref.ContentReferenceUI; -import fr.ird.observe.ui.content.ref.ContentReferenceUIHandler; -import jaxx.runtime.validator.swing.SwingValidatorMessage; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.event.TableModelListener; -import java.util.HashSet; -import java.util.Set; - -/** - * Created on 3/23/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.16 - */ -public class GearUIHandler extends ContentReferenceUIHandler<GearDto> { - - // Compute valid state of tab from the error table - protected final TableModelListener computeTabValidStateListener; - - public GearUIHandler(ContentReferenceUI<GearDto> ui) { - super(ui); - computeTabValidStateListener = e -> { - - SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); - computeTabValidState(source); - - }; - } - - @Override - public void initUI() { - - super.initUI(); - - // To be sure always remove listener (could prevent some leaks) - getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); - // listen messages to see if required to add - getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); - - } - - @Override - public void selectBean(ReferentialReference<GearDto> selectedBean) { - - super.selectBean(selectedBean); - - SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); - computeTabValidState(errorTableModel); - - ((GearUI) getUi()).getTabPane().setSelectedIndex(0); - - } - - protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { - - Set<String> errorProperties = new HashSet<>(); - int rowCount = errorTableModel.getRowCount(); - for (int i = 0; i < rowCount; i++) { - - SwingValidatorMessage row = errorTableModel.getRow(i); - if (NuitonValidatorScope.ERROR.equals(row.getScope())) { - errorProperties.add(row.getField()); - } - } - - boolean generalTabValid = !errorProperties.removeAll(GearUIModel.GENERAL_TAB_PROPERTIES); - boolean gearCaracteristicTabValid = !errorProperties.removeAll(GearUIModel.GEAR_CARACTERISTIC_TAB_PROPERTIES); - - GearUIModel model = (GearUIModel) getModel(); - model.setGeneralTabValid(generalTabValid); - model.setGearCaracteristicTabValid(gearCaracteristicTabValid); - - } -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearUIModel.java deleted file mode 100644 index c0f5974..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/GearUIModel.java +++ /dev/null @@ -1,92 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.ImmutableSet; -import fr.ird.observe.services.dto.referential.GearDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -import java.util.Set; - -/** - * Created on 3/23/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.16 - */ -public class GearUIModel extends ContentReferenceUIModel<GearDto> { - - private static final long serialVersionUID = 1L; - - public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; - - public static final String PROPERTY_GEAR_CARACTERISTIC_TAB_VALID = "gearCaracteristicTabValid"; - - public static final Set<String> GENERAL_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(GearDto.PROPERTY_URI, - GearDto.PROPERTY_CODE, - GearDto.PROPERTY_STATUS, - GearDto.PROPERTY_NEED_COMMENT, - GearDto.PROPERTY_LABEL1, - GearDto.PROPERTY_LABEL2, - GearDto.PROPERTY_LABEL3, - GearDto.PROPERTY_LABEL4, - GearDto.PROPERTY_LABEL5, - GearDto.PROPERTY_LABEL6, - GearDto.PROPERTY_LABEL7, - GearDto.PROPERTY_LABEL8).build(); - - public static final Set<String> GEAR_CARACTERISTIC_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(GearDto.PROPERTY_GEAR_CARACTERISTIC).build(); - - protected boolean generalTabValid; - - protected boolean gearCaracteristicTabValid; - - public GearUIModel() { - super(GearDto.class, - new String[]{GearDto.PROPERTY_GEAR_CARACTERISTIC}, - new String[]{GearDto.PROPERTY_GEAR_CARACTERISTIC + SUFFIX_SELECTED}); - } - - public boolean isGearCaracteristicTabValid() { - return gearCaracteristicTabValid; - } - - public void setGearCaracteristicTabValid(boolean gearCaracteristicTabValid) { - Object oldValue = isGearCaracteristicTabValid(); - this.gearCaracteristicTabValid = gearCaracteristicTabValid; - firePropertyChange(PROPERTY_GEAR_CARACTERISTIC_TAB_VALID, oldValue, gearCaracteristicTabValid); - } - - public boolean isGeneralTabValid() { - return generalTabValid; - } - - public void setGeneralTabValid(boolean generalTabValid) { - Object oldValue = isGeneralTabValid(); - this.generalTabValid = generalTabValid; - firePropertyChange(PROPERTY_GENERAL_TAB_VALID, oldValue, generalTabValid); - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/HarbourUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/HarbourUI.jaxx deleted file mode 100644 index 5709959..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/HarbourUI.jaxx +++ /dev/null @@ -1,149 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='HarbourDto' - contentTitle='{n("observe.content.title.harbours")}' - listText='{n("observe.content.list.harbour")}' - createToolTip='{n("observe.content.action.harbour.create.tip")}' - detailToolTip='{n("observe.content.action.harbour.detail.tip")}' - modifyToolTip='{n("observe.content.action.harbour.modify.tip")}' - deleteToolTip='{n("observe.content.action.harbour.delete.tip")}' - saveToolTip='{n("observe.content.action.harbour.save.tip")}' - - > - - <style source="ReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.HarbourDto - fr.ird.observe.services.dto.referential.CountryDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - jaxx.runtime.swing.editor.bean.BeanComboBox - - org.nuiton.jaxx.widgets.gis.absolute.CoordinatesEditor - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' context='ui-create' - beanClass='fr.ird.observe.services.dto.referential.HarbourDto' - errorTableModel='{getErrorTableModel()}'> - - <field name='longitude' component='coordinates'/> - <field name='latitude' component='coordinates'/> - <field name='quadrant' component='coordinates'/> - <field name='name' component='harbourName'/> - - </BeanValidator> - - <!-- model --> - <HarbourUIModel id='model'/> - - <!-- edit bean --> - <HarbourDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- locode --> - <row> - <cell anchor='west'> - <JLabel id='locodeLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='locode' onKeyReleased='getBean().setLocode(locode.getText())'/> - </cell> - </row> - - <!-- name --> - <row> - <cell anchor='west'> - <JLabel id='harbourNameLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='harbourName' onKeyReleased='getBean().setName(harbourName.getText())'/> - </cell> - </row> - - <!-- country --> - <row> - <cell anchor='west'> - <JLabel id='countryLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='country' constructorParams='this' genericType='ReferentialReference<CountryDto>' _entityClass='CountryDto.class'/> - </cell> - </row> - - <!-- coordinates --> - <row> - <cell anchor='west'> - <JLabel id='coordinatesLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <CoordinatesEditor id='coordinates' constructorParams='this'/> - </cell> - - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/HarbourUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/HarbourUIModel.java deleted file mode 100644 index b387c93..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/HarbourUIModel.java +++ /dev/null @@ -1,55 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.HarbourDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 1/7/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.11 - */ -public class HarbourUIModel extends ContentReferenceUIModel<HarbourDto> { - - private static final long serialVersionUID = 1L; - - public HarbourUIModel() { - super(HarbourDto.class, - new String[]{HarbourDto.PROPERTY_NAME, - HarbourDto.PROPERTY_COUNTRY, - HarbourDto.PROPERTY_LOCODE, - HarbourDto.PROPERTY_LATITUDE, - HarbourDto.PROPERTY_LONGITUDE, - HarbourDto.PROPERTY_QUADRANT}, - new String[]{HarbourUI.BINDING_COUNTRY_SELECTED_ITEM, - HarbourUI.BINDING_HARBOUR_NAME_TEXT, - HarbourUI.BINDING_LOCODE_TEXT, - HarbourUI.BINDING_COORDINATES_LATITUDE, - HarbourUI.BINDING_COORDINATES_LONGITUDE, - HarbourUI.BINDING_COORDINATES_QUADRANT} - ); - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/LengthWeightParameterUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/LengthWeightParameterUI.jaxx deleted file mode 100644 index 356ffb0..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/LengthWeightParameterUI.jaxx +++ /dev/null @@ -1,300 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='LengthWeightParameterDto' - contentTitle='{n("observe.content.title.lengthWeightParameters")}' - listText='{n("observe.content.list.lengthWeightParameter")}' - createToolTip='{n("observe.content.action.lengthWeightParameter.create.tip")}' - detailToolTip='{n("observe.content.action.lengthWeightParameter.detail.tip")}' - modifyToolTip='{n("observe.content.action.lengthWeightParameter.modify.tip")}' - deleteToolTip='{n("observe.content.action.lengthWeightParameter.delete.tip")}' - saveToolTip='{n("observe.content.action.lengthWeightParameter.save.tip")}' - - > - - <style source="ReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.SexDto - fr.ird.observe.services.dto.referential.SpeciesDto - fr.ird.observe.services.dto.referential.OceanDto - fr.ird.observe.services.dto.referential.LengthWeightParameterDto - fr.ird.observe.ui.UIHelper - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - org.jdesktop.swingx.JXDatePicker - - javax.swing.JScrollPane - javax.swing.JTable - javax.swing.table.TableCellRenderer - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.LengthWeightParameterDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <LengthWeightParameterUIModel id='model'/> - - <!-- handler --> - <LengthWeightParameterUIHandler id='handler' constructorParams="this"/> - - <!-- edit bean --> - <LengthWeightParameterDto id='bean'/> - - <script><![CDATA[ -@Override -public void decorateUniqueKeyTable(JTable table, - TableCellRenderer renderer, - JScrollPane pane) { - - UIHelper.fixTableColumnWidth(table, 0, 250); - UIHelper.fixTableColumnWidth(table, 1, 100); - UIHelper.fixTableColumnWidth(table, 2, 100); - UIHelper.fixTableColumnWidth(table, 3, 200); - - table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); - - UIHelper.setTableColumnRenderer(table, 1, - UIHelper.newDecorateTableCellRenderer(renderer, SexDto.class)); -} -]]></script> - - <Table id="editView" insets="0" fill="both"> - <row> - <cell anchor="north" weightx="1"> - <JTabbedPane id='tabPane'> - <tab id='generalTab'> - <Table fill="both"> - - <!-- sex --> - <row> - <cell anchor="west"> - <JLabel id='sexLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='sex' constructorParams='this' - genericType='ReferentialReference<SexDto>' _entityClass='SexDto.class'/> - </cell> - </row> - - <!-- species --> - <row> - <cell anchor='west'> - <JLabel id='speciesLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='species' constructorParams='this' - genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class'/> - </cell> - </row> - - <!-- ocean --> - <row> - <cell anchor='west'> - <JLabel id='oceanLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='ocean' constructorParams='this' - genericType='ReferentialReference<OceanDto>' _entityClass='OceanDto.class'/> - </cell> - </row> - - <!-- date debut - fin de validite --> - <row> - <cell anchor='west'> - <JLabel id='startDateFinValiditeLabel'/> - </cell> - <cell anchor='west' weightx="1" fill="both"> - <JPanel layout='{new GridLayout()}'> - <JXDatePicker id='startDate' - onActionPerformed='getBean().setStartDate(startDate.getDate())'/> - <JXDatePicker id='endDate' - onActionPerformed='getBean().setEndDate(endDate.getDate())'/> - </JPanel> - </cell> - </row> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- status --> - <row> - <cell anchor="west"> - <JLabel id='statusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <EnumEditor id='status' constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - - <row> - <cell columns="2" weighty="1"> - <JLabel/> - </cell> - </row> - </Table> - </tab> - - <tab id='otherTab'> - <Table fill="both" insets="0"> - - <row> - <cell weightx="1"> - <Table id="relationTable" fill="both"> - - <!-- coefficients --> - <row> - <cell anchor='west' columns="2"> - <JLabel id='coefficientsInformation'/> - </cell> - </row> - - <row> - <cell anchor='west'> - <JLabel id='coefficientsLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='coefficients' - onKeyReleased='getBean().setCoefficients(coefficients.getText())'/> - </cell> - </row> - - <!-- relation weight --> - <row> - <cell anchor='west' columns="2"> - <JLabel id='lengthWeightFormulaInformation'/> - </cell> - </row> - - <row> - <cell anchor='west'> - <JLabel id='lengthWeightFormulaLabel'/> - </cell> - <cell weightx="1" fill="both"> - <JTextField id='lengthWeightFormula' - onKeyReleased='getBean().setLengthWeightFormula(lengthWeightFormula.getText())'/> - </cell> - </row> - - <!-- relation taille --> - <row> - <cell anchor='west' columns="2"> - <JLabel id='weightLengthFormulaInformation'/> - </cell> - </row> - - <row> - <cell anchor='west'> - <JLabel id='weightLengthFormulaLabel'/> - </cell> - <cell weightx="1" fill="both"> - <JTextField id='weightLengthFormula' - onKeyReleased='getBean().setWeightLengthFormula(weightLengthFormula.getText())'/> - </cell> - </row> - </Table> - </cell> - </row> - - <row> - <cell weightx="1"> - - <Table id='meanValuesTable' fill='both' insets="1"> - - <!-- tailleMoyen --> - <row> - <cell anchor="west"> - <JLabel id='meanLengthLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <NumberEditor id='meanLength' constructorParams='this' styleClass="float2"/> - </cell> - </row> - - <!-- meanWeight --> - <row> - <cell anchor="west"> - <JLabel id='meanWeightLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <NumberEditor id='meanWeight' constructorParams='this' styleClass="float2"/> - </cell> - </row> - <row> - <cell> - <javax.swing.Box.Filler id='filler' - constructorParams='UIHelper.newMinDimension(), UIHelper.newMinDimension(), UIHelper.newMaxXDimension()'/> - </cell> - </row> - </Table> - - </cell> - </row> - - <row> - <cell columns="2" weighty="1"> - <JLabel/> - </cell> - </row> - - </Table> - </tab> - </JTabbedPane> - </cell> - </row> - <row> - <cell columns="2" weighty="1"> - <JLabel/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/LengthWeightParameterUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/LengthWeightParameterUIHandler.java deleted file mode 100644 index f3cb36c..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/LengthWeightParameterUIHandler.java +++ /dev/null @@ -1,102 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.LengthWeightParameterDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.content.ref.ContentReferenceUI; -import fr.ird.observe.ui.content.ref.ContentReferenceUIHandler; -import jaxx.runtime.validator.swing.SwingValidatorMessage; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.event.TableModelListener; -import java.util.HashSet; -import java.util.Set; - -/** - * Created on 1/11/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.11 - */ -public class LengthWeightParameterUIHandler extends ContentReferenceUIHandler<LengthWeightParameterDto> { - - // Compute valid state of tab from the error table - protected final TableModelListener computeTabValidStateListener; - - public LengthWeightParameterUIHandler(ContentReferenceUI<LengthWeightParameterDto> ui) { - super(ui); - computeTabValidStateListener = e -> { - - SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); - computeTabValidState(source); - - }; - } - - @Override - public void initUI() { - - super.initUI(); - - // To be sure always remove listener (could prevent some leaks) - getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); - // listen messages to see if required to add - getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); - - } - - @Override - public void selectBean(ReferentialReference<LengthWeightParameterDto> selectedBean) { - - super.selectBean(selectedBean); - - SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); - computeTabValidState(errorTableModel); - - ((LengthWeightParameterUI) getUi()).getTabPane().setSelectedIndex(0); - - } - - protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { - - Set<String> errorProperties = new HashSet<>(); - int rowCount = errorTableModel.getRowCount(); - for (int i = 0; i < rowCount; i++) { - - SwingValidatorMessage row = errorTableModel.getRow(i); - if (NuitonValidatorScope.ERROR.equals(row.getScope())) { - errorProperties.add(row.getField()); - } - } - - boolean generalTabValid = !errorProperties.removeAll(LengthWeightParameterUIModel.GENERAL_TAB_PROPERTIES); - boolean otherTabValid = !errorProperties.removeAll(LengthWeightParameterUIModel.OTHER_TAB_PROPERTIES); - - LengthWeightParameterUIModel model = (LengthWeightParameterUIModel) getModel(); - model.setGeneralTabValid(generalTabValid); - model.setOtherTabValid(otherTabValid); - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/LengthWeightParameterUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/LengthWeightParameterUIModel.java deleted file mode 100644 index 117868d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/LengthWeightParameterUIModel.java +++ /dev/null @@ -1,102 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.ImmutableSet; -import fr.ird.observe.services.dto.referential.LengthWeightParameterDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -import java.util.Set; - -/** - * Created on 9/27/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class LengthWeightParameterUIModel extends ContentReferenceUIModel<LengthWeightParameterDto> { - - public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; - - public static final String PROPERTY_OTHER_TAB_VALID = "otherTabValid"; - - public static final Set<String> GENERAL_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(LengthWeightParameterDto.PROPERTY_URI, - LengthWeightParameterDto.PROPERTY_CODE, - LengthWeightParameterDto.PROPERTY_STATUS, - LengthWeightParameterDto.PROPERTY_SEX, - LengthWeightParameterDto.PROPERTY_OCEAN, - LengthWeightParameterDto.PROPERTY_SPECIES, - LengthWeightParameterDto.PROPERTY_NEED_COMMENT, - LengthWeightParameterDto.PROPERTY_START_DATE, - LengthWeightParameterDto.PROPERTY_END_DATE).build(); - - public static final Set<String> OTHER_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(LengthWeightParameterDto.PROPERTY_MEAN_LENGTH, - LengthWeightParameterDto.PROPERTY_MEAN_WEIGHT, - LengthWeightParameterDto.PROPERTY_WEIGHT_LENGTH_FORMULA, - LengthWeightParameterDto.PROPERTY_WEIGHT_LENGTH_FORMULA_VALID, - LengthWeightParameterDto.PROPERTY_LENGTH_WEIGHT_FORMULA, - LengthWeightParameterDto.PROPERTY_LENGTH_WEIGHT_FORMULA_VALID, - LengthWeightParameterDto.PROPERTY_COEFFICIENTS).build(); - - private static final long serialVersionUID = 1L; - - protected boolean generalTabValid; - - protected boolean otherTabValid; - - public LengthWeightParameterUIModel() { - super(LengthWeightParameterDto.class, - null, - new String[]{ - LengthWeightParameterDto.PROPERTY_SEX, - LengthWeightParameterDto.PROPERTY_OCEAN, - LengthWeightParameterDto.PROPERTY_SPECIES, - LengthWeightParameterDto.PROPERTY_START_DATE, - }, - null - ); - } - - public boolean isOtherTabValid() { - return otherTabValid; - } - - public void setOtherTabValid(boolean otherTabValid) { - Object oldValue = isOtherTabValid(); - this.otherTabValid = otherTabValid; - firePropertyChange(PROPERTY_OTHER_TAB_VALID, oldValue, otherTabValid); - } - - public boolean isGeneralTabValid() { - return generalTabValid; - } - - public void setGeneralTabValid(boolean generalTabValid) { - Object oldValue = isGeneralTabValid(); - this.generalTabValid = generalTabValid; - firePropertyChange(PROPERTY_GENERAL_TAB_VALID, oldValue, generalTabValid); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/OceanUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/OceanUI.jaxx deleted file mode 100644 index 18ddbb3..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/OceanUI.jaxx +++ /dev/null @@ -1,164 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='OceanDto' - contentTitle='{n("observe.content.title.oceans")}' - listText='{n("observe.content.list.ocean")}' - createToolTip='{n("observe.content.action.ocean.create.tip")}' - detailToolTip='{n("observe.content.action.ocean.detail.tip")}' - modifyToolTip='{n("observe.content.action.ocean.modify.tip")}' - deleteToolTip='{n("observe.content.action.ocean.delete.tip")}' - saveToolTip='{n("observe.content.action.ocean.save.tip")}' - - > - - <style source="ReferenceEntity.jcss"/> - <style source="I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.OceanDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.OceanDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <OceanUIModel id='model'/> - - <!-- edit bean --> - <OceanDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' - onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/OceanUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/OceanUIModel.java deleted file mode 100644 index 9d78273..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/OceanUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.OceanDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/27/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class OceanUIModel extends ContentReferenceUIModel<OceanDto> { - - private static final long serialVersionUID = 1L; - - public OceanUIModel() { - super(OceanDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/OrganismUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/OrganismUI.jaxx deleted file mode 100644 index a22c39e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/OrganismUI.jaxx +++ /dev/null @@ -1,189 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='OrganismDto' - contentTitle='{n("observe.content.title.organisms")}' - listText='{n("observe.content.list.organism")}' - createToolTip='{n("observe.content.action.organism.create.tip")}' - detailToolTip='{n("observe.content.action.organism.detail.tip")}' - modifyToolTip='{n("observe.content.action.organism.modify.tip")}' - deleteToolTip='{n("observe.content.action.organism.delete.tip")}' - saveToolTip='{n("observe.content.action.organism.save.tip")}' - - > - - <style source="ReferenceEntity.jcss"/> - <style source="I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.OrganismDto - fr.ird.observe.services.dto.referential.CountryDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - jaxx.runtime.swing.editor.bean.BeanComboBox - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.OrganismDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <OrganismUIModel id='model'/> - - <!-- edit bean --> - <OrganismDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' - onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- country --> - <row> - <cell anchor='west'> - <JLabel id='countryLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='country' constructorParams='this' genericType='ReferentialReference<CountryDto>' _entityClass='CountryDto.class'/> - </cell> - </row> - - <!-- description --> - <row> - <cell anchor='west'> - <JLabel id='descriptionLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='description' - onKeyReleased='getBean().setDescription(description.getText())'/> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/OrganismUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/OrganismUIModel.java deleted file mode 100644 index b11c548..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/OrganismUIModel.java +++ /dev/null @@ -1,45 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.OrganismDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/27/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class OrganismUIModel extends ContentReferenceUIModel<OrganismDto> { - - private static final long serialVersionUID = 1L; - - public OrganismUIModel() { - super(OrganismDto.class, - new String[]{OrganismDto.PROPERTY_COUNTRY, OrganismDto.PROPERTY_DESCRIPTION}, - new String[]{OrganismUI.BINDING_COUNTRY_SELECTED_ITEM, OrganismUI.BINDING_DESCRIPTION_TEXT} - ); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/PersonUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/PersonUI.jaxx deleted file mode 100644 index a9b73bd..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/PersonUI.jaxx +++ /dev/null @@ -1,169 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='PersonDto' - contentTitle='{n("observe.content.title.persons")}' - listText='{n("observe.content.list.person")}' - createToolTip='{n("observe.content.action.person.create.tip")}' - detailToolTip='{n("observe.content.action.person.detail.tip")}' - modifyToolTip='{n("observe.content.action.person.modify.tip")}' - deleteToolTip='{n("observe.content.action.person.delete.tip")}' - saveToolTip='{n("observe.content.action.person.save.tip")}' - - > - - <style source="ReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.PersonDto - fr.ird.observe.services.dto.referential.CountryDto - fr.ird.observe.ui.UIHelper - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - javax.swing.JTable - javax.swing.JScrollPane - javax.swing.table.TableCellRenderer - - jaxx.runtime.swing.editor.bean.BeanComboBox - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.PersonDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <PersonUIModel id='model'/> - - <!-- edit bean --> - <PersonDto id='bean'/> - - <script><![CDATA[ -@Override -public void decorateUniqueKeyTable(JTable table, - TableCellRenderer renderer, - JScrollPane pane) { - UIHelper.fixTableColumnWidth(table, 1, 120); -} -]]></script> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- lastName --> - <row> - <cell anchor="west"> - <JLabel id='lastNameLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='lastName' - onKeyReleased='getBean().setLastName(lastName.getText())'/> - </cell> - </row> - - <!-- firstName --> - <row> - <cell anchor="west"> - <JLabel id='firstNameLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='firstName' - onKeyReleased='getBean().setFirstName(firstName.getText())'/> - </cell> - </row> - - <!-- country --> - <row> - <cell anchor='west'> - <JLabel id='countryLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='country' constructorParams='this' genericType='ReferentialReference<CountryDto>' _entityClass='CountryDto.class'/> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - - <!-- is observer --> - <row> - <cell columns="2"> - <JCheckBox id='observer' - onStateChanged='getBean().setObserver(observer.isSelected())'/> - </cell> - </row> - - <!-- is captain --> - <row> - <cell columns="2"> - <JCheckBox id='captain' - onStateChanged='getBean().setCaptain(captain.isSelected())'/> - </cell> - </row> - - <!-- is dataEntryOperator --> - <row> - <cell columns="2"> - <JCheckBox id='dataEntryOperator' - onStateChanged='getBean().setDataEntryOperator(dataEntryOperator.isSelected())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/PersonUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/PersonUIModel.java deleted file mode 100644 index 40269f5..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/PersonUIModel.java +++ /dev/null @@ -1,61 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.PersonDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/27/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class PersonUIModel extends ContentReferenceUIModel<PersonDto> { - - private static final long serialVersionUID = 1L; - - public PersonUIModel() { - super(PersonDto.class, - new String[]{ - PersonDto.PROPERTY_CODE, - PersonDto.PROPERTY_LAST_NAME, - PersonDto.PROPERTY_FIRST_NAME, - PersonDto.PROPERTY_CAPTAIN, - PersonDto.PROPERTY_OBSERVER, - PersonDto.PROPERTY_DATA_ENTRY_OPERATOR, - PersonDto.PROPERTY_COUNTRY - }, - new String[]{PersonDto.PROPERTY_CODE}, - new String[]{PersonUI.BINDING_CODE_TEXT, - PersonUI.BINDING_FIRST_NAME_TEXT, - PersonUI.BINDING_LAST_NAME_TEXT, - PersonUI.BINDING_CAPTAIN_SELECTED, - PersonUI.BINDING_OBSERVER_SELECTED, - PersonUI.BINDING_DATA_ENTRY_OPERATOR_SELECTED, - PersonUI.BINDING_COUNTRY_SELECTED_ITEM, - } - ); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/ProgramObservationEnum.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/ProgramObservationEnum.java deleted file mode 100644 index 35f6828..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/ProgramObservationEnum.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.ref.impl; - -import static org.nuiton.i18n.I18n.n; - -/** - * Une énumeration pour définir les différents niveaux d'observations effectués - * sur un program. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.2 - */ -public enum ProgramObservationEnum { - - value0, - value1, - value2, - value3, - value4, - value5, - value6, - value7, - value8, - value9; - - static { - - n("observe.programObservationEnum.value0"); - n("observe.programObservationEnum.value1"); - n("observe.programObservationEnum.value2"); - n("observe.programObservationEnum.value3"); - n("observe.programObservationEnum.value4"); - n("observe.programObservationEnum.value5"); - n("observe.programObservationEnum.value6"); - n("observe.programObservationEnum.value7"); - n("observe.programObservationEnum.value8"); - n("observe.programObservationEnum.value9"); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/ProgramUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/ProgramUI.jaxx deleted file mode 100644 index 55f8665..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/ProgramUI.jaxx +++ /dev/null @@ -1,339 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='ProgramDto' - contentTitle='{n("observe.content.title.programs")}' - listText='{n("observe.content.list.program")}' - createToolTip='{n("observe.content.action.program.create.tip")}' - detailToolTip='{n("observe.content.action.program.detail.tip")}' - modifyToolTip='{n("observe.content.action.program.modify.tip")}' - deleteToolTip='{n("observe.content.action.program.delete.tip")}' - saveToolTip='{n("observe.content.action.program.save.tip")}' - - > - - <style source="ReferenceEntity.jcss"/> - <style source="I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.constants.GearType - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.ProgramDto - fr.ird.observe.services.dto.referential.OrganismDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - fr.ird.observe.ui.content.ref.impl.ProgramObservationEnum - - jaxx.runtime.swing.editor.bean.BeanComboBox - - org.jdesktop.swingx.JXDatePicker - - java.awt.Dimension - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' context='ui-create' - beanClass='fr.ird.observe.services.dto.referential.ProgramDto' errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <ProgramUIModel id='model'/> - - <!-- handler --> - <ProgramUIHandler id='handler' constructorParams="this"/> - - <!-- edit bean --> - <ProgramDto id='bean'/> - - <Table id="editView" insets="0" fill="both"> - <row> - <cell anchor="north" weightx="1"> - <JTabbedPane id='tabPane'> - <tab id='generalTab'> - <Table fill="both"> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- organism --> - <row> - <cell anchor='west'> - <JLabel id='organismLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='organism' constructorParams='this' - genericType='ReferentialReference<OrganismDto>' _entityClass='OrganismDto.class'/> - </cell> - </row> - - <row> - <!-- gearType --> - <cell anchor='west'> - <JLabel id='gearTypeLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <EnumEditor id='gearType' - constructorParams='GearType.class' - genericType='GearType' - onItemStateChanged='getBean().setGearType((GearType) gearType.getSelectedItem())'/> - </cell> - </row> - - <!-- date debut - fin de validite --> - <row> - <cell anchor='west'> - <JLabel id='startDateFinProgramLabel'/> - </cell> - <cell anchor='west'> - <JPanel layout='{new GridLayout()}'> - <JXDatePicker id='startDate' onActionPerformed='getBean().setStartDate(startDate.getDate())'/> - <JXDatePicker id='endDate' onActionPerformed='getBean().setEndDate(endDate.getDate())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - - <row> - <cell columns="2"> - <Table id='editI18nTable2'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> - </cell> - </row> - </Table> - </tab> - - <tab id='observationsTab'> - <Table fill="both"> - - <row> - - <!-- nonTargetObservation --> - <cell anchor='west'> - <JLabel id='nonTargetObservationLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <EnumEditor id='nonTargetObservation' - constructorParams='ProgramObservationEnum.class, getConfig().getNonTargetObservation()' - genericType='ProgramObservationEnum' - onItemStateChanged='getBean().setNonTargetObservation(nonTargetObservation.getSelectedIndex())'/> - </cell> - - </row> - <row> - <!-- targetDiscardsObservation --> - <cell anchor='west'> - <JLabel id='targetDiscardsObservationLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <EnumEditor id='targetDiscardsObservation' - constructorParams='ProgramObservationEnum.class, getConfig().getTargetDiscardsObservation()' - genericType='ProgramObservationEnum' - onItemStateChanged='getBean().setTargetDiscardsObservation(targetDiscardsObservation.getSelectedIndex())'/> - </cell> - </row> - <row> - - <!-- samplesObservation --> - <cell anchor='west'> - <JLabel id='samplesObservationLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <EnumEditor id='samplesObservation' - constructorParams='ProgramObservationEnum.class, getConfig().getSamplesObservation()' - genericType='ProgramObservationEnum' - onItemStateChanged='getBean().setSamplesObservation(samplesObservation.getSelectedIndex())'/> - </cell> - </row> - <row> - <!-- objectsObservation --> - <cell anchor='west'> - <JLabel id='objectsObservationLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <EnumEditor id='objectsObservation' - constructorParams='ProgramObservationEnum.class, getConfig().getObjectsObservation()' - genericType='ProgramObservationEnum' - onItemStateChanged='getBean().setObjectsObservation(objectsObservation.getSelectedIndex())'/> - </cell> - </row> - <row> - - <!-- detailledActivitiesObservation --> - <cell anchor='west'> - <JLabel id='detailledActivitiesObservationLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <EnumEditor id='detailledActivitiesObservation' - constructorParams='ProgramObservationEnum.class, getConfig().getDetailledActivitiesObservation()' - genericType='ProgramObservationEnum' - onItemStateChanged='getBean().setDetailledActivitiesObservation(detailledActivitiesObservation.getSelectedIndex())'/> - </cell> - </row> - <row> - <!-- mammalsObservation --> - <cell anchor='west'> - <JLabel id='mammalsObservationLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <EnumEditor id='mammalsObservation' - constructorParams='ProgramObservationEnum.class, getConfig().getMammalsObservation()' - genericType='ProgramObservationEnum' - onItemStateChanged='getBean().setMammalsObservation(mammalsObservation.getSelectedIndex())'/> - </cell> - </row> - <row> - - <!-- birdsObservation --> - <cell anchor='west'> - <JLabel id='birdsObservationLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <EnumEditor id='birdsObservation' - constructorParams='ProgramObservationEnum.class, getConfig().getBirdsObservation()' - genericType='ProgramObservationEnum' - onItemStateChanged='getBean().setBirdsObservation(birdsObservation.getSelectedIndex())'/> - </cell> - </row> - <row> - <!-- baitObservation --> - <cell anchor='west'> - <JLabel id='baitObservationLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <EnumEditor id='baitObservation' - constructorParams='ProgramObservationEnum.class, getConfig().getBaitObservation()' - genericType='ProgramObservationEnum' - onItemStateChanged='getBean().setBaitObservation(baitObservation.getSelectedIndex())'/> - </cell> - </row> - - <row> - <cell columns="2" weighty="1"> - <JLabel/> - </cell> - </row> - </Table> - </tab> - </JTabbedPane> - </cell> - </row> - - <!-- Comment --> - <row> - <cell weightx="1" weighty="1" fill="both"> - <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2' onKeyReleased='getBean().setComment(comment2.getText())'/> - </JScrollPane> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/ProgramUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/ProgramUIHandler.java deleted file mode 100644 index d45819b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/ProgramUIHandler.java +++ /dev/null @@ -1,102 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.content.ref.ContentReferenceUI; -import fr.ird.observe.ui.content.ref.ContentReferenceUIHandler; -import jaxx.runtime.validator.swing.SwingValidatorMessage; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.event.TableModelListener; -import java.util.HashSet; -import java.util.Set; - -/** - * Created on 1/11/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.11 - */ -public class ProgramUIHandler extends ContentReferenceUIHandler<ProgramDto> { - - // Compute valid state of tab from the error table - protected final TableModelListener computeTabValidStateListener; - - public ProgramUIHandler(ContentReferenceUI<ProgramDto> ui) { - super(ui); - computeTabValidStateListener = e -> { - - SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); - computeTabValidState(source); - - }; - } - - @Override - public void initUI() { - - super.initUI(); - - // To be sure always remove listener (could prevent some leaks) - getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); - // listen messages to see if required to add - getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); - - } - - @Override - public void selectBean(ReferentialReference<ProgramDto> selectedBean) { - - super.selectBean(selectedBean); - - SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); - computeTabValidState(errorTableModel); - - ((ProgramUI) getUi()).getTabPane().setSelectedIndex(0); - - } - - protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { - - Set<String> errorProperties = new HashSet<>(); - int rowCount = errorTableModel.getRowCount(); - for (int i = 0; i < rowCount; i++) { - - SwingValidatorMessage row = errorTableModel.getRow(i); - if (NuitonValidatorScope.ERROR.equals(row.getScope())) { - errorProperties.add(row.getField()); - } - } - - boolean generalTabValid = !errorProperties.removeAll(ProgramUIModel.GENERAL_TAB_PROPERTIES); - boolean observationsTabValid = !errorProperties.removeAll(ProgramUIModel.OBSERVATIONS_TAB_PROPERTIES); - - ProgramUIModel model = (ProgramUIModel) getModel(); - model.setGeneralTabValid(generalTabValid); - model.setObservationsTabValid(observationsTabValid); - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/ProgramUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/ProgramUIModel.java deleted file mode 100644 index a20c38f..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/ProgramUIModel.java +++ /dev/null @@ -1,126 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.ImmutableSet; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -import java.util.Set; - -/** - * Created on 9/27/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ProgramUIModel extends ContentReferenceUIModel<ProgramDto> { - - public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; - - public static final String PROPERTY_OBSERVATIONS_TAB_VALID = "observationsTabValid"; - - public static final Set<String> GENERAL_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(ProgramDto.PROPERTY_URI, - ProgramDto.PROPERTY_CODE, - ProgramDto.PROPERTY_STATUS, - ProgramDto.PROPERTY_NEED_COMMENT, - ProgramDto.PROPERTY_GEAR_TYPE, - ProgramDto.PROPERTY_ORGANISM, - ProgramDto.PROPERTY_LABEL1, - ProgramDto.PROPERTY_LABEL2, - ProgramDto.PROPERTY_LABEL3, - ProgramDto.PROPERTY_LABEL4, - ProgramDto.PROPERTY_LABEL5, - ProgramDto.PROPERTY_LABEL6, - ProgramDto.PROPERTY_LABEL7, - ProgramDto.PROPERTY_LABEL8).build(); - - public static final Set<String> OBSERVATIONS_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(ProgramDto.PROPERTY_DETAILLED_ACTIVITIES_OBSERVATION, - ProgramDto.PROPERTY_NON_TARGET_OBSERVATION, - ProgramDto.PROPERTY_BAIT_OBSERVATION, - ProgramDto.PROPERTY_MAMMALS_OBSERVATION, - ProgramDto.PROPERTY_SAMPLES_OBSERVATION, - ProgramDto.PROPERTY_OBJECTS_OBSERVATION, - ProgramDto.PROPERTY_BIRDS_OBSERVATION, - ProgramDto.PROPERTY_TARGET_DISCARDS_OBSERVATION).build(); - - private static final long serialVersionUID = 1L; - - protected boolean generalTabValid; - - protected boolean observationsTabValid; - - public ProgramUIModel() { - super(ProgramDto.class, - new String[]{ - ProgramDto.PROPERTY_ORGANISM, - ProgramDto.PROPERTY_START_DATE, - ProgramDto.PROPERTY_END_DATE, - ProgramDto.PROPERTY_DETAILLED_ACTIVITIES_OBSERVATION, - ProgramDto.PROPERTY_NON_TARGET_OBSERVATION, - ProgramDto.PROPERTY_BAIT_OBSERVATION, - ProgramDto.PROPERTY_MAMMALS_OBSERVATION, - ProgramDto.PROPERTY_SAMPLES_OBSERVATION, - ProgramDto.PROPERTY_OBJECTS_OBSERVATION, - ProgramDto.PROPERTY_BIRDS_OBSERVATION, - ProgramDto.PROPERTY_TARGET_DISCARDS_OBSERVATION, - ProgramDto.PROPERTY_GEAR_TYPE}, - new String[]{ - ProgramUI.BINDING_ORGANISM_SELECTED_ITEM, - ProgramUI.BINDING_START_DATE_DATE, - ProgramUI.BINDING_END_DATE_DATE, - ProgramUI.BINDING_DETAILLED_ACTIVITIES_OBSERVATION_SELECTED_INDEX, - ProgramUI.BINDING_NON_TARGET_OBSERVATION_SELECTED_INDEX, - ProgramUI.BINDING_BAIT_OBSERVATION_SELECTED_INDEX, - ProgramUI.BINDING_MAMMALS_OBSERVATION_SELECTED_INDEX, - ProgramUI.BINDING_SAMPLES_OBSERVATION_SELECTED_INDEX, - ProgramUI.BINDING_OBJECTS_OBSERVATION_SELECTED_INDEX, - ProgramUI.BINDING_BIRDS_OBSERVATION_SELECTED_INDEX, - ProgramUI.BINDING_TARGET_DISCARDS_OBSERVATION_SELECTED_INDEX, - ProgramUI.BINDING_GEAR_TYPE_SELECTED_ITEM} - ); - } - - public boolean isObservationsTabValid() { - return observationsTabValid; - } - - public void setObservationsTabValid(boolean observationsTabValid) { - Object oldValue = isObservationsTabValid(); - this.observationsTabValid = observationsTabValid; - firePropertyChange(PROPERTY_OBSERVATIONS_TAB_VALID, oldValue, observationsTabValid); - } - - public boolean isGeneralTabValid() { - return generalTabValid; - } - - public void setGeneralTabValid(boolean generalTabValid) { - Object oldValue = isGeneralTabValid(); - this.generalTabValid = generalTabValid; - firePropertyChange(PROPERTY_GENERAL_TAB_VALID, oldValue, generalTabValid); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SexUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SexUI.jaxx deleted file mode 100644 index 760e12b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SexUI.jaxx +++ /dev/null @@ -1,164 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='SexDto' - contentTitle='{n("observe.content.title.sexx")}' - listText='{n("observe.content.list.sex")}' - createToolTip='{n("observe.content.action.sex.create.tip")}' - detailToolTip='{n("observe.content.action.sex.detail.tip")}' - modifyToolTip='{n("observe.content.action.sex.modify.tip")}' - deleteToolTip='{n("observe.content.action.sex.delete.tip")}' - saveToolTip='{n("observe.content.action.sex.save.tip")}' - - > - - <style source="ReferenceEntity.jcss"/> - <style source="I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.SexDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.SexDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <SexUIModel id='model'/> - - <!-- edit bean --> - <SexDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id="uriLabel"/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SexUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SexUIModel.java deleted file mode 100644 index 179b9e2..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SexUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.SexDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/27/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class SexUIModel extends ContentReferenceUIModel<SexDto> { - - private static final long serialVersionUID = 1L; - - public SexUIModel() { - super(SexDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesGroupUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesGroupUI.jaxx deleted file mode 100644 index 3278661..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesGroupUI.jaxx +++ /dev/null @@ -1,166 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='SpeciesGroupDto' - contentTitle='{n("observe.content.title.speciesGroupSpeciess")}' - listText='{n("observe.content.list.speciesGroupSpecies")}' - createToolTip='{n("observe.content.action.speciesGroupSpecies.create.tip")}' - detailToolTip='{n("observe.content.action.speciesGroupSpecies.detail.tip")}' - modifyToolTip='{n("observe.content.action.speciesGroupSpecies.modify.tip")}' - deleteToolTip='{n("observe.content.action.speciesGroupSpecies.delete.tip")}' - saveToolTip='{n("observe.content.action.speciesGroupSpecies.save.tip")}' - - > - - <style source="ReferenceEntity.jcss"/> - <style source="I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.SpeciesGroupDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - jaxx.runtime.swing.editor.NumberEditor - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.SpeciesGroupDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <SpeciesGroupUIModel id='model'/> - - <!-- edit bean --> - <SpeciesGroupDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesGroupUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesGroupUIModel.java deleted file mode 100644 index 809a647..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesGroupUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.SpeciesGroupDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/27/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class SpeciesGroupUIModel extends ContentReferenceUIModel<SpeciesGroupDto> { - - private static final long serialVersionUID = 1L; - - public SpeciesGroupUIModel() { - super(SpeciesGroupDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesListUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesListUI.jaxx deleted file mode 100644 index 3acae19..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesListUI.jaxx +++ /dev/null @@ -1,206 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='SpeciesListDto' - contentTitle='{n("observe.content.title.speciesLists")}' - listText='{n("observe.content.list.speciesList")}' - createToolTip='{n("observe.content.action.speciesList.create.tip")}' - detailToolTip='{n("observe.content.action.speciesList.detail.tip")}' - modifyToolTip='{n("observe.content.action.speciesList.modify.tip")}' - deleteToolTip='{n("observe.content.action.speciesList.delete.tip")}' - saveToolTip='{n("observe.content.action.species.save.tip")}' - - > - - <style source="ReferenceEntity.jcss"/> - <style source="I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.SpeciesListDto - fr.ird.observe.services.dto.referential.SpeciesDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - jaxx.runtime.swing.editor.bean.BeanComboBox - org.nuiton.jaxx.widgets.select.FilterableDoubleList - - javax.swing.DefaultListModel - javax.swing.ListSelectionModel - - java.util.Collection - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.SpeciesListDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <SpeciesListUIModel id='model'/> - - <!-- edit bean --> - <SpeciesListDto id='bean'/> - - <!-- handler --> - <SpeciesListUIHandler id='handler' constructorParams="this"/> - - <Table id="editView" insets="0" fill="both"> - <row> - <cell anchor="north" weightx="1"> - <JTabbedPane id='tabPane'> - <tab id='generalTab'> - <Table fill="both"> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - - <row> - <cell columns="2"> - <Table id='editI18nTable2'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> - </cell> - </row> - <row> - <cell columns="2" weighty="1"> - <JLabel/> - </cell> - </row> - </Table> - </tab> - - <tab id='speciesTab'> - <Table fill="both" weightx="1"> - <!-- species --> - <row> - <cell weightx="1" weighty="1"> - <JScrollPane id='speciesPane' layout='{new GridLayout(1,1)}'> - <FilterableDoubleList id='species' - genericType='ReferentialReference<SpeciesDto>' - _entityClass='SpeciesDto.class'/> - </JScrollPane> - </cell> - </row> - </Table> - </tab> - </JTabbedPane> - </cell> - </row> - <row> - <cell columns="2" weighty="1"> - <JLabel/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesListUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesListUIHandler.java deleted file mode 100644 index 2951983..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesListUIHandler.java +++ /dev/null @@ -1,102 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.SpeciesListDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUI; -import fr.ird.observe.ui.content.ref.ContentReferenceUIHandler; -import jaxx.runtime.validator.swing.SwingValidatorMessage; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.event.TableModelListener; -import java.util.HashSet; -import java.util.Set; - -/** - * Created on 1/11/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.11 - */ -public class SpeciesListUIHandler extends ContentReferenceUIHandler<SpeciesListDto> { - - // Compute valid state of tab from the error table - protected final TableModelListener computeTabValidStateListener; - - public SpeciesListUIHandler(ContentReferenceUI<SpeciesListDto> ui) { - super(ui); - computeTabValidStateListener = e -> { - - SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); - computeTabValidState(source); - - }; - } - - @Override - public void initUI() { - - super.initUI(); - - // To be sure always remove listener (could prevent some leaks) - getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); - // listen messages to see if required to add - getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); - - } - - @Override - public void selectBean(ReferentialReference<SpeciesListDto> selectedBean) { - - super.selectBean(selectedBean); - - SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); - computeTabValidState(errorTableModel); - - ((SpeciesListUI) getUi()).getTabPane().setSelectedIndex(0); - - } - - protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { - - Set<String> errorProperties = new HashSet<>(); - int rowCount = errorTableModel.getRowCount(); - for (int i = 0; i < rowCount; i++) { - - SwingValidatorMessage row = errorTableModel.getRow(i); - if (NuitonValidatorScope.ERROR.equals(row.getScope())) { - errorProperties.add(row.getField()); - } - } - - boolean generalTabValid = !errorProperties.removeAll(SpeciesListUIModel.GENERAL_TAB_PROPERTIES); - boolean speciesTabValid = !errorProperties.removeAll(SpeciesListUIModel.SPECIES_TAB_PROPERTIES); - - SpeciesListUIModel model = (SpeciesListUIModel) getModel(); - model.setGeneralTabValid(generalTabValid); - model.setSpeciesTabValid(speciesTabValid); - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesListUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesListUIModel.java deleted file mode 100644 index 0333d7b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesListUIModel.java +++ /dev/null @@ -1,94 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.ImmutableSet; -import fr.ird.observe.services.dto.referential.SpeciesListDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -import java.util.Set; - -/** - * Created on 9/27/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class SpeciesListUIModel extends ContentReferenceUIModel<SpeciesListDto> { - - public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; - - public static final String PROPERTY_SPECIES_TAB_VALID = "speciesTabValid"; - - public static final Set<String> GENERAL_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(SpeciesListDto.PROPERTY_URI, - SpeciesListDto.PROPERTY_CODE, - SpeciesListDto.PROPERTY_STATUS, - SpeciesListDto.PROPERTY_NEED_COMMENT, - SpeciesListDto.PROPERTY_LABEL1, - SpeciesListDto.PROPERTY_LABEL2, - SpeciesListDto.PROPERTY_LABEL3, - SpeciesListDto.PROPERTY_LABEL4, - SpeciesListDto.PROPERTY_LABEL5, - SpeciesListDto.PROPERTY_LABEL6, - SpeciesListDto.PROPERTY_LABEL7, - SpeciesListDto.PROPERTY_LABEL8).build(); - - public static final Set<String> SPECIES_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(SpeciesListDto.PROPERTY_SPECIES).build(); - - private static final long serialVersionUID = 1L; - - protected boolean generalTabValid; - - protected boolean speciesTabValid; - - public SpeciesListUIModel() { - super(SpeciesListDto.class, - new String[]{SpeciesListDto.PROPERTY_SPECIES}, - new String[]{SpeciesListDto.PROPERTY_SPECIES + SUFFIX_SELECTED}, - null - ); - } - - public boolean isSpeciesTabValid() { - return speciesTabValid; - } - - public void setSpeciesTabValid(boolean speciesTabValid) { - Object oldValue = isSpeciesTabValid(); - this.speciesTabValid = speciesTabValid; - firePropertyChange(PROPERTY_SPECIES_TAB_VALID, oldValue, speciesTabValid); - } - - public boolean isGeneralTabValid() { - return generalTabValid; - } - - public void setGeneralTabValid(boolean generalTabValid) { - Object oldValue = isGeneralTabValid(); - this.generalTabValid = generalTabValid; - firePropertyChange(PROPERTY_GENERAL_TAB_VALID, oldValue, generalTabValid); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesUI.jaxx deleted file mode 100644 index 9f20eeb..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesUI.jaxx +++ /dev/null @@ -1,282 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='SpeciesDto' - contentTitle='{n("observe.content.title.speciess")}' - listText='{n("observe.content.list.speciesFaune")}' - createToolTip='{n("observe.content.action.species.create.tip")}' - detailToolTip='{n("observe.content.action.species.detail.tip")}' - modifyToolTip='{n("observe.content.action.species.modify.tip")}' - deleteToolTip='{n("observe.content.action.species.delete.tip")}' - saveToolTip='{n("observe.content.action.species.save.tip")}' - - > - - <style source="ReferenceEntity.jcss"/> - <style source="I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.SpeciesDto - fr.ird.observe.services.dto.referential.SpeciesGroupDto - fr.ird.observe.services.dto.referential.OceanDto - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - org.nuiton.jaxx.widgets.select.FilterableDoubleList - - java.util.Collection - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.SpeciesDto' - context='ui-create' errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <SpeciesUIModel id='model'/> - - <!-- handler --> - <SpeciesUIHandler id='handler' constructorParams="this"/> - - <!-- edit bean --> - <SpeciesDto id='bean'/> - - <Table id="editView" insets="0" fill="both"> - <row> - <cell anchor="north" weightx="1"> - <JTabbedPane id='tabPane'> - <tab id='generalTab'> - <Table fill="both"> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' constructorParams='ReferenceStatus.class' genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- homeId / faoCode / wormsId --> - <row> - <cell anchor="west"> - <JLabel id='homeIdFAOWormsIdLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel layout='{new GridLayout()}'> - <JTextField id='homeId' onKeyReleased='getBean().setHomeId(homeId.getText())'/> - <JTextField id='faoCode' onKeyReleased='getBean().setFaoCode(faoCode.getText())'/> - <JTextField id='wormsId' onKeyReleased='getBean().setWormsId(Long.valueOf(wormsId.getText()))'/> - </JPanel> - </cell> - </row> - - <!-- speciesGroup --> - <row> - <cell anchor='west'> - <JLabel id='speciesGroupLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='speciesGroup' constructorParams='this' genericType='ReferentialReference<SpeciesGroupDto>' _entityClass='SpeciesGroupDto.class'/> - </cell> - </row> - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - - <row> - <cell columns="2"> - <Table id='editI18nTable2'> - <!-- scientificLabel --> - <row> - <cell anchor='west'> - <JLabel id='scientificLabelLabel'/> - </cell> - <cell anchor='east' fill="both" columns="3"> - <JTextField id='scientificLabel' - onKeyReleased='getBean().setScientificLabel(scientificLabel.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> - </cell> - </row> - <row> - <cell columns="2" weighty="1"> - <JLabel/> - </cell> - </row> - </Table> - </tab> - - <tab id='otherTab'> - <Table fill="both"> - <row> - <cell weightx="1"> - <Table id="editTaillePoids" fill='both' insets="1"> - - <!-- lengthMeasureType --> - <row> - <cell anchor="west"> - <JLabel id='lengthMeasureTypeLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='lengthMeasureType' - onKeyReleased='getBean().setLengthMeasureType(lengthMeasureType.getText())'/> - </cell> - </row> - - <!-- minLengthMax --> - <row> - <cell anchor="west"> - <JLabel id='minLengthMaxLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel layout='{new GridLayout()}'> - <NumberEditor id='minLength' constructorParams='this' styleClass="float2"/> - <NumberEditor id='maxLength' constructorParams='this' styleClass="float2"/> - </JPanel> - </cell> - </row> - - <!-- minWeightMax --> - <row> - <cell anchor="west"> - <JLabel id='minWeightMaxLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel layout='{new GridLayout()}'> - <NumberEditor id='minWeight' constructorParams='this' styleClass="float2"/> - <NumberEditor id='maxWeight' constructorParams='this' styleClass="float2"/> - </JPanel> - </cell> - </row> - - </Table> - </cell> - </row> - - <row> - <cell weightx="1"> - <JScrollPane id='oceanPane' layout='{new GridLayout(1,1)}' onFocusGained='ocean.requestFocus()'> - <FilterableDoubleList id='ocean' genericType='ReferentialReference<OceanDto>' _entityClass='OceanDto.class'/> - </JScrollPane> - </cell> - </row> - - <row> - <cell columns="2" weighty="1"> - <JLabel/> - </cell> - </row> - </Table> - </tab> - </JTabbedPane> - </cell> - </row> - <row> - <cell columns="2" weighty="1"> - <JLabel/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesUIHandler.java deleted file mode 100644 index 1928b3a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesUIHandler.java +++ /dev/null @@ -1,102 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.SpeciesDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUI; -import fr.ird.observe.ui.content.ref.ContentReferenceUIHandler; -import jaxx.runtime.validator.swing.SwingValidatorMessage; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.event.TableModelListener; -import java.util.HashSet; -import java.util.Set; - -/** - * Created on 1/11/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.11 - */ -public class SpeciesUIHandler extends ContentReferenceUIHandler<SpeciesDto> { - - // Compute valid state of tab from the error table - protected final TableModelListener computeTabValidStateListener; - - public SpeciesUIHandler(ContentReferenceUI<SpeciesDto> ui) { - super(ui); - computeTabValidStateListener = e -> { - - SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); - computeTabValidState(source); - - }; - } - - @Override - public void initUI() { - - super.initUI(); - - // To be sure always remove listener (could prevent some leaks) - getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); - // listen messages to see if required to add - getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); - - } - - @Override - public void selectBean(ReferentialReference<SpeciesDto> selectedBean) { - - super.selectBean(selectedBean); - - SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); - computeTabValidState(errorTableModel); - - ((SpeciesUI) getUi()).getTabPane().setSelectedIndex(0); - - } - - protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { - - Set<String> errorProperties = new HashSet<>(); - int rowCount = errorTableModel.getRowCount(); - for (int i = 0; i < rowCount; i++) { - - SwingValidatorMessage row = errorTableModel.getRow(i); - if (NuitonValidatorScope.ERROR.equals(row.getScope())) { - errorProperties.add(row.getField()); - } - } - - boolean generalTabValid = !errorProperties.removeAll(SpeciesUIModel.GENERAL_TAB_PROPERTIES); - boolean otherTabValid = !errorProperties.removeAll(SpeciesUIModel.OTHER_TAB_PROPERTIES); - - SpeciesUIModel model = (SpeciesUIModel) getModel(); - model.setGeneralTabValid(generalTabValid); - model.setOtherTabValid(otherTabValid); - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesUIModel.java deleted file mode 100644 index 4f4c581..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/SpeciesUIModel.java +++ /dev/null @@ -1,124 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.ImmutableSet; -import fr.ird.observe.services.dto.referential.SpeciesDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -import java.util.Set; - -/** - * Created on 9/27/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class SpeciesUIModel extends ContentReferenceUIModel<SpeciesDto> { - - public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; - - public static final String PROPERTY_OTHER_TAB_VALID = "otherTabValid"; - - public static final Set<String> GENERAL_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(SpeciesDto.PROPERTY_URI, - SpeciesDto.PROPERTY_CODE, - SpeciesDto.PROPERTY_STATUS, - SpeciesDto.PROPERTY_FAO_CODE, - SpeciesDto.PROPERTY_HOME_ID, - SpeciesDto.PROPERTY_WORMS_ID, - SpeciesDto.PROPERTY_NEED_COMMENT, - SpeciesDto.PROPERTY_SCIENTIFIC_LABEL, - SpeciesDto.PROPERTY_LABEL1, - SpeciesDto.PROPERTY_LABEL2, - SpeciesDto.PROPERTY_LABEL3, - SpeciesDto.PROPERTY_LABEL4, - SpeciesDto.PROPERTY_LABEL5, - SpeciesDto.PROPERTY_LABEL6, - SpeciesDto.PROPERTY_LABEL7, - SpeciesDto.PROPERTY_LABEL8).build(); - - public static final Set<String> OTHER_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(SpeciesDto.PROPERTY_SPECIES_GROUP, - SpeciesDto.PROPERTY_OCEAN, - SpeciesDto.PROPERTY_MAX_LENGTH, - SpeciesDto.PROPERTY_MIN_LENGTH, - SpeciesDto.PROPERTY_MAX_WEIGHT, - SpeciesDto.PROPERTY_MIN_WEIGHT).build(); - - private static final long serialVersionUID = 1L; - - protected boolean generalTabValid; - - protected boolean otherTabValid; - - - public SpeciesUIModel() { - super(SpeciesDto.class, - new String[]{SpeciesDto.PROPERTY_SPECIES_GROUP, - SpeciesDto.PROPERTY_OCEAN, - SpeciesDto.PROPERTY_LENGTH_MEASURE_TYPE, - SpeciesDto.PROPERTY_MIN_LENGTH, - SpeciesDto.PROPERTY_MAX_LENGTH, - SpeciesDto.PROPERTY_MIN_WEIGHT, - SpeciesDto.PROPERTY_MAX_WEIGHT, - SpeciesDto.PROPERTY_HOME_ID, - SpeciesDto.PROPERTY_FAO_CODE, - SpeciesDto.PROPERTY_WORMS_ID, - SpeciesDto.PROPERTY_SCIENTIFIC_LABEL}, - new String[]{ - SpeciesDto.PROPERTY_SPECIES_GROUP + SUFFIX_SELECTED_ITEM, - SpeciesDto.PROPERTY_LENGTH_MEASURE_TYPE + SUFFIX_TEXT, - SpeciesDto.PROPERTY_MIN_LENGTH + SUFFIX_MODEL, - SpeciesDto.PROPERTY_MAX_LENGTH + SUFFIX_MODEL, - SpeciesDto.PROPERTY_MIN_WEIGHT + SUFFIX_MODEL, - SpeciesDto.PROPERTY_MAX_WEIGHT + SUFFIX_MODEL, - SpeciesDto.PROPERTY_HOME_ID + SUFFIX_TEXT, - SpeciesDto.PROPERTY_FAO_CODE + SUFFIX_TEXT, - SpeciesDto.PROPERTY_WORMS_ID + SUFFIX_TEXT, - SpeciesDto.PROPERTY_SCIENTIFIC_LABEL + SUFFIX_TEXT, - SpeciesDto.PROPERTY_OCEAN + SUFFIX_SELECTED} - ); - } - - public boolean isOtherTabValid() { - return otherTabValid; - } - - public void setOtherTabValid(boolean otherTabValid) { - Object oldValue = isOtherTabValid(); - this.otherTabValid = otherTabValid; - firePropertyChange(PROPERTY_OTHER_TAB_VALID, oldValue, otherTabValid); - } - - public boolean isGeneralTabValid() { - return generalTabValid; - } - - public void setGeneralTabValid(boolean generalTabValid) { - Object oldValue = isGeneralTabValid(); - this.generalTabValid = generalTabValid; - firePropertyChange(PROPERTY_GENERAL_TAB_VALID, oldValue, generalTabValid); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselSizeCategoryUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselSizeCategoryUI.jaxx deleted file mode 100644 index 2a32714..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselSizeCategoryUI.jaxx +++ /dev/null @@ -1,121 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='VesselSizeCategoryDto' - contentTitle='{n("observe.content.title.vesselSizeCategoryx")}' - listText='{n("observe.content.list.vesselSizeCategory")}' - createToolTip='{n("observe.content.action.vesselSizeCategory.create.tip")}' - detailToolTip='{n("observe.content.action.vesselSizeCategory.detail.tip")}' - modifyToolTip='{n("observe.content.action.vesselSizeCategory.modify.tip")}' - deleteToolTip='{n("observe.content.action.vesselSizeCategory.delete.tip")}' - saveToolTip='{n("observe.content.action.vesselSizeCategory.save.tip")}' - - > - - <style source="ReferenceEntity.jcss"/> - <style source="I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.VesselSizeCategoryDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.VesselSizeCategoryDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <VesselSizeCategoryUIModel id='model'/> - - <!-- edit bean --> - <VesselSizeCategoryDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - - <!-- gaugeLabel --> - <row> - <cell anchor="west"> - <JLabel id='gaugeLabelLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='gaugeLabel' - onKeyReleased='getBean().setGaugeLabel(gaugeLabel.getText())'/> - </cell> - </row> - - <!-- capacityLabel --> - <row> - <cell anchor="west"> - <JLabel id='capacityLabelLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='capacityLabel' - onKeyReleased='getBean().setCapacityLabel(capacityLabel.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselSizeCategoryUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselSizeCategoryUIModel.java deleted file mode 100644 index 2c3a893..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselSizeCategoryUIModel.java +++ /dev/null @@ -1,50 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.VesselSizeCategoryDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/27/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class VesselSizeCategoryUIModel extends ContentReferenceUIModel<VesselSizeCategoryDto> { - - private static final long serialVersionUID = 1L; - - public VesselSizeCategoryUIModel() { - super(VesselSizeCategoryDto.class, - new String[]{ - VesselSizeCategoryDto.PROPERTY_GAUGE_LABEL, - VesselSizeCategoryDto.PROPERTY_CAPACITY_LABEL - }, - new String[]{ - VesselSizeCategoryUI.BINDING_CAPACITY_LABEL_TEXT, - VesselSizeCategoryUI.BINDING_GAUGE_LABEL_TEXT} - ); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselTypeUI.jaxx deleted file mode 100644 index 6429186..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselTypeUI.jaxx +++ /dev/null @@ -1,164 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='VesselTypeDto' - contentTitle='{n("observe.content.title.vesselTypex")}' - listText='{n("observe.content.list.vesselType")}' - createToolTip='{n("observe.content.action.vesselType.create.tip")}' - detailToolTip='{n("observe.content.action.vesselType.detail.tip")}' - modifyToolTip='{n("observe.content.action.vesselType.modify.tip")}' - deleteToolTip='{n("observe.content.action.vesselType.delete.tip")}' - saveToolTip='{n("observe.content.action.vesselType.save.tip")}' - - > - - <style source="ReferenceEntity.jcss"/> - <style source="I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.VesselTypeDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.VesselTypeDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <VesselTypeUIModel id='model'/> - - <!-- edit bean --> - <VesselTypeDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id="uriLabel"/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselTypeUIModel.java deleted file mode 100644 index 78e7ce3..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselTypeUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.VesselTypeDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/27/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class VesselTypeUIModel extends ContentReferenceUIModel<VesselTypeDto> { - - private static final long serialVersionUID = 1L; - - public VesselTypeUIModel() { - super(VesselTypeDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselUI.jaxx deleted file mode 100644 index 3f75249..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselUI.jaxx +++ /dev/null @@ -1,297 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='VesselDto' - contentTitle='{n("observe.content.title.vesselx")}' - listText='{n("observe.content.list.vessel")}' - createToolTip='{n("observe.content.action.vessel.create.tip")}' - detailToolTip='{n("observe.content.action.vessel.detail.tip")}' - modifyToolTip='{n("observe.content.action.vessel.modify.tip")}' - deleteToolTip='{n("observe.content.action.vessel.delete.tip")}' - saveToolTip='{n("observe.content.action.vessel.save.tip")}' - - > - - <style source="ReferenceEntity.jcss"/> - <style source="I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.VesselDto - fr.ird.observe.services.dto.referential.VesselSizeCategoryDto - fr.ird.observe.services.dto.referential.CountryDto - fr.ird.observe.services.dto.referential.VesselTypeDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - org.jdesktop.swingx.JXDatePicker - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' context='ui-create' - beanClass='fr.ird.observe.services.dto.referential.VesselDto' errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <VesselUIModel id='model'/> - - <!-- handler --> - <VesselUIHandler id='handler' constructorParams="this"/> - - <!-- edit bean --> - <VesselDto id='bean'/> - - <Table id="editView" insets="0" fill="both"> - <row> - <cell anchor="north" weightx="1"> - <JTabbedPane id='tabPane'> - <tab id='generalTab'> - <Table fill="both"> - - <!-- keelCode / fleetCountry --> - <row> - <cell anchor="west"> - <JLabel id='keelCodeFlotteLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel layout='{new GridLayout()}'> - <NumberEditor id='keelCode' constructorParams='this' styleClass="integer"/> - <NumberEditor id='fleetCountry' constructorParams='this' styleClass="integer"/> - </JPanel> - </cell> - </row> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' constructorParams='ReferenceStatus.class' genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- vesselType --> - <row> - <cell anchor='west'> - <JLabel id='vesselTypeLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='vesselType' constructorParams='this' genericType='ReferentialReference<VesselTypeDto>' _entityClass='VesselTypeDto.class'/> - </cell> - </row> - - <!-- vesselSizeCategory --> - <row> - <cell anchor='west'> - <JLabel id='vesselSizeCategoryLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='vesselSizeCategory' constructorParams='this' genericType='ReferentialReference<VesselSizeCategoryDto>' _entityClass='VesselSizeCategoryDto.class'/> - </cell> - </row> - - <!-- flagCountry --> - <row> - <cell anchor='west'> - <JLabel id='flagCountryLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='flagCountry' constructorParams='this' genericType='ReferentialReference<CountryDto>' _entityClass='CountryDto.class'/> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - <row> - <cell columns="2"> - <Table id='editI18nTable2'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> - </cell> - </row> - <row> - <cell columns="2" weighty="1"> - <JLabel/> - </cell> - </row> - </Table> - </tab> - - <tab id='otherTab'> - <Table fill="both"> - <!-- length --> - <row> - <cell anchor="west"> - <JLabel id='lengthLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <NumberEditor id='length' constructorParams='this' styleClass="float2"/> - </cell> - </row> - - <!-- capacity --> - <row> - <cell anchor="west"> - <JLabel id='capacityLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <NumberEditor id='capacity' constructorParams='this' styleClass="float2"/> - </cell> - </row> - - <!-- power --> - <row> - <cell anchor="west"> - <JLabel id='powerLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <NumberEditor id='power' constructorParams='this' styleClass="integer"/> - </cell> - </row> - - <!-- searchMaximum --> - <row> - <cell anchor="west"> - <JLabel id='searchMaximumLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <NumberEditor id='searchMaximum' constructorParams='this' styleClass="float2"/> - </cell> - </row> - - <!-- yearService --> - <row> - <cell anchor="west"> - <JLabel id='yearServiceLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <NumberEditor id='yearService' constructorParams='this' styleClass="integer"/> - </cell> - </row> - - <!-- changeDate --> - <row> - <cell anchor='west'> - <JLabel id='changeDateLabel'/> - </cell> - <cell anchor='west'> - <JXDatePicker id='changeDate' onActionPerformed='getBean().setChangeDate(changeDate.getDate())'/> - </cell> - </row> - <row> - <cell columns="2" weighty="1"> - <JLabel/> - </cell> - </row> - </Table> - </tab> - </JTabbedPane> - </cell> - </row> - <row> - <cell columns="2" weighty="1"> - <JLabel/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselUIHandler.java deleted file mode 100644 index f00cb0e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselUIHandler.java +++ /dev/null @@ -1,102 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.VesselDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUI; -import fr.ird.observe.ui.content.ref.ContentReferenceUIHandler; -import jaxx.runtime.validator.swing.SwingValidatorMessage; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.event.TableModelListener; -import java.util.HashSet; -import java.util.Set; - -/** - * Created on 1/11/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.11 - */ -public class VesselUIHandler extends ContentReferenceUIHandler<VesselDto> { - - // Compute valid state of tab from the error table - protected final TableModelListener computeTabValidStateListener; - - public VesselUIHandler(ContentReferenceUI<VesselDto> ui) { - super(ui); - computeTabValidStateListener = e -> { - - SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); - computeTabValidState(source); - - }; - } - - @Override - public void initUI() { - - super.initUI(); - - // To be sure always remove listener (could prevent some leaks) - getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); - // listen messages to see if required to add - getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); - - } - - @Override - public void selectBean(ReferentialReference<VesselDto> selectedBean) { - - super.selectBean(selectedBean); - - SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); - computeTabValidState(errorTableModel); - - ((VesselUI) getUi()).getTabPane().setSelectedIndex(0); - - } - - protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { - - Set<String> errorProperties = new HashSet<>(); - int rowCount = errorTableModel.getRowCount(); - for (int i = 0; i < rowCount; i++) { - - SwingValidatorMessage row = errorTableModel.getRow(i); - if (NuitonValidatorScope.ERROR.equals(row.getScope())) { - errorProperties.add(row.getField()); - } - } - - boolean generalTabValid = !errorProperties.removeAll(VesselUIModel.GENERAL_TAB_PROPERTIES); - boolean otherTabValid = !errorProperties.removeAll(VesselUIModel.OTHER_TAB_PROPERTIES); - - VesselUIModel model = (VesselUIModel) getModel(); - model.setGeneralTabValid(generalTabValid); - model.setOtherTabValid(otherTabValid); - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselUIModel.java deleted file mode 100644 index 58d8e6c..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/VesselUIModel.java +++ /dev/null @@ -1,126 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.ImmutableSet; -import fr.ird.observe.services.dto.referential.VesselDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -import java.util.Set; - -/** - * Created on 9/27/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class VesselUIModel extends ContentReferenceUIModel<VesselDto> { - - public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; - - public static final String PROPERTY_OTHER_TAB_VALID = "otherTabValid"; - - public static final Set<String> GENERAL_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(VesselDto.PROPERTY_URI, - VesselDto.PROPERTY_CODE, - VesselDto.PROPERTY_STATUS, - VesselDto.PROPERTY_KEEL_CODE, - VesselDto.PROPERTY_VESSEL_TYPE, - VesselDto.PROPERTY_VESSEL_SIZE_CATEGORY, - VesselDto.PROPERTY_NEED_COMMENT, - VesselDto.PROPERTY_FLAG_COUNTRY, - VesselDto.PROPERTY_FLEET_COUNTRY, - VesselDto.PROPERTY_LABEL1, - VesselDto.PROPERTY_LABEL2, - VesselDto.PROPERTY_LABEL3, - VesselDto.PROPERTY_LABEL4, - VesselDto.PROPERTY_LABEL5, - VesselDto.PROPERTY_LABEL6, - VesselDto.PROPERTY_LABEL7, - VesselDto.PROPERTY_LABEL8).build(); - - public static final Set<String> OTHER_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(VesselDto.PROPERTY_CAPACITY, - VesselDto.PROPERTY_CHANGE_DATE, - VesselDto.PROPERTY_COMMENT, - VesselDto.PROPERTY_LENGTH, - VesselDto.PROPERTY_LENGTH, - VesselDto.PROPERTY_POWER, - VesselDto.PROPERTY_SEARCH_MAXIMUM, - VesselDto.PROPERTY_YEAR_SERVICE).build(); - - private static final long serialVersionUID = 1L; - - protected boolean generalTabValid; - - protected boolean otherTabValid; - - public VesselUIModel() { - super(VesselDto.class, - new String[]{ - VesselDto.PROPERTY_VESSEL_TYPE, - VesselDto.PROPERTY_VESSEL_SIZE_CATEGORY, - VesselDto.PROPERTY_FLAG_COUNTRY, - VesselDto.PROPERTY_KEEL_CODE, - VesselDto.PROPERTY_FLEET_COUNTRY, - VesselDto.PROPERTY_YEAR_SERVICE, - VesselDto.PROPERTY_LENGTH, - VesselDto.PROPERTY_CAPACITY, - VesselDto.PROPERTY_POWER, - VesselDto.PROPERTY_SEARCH_MAXIMUM, - VesselDto.PROPERTY_CHANGE_DATE}, - new String[]{VesselUI.BINDING_VESSEL_TYPE_SELECTED_ITEM, - VesselUI.BINDING_VESSEL_SIZE_CATEGORY_SELECTED_ITEM, - VesselUI.BINDING_FLAG_COUNTRY_SELECTED_ITEM, - VesselUI.BINDING_KEEL_CODE_MODEL, - VesselUI.BINDING_FLEET_COUNTRY_MODEL, - VesselUI.BINDING_YEAR_SERVICE_MODEL, - VesselUI.BINDING_LENGTH_MODEL, - VesselUI.BINDING_CAPACITY_MODEL, - VesselUI.BINDING_POWER_MODEL, - VesselUI.BINDING_SEARCH_MAXIMUM_MODEL, - VesselUI.BINDING_CHANGE_DATE_DATE} - ); - } - - public boolean isOtherTabValid() { - return otherTabValid; - } - - public void setOtherTabValid(boolean otherTabValid) { - Object oldValue = isOtherTabValid(); - this.otherTabValid = otherTabValid; - firePropertyChange(PROPERTY_OTHER_TAB_VALID, oldValue, otherTabValid); - } - - public boolean isGeneralTabValid() { - return generalTabValid; - } - - public void setGeneralTabValid(boolean generalTabValid) { - Object oldValue = isGeneralTabValid(); - this.generalTabValid = generalTabValid; - firePropertyChange(PROPERTY_GENERAL_TAB_VALID, oldValue, generalTabValid); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/BaitHaulingStatusUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/BaitHaulingStatusUI.jaxx deleted file mode 100644 index 4b49951..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/BaitHaulingStatusUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='BaitHaulingStatusDto' - contentTitle='{n("observe.content.title.baitHaulingStatuss")}' - listText='{n("observe.content.list.baitHaulingStatus")}' - createToolTip='{n("observe.content.action.baitHaulingStatus.create.tip")}' - detailToolTip='{n("observe.content.action.baitHaulingStatus.detail.tip")}' - modifyToolTip='{n("observe.content.action.baitHaulingStatus.modify.tip")}' - deleteToolTip='{n("observe.content.action.baitHaulingStatus.delete.tip")}' - saveToolTip='{n("observe.content.action.baitHaulingStatus.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.BaitHaulingStatusDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.BaitHaulingStatusDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <BaitHaulingStatusUIModel id='model'/> - - <!-- edit bean --> - <BaitHaulingStatusDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/BaitHaulingStatusUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/BaitHaulingStatusUIModel.java deleted file mode 100644 index aabe2b5..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/BaitHaulingStatusUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.BaitHaulingStatusDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class BaitHaulingStatusUIModel extends ContentReferenceUIModel<BaitHaulingStatusDto> { - - private static final long serialVersionUID = 1L; - - public BaitHaulingStatusUIModel() { - super(BaitHaulingStatusDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/BaitSettingStatusUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/BaitSettingStatusUI.jaxx deleted file mode 100644 index f587028..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/BaitSettingStatusUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='BaitSettingStatusDto' - contentTitle='{n("observe.content.title.baitSettingStatuss")}' - listText='{n("observe.content.list.baitSettingStatus")}' - createToolTip='{n("observe.content.action.baitSettingStatus.create.tip")}' - detailToolTip='{n("observe.content.action.baitSettingStatus.detail.tip")}' - modifyToolTip='{n("observe.content.action.baitSettingStatus.modify.tip")}' - deleteToolTip='{n("observe.content.action.baitSettingStatus.delete.tip")}' - saveToolTip='{n("observe.content.action.baitSettingStatus.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.BaitSettingStatusDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.BaitSettingStatusDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <BaitSettingStatusUIModel id='model'/> - - <!-- edit bean --> - <BaitSettingStatusDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/BaitSettingStatusUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/BaitSettingStatusUIModel.java deleted file mode 100644 index d448137..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/BaitSettingStatusUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.BaitSettingStatusDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class BaitSettingStatusUIModel extends ContentReferenceUIModel<BaitSettingStatusDto> { - - private static final long serialVersionUID = 1L; - - public BaitSettingStatusUIModel() { - super(BaitSettingStatusDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/BaitTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/BaitTypeUI.jaxx deleted file mode 100644 index b080fff..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/BaitTypeUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='BaitTypeDto' - contentTitle='{n("observe.content.title.baitTypes")}' - listText='{n("observe.content.list.baitType")}' - createToolTip='{n("observe.content.action.baitType.create.tip")}' - detailToolTip='{n("observe.content.action.baitType.detail.tip")}' - modifyToolTip='{n("observe.content.action.baitType.modify.tip")}' - deleteToolTip='{n("observe.content.action.baitType.delete.tip")}' - saveToolTip='{n("observe.content.action.baitType.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.BaitTypeDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.BaitTypeDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <BaitTypeUIModel id='model'/> - - <!-- edit bean --> - <BaitTypeDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/BaitTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/BaitTypeUIModel.java deleted file mode 100644 index dca3c33..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/BaitTypeUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.BaitTypeDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class BaitTypeUIModel extends ContentReferenceUIModel<BaitTypeDto> { - - private static final long serialVersionUID = 1L; - - public BaitTypeUIModel() { - super(BaitTypeDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/CatchFateLonglineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/CatchFateLonglineUI.jaxx deleted file mode 100644 index 13d13e2..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/CatchFateLonglineUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='CatchFateLonglineDto' - contentTitle='{n("observe.content.title.catchFateLonglines")}' - listText='{n("observe.content.list.catchFateLongline")}' - createToolTip='{n("observe.content.action.catchFateLongline.create.tip")}' - detailToolTip='{n("observe.content.action.catchFateLongline.detail.tip")}' - modifyToolTip='{n("observe.content.action.catchFateLongline.modify.tip")}' - deleteToolTip='{n("observe.content.action.catchFateLongline.delete.tip")}' - saveToolTip='{n("observe.content.action.catchFateLongline.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.CatchFateLonglineDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.CatchFateLonglineDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <CatchFateLonglineUIModel id='model'/> - - <!-- edit bean --> - <CatchFateLonglineDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/CatchFateLonglineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/CatchFateLonglineUIModel.java deleted file mode 100644 index 5a15cb2..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/CatchFateLonglineUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.CatchFateLonglineDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class CatchFateLonglineUIModel extends ContentReferenceUIModel<CatchFateLonglineDto> { - - private static final long serialVersionUID = 1L; - - public CatchFateLonglineUIModel() { - super(CatchFateLonglineDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/EncounterTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/EncounterTypeUI.jaxx deleted file mode 100644 index 656f332..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/EncounterTypeUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='EncounterTypeDto' - contentTitle='{n("observe.content.title.encounterTypes")}' - listText='{n("observe.content.list.encounterType")}' - createToolTip='{n("observe.content.action.encounterType.create.tip")}' - detailToolTip='{n("observe.content.action.encounterType.detail.tip")}' - modifyToolTip='{n("observe.content.action.encounterType.modify.tip")}' - deleteToolTip='{n("observe.content.action.encounterType.delete.tip")}' - saveToolTip='{n("observe.content.action.encounterType.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.EncounterTypeDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.EncounterTypeDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <EncounterTypeUIModel id='model'/> - - <!-- edit bean --> - <EncounterTypeDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/EncounterTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/EncounterTypeUIModel.java deleted file mode 100644 index 2ee2e64..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/EncounterTypeUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.EncounterTypeDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class EncounterTypeUIModel extends ContentReferenceUIModel<EncounterTypeDto> { - - private static final long serialVersionUID = 1L; - - public EncounterTypeUIModel() { - super(EncounterTypeDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HealthnessUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HealthnessUI.jaxx deleted file mode 100644 index 4475ee3..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HealthnessUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='HealthnessDto' - contentTitle='{n("observe.content.title.healthnesss")}' - listText='{n("observe.content.list.healthness")}' - createToolTip='{n("observe.content.action.healthness.create.tip")}' - detailToolTip='{n("observe.content.action.healthness.detail.tip")}' - modifyToolTip='{n("observe.content.action.healthness.modify.tip")}' - deleteToolTip='{n("observe.content.action.healthness.delete.tip")}' - saveToolTip='{n("observe.content.action.healthness.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.HealthnessDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.HealthnessDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <HealthnessUIModel id='model'/> - - <!-- edit bean --> - <HealthnessDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HealthnessUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HealthnessUIModel.java deleted file mode 100644 index 944a9eb..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HealthnessUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.HealthnessDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class HealthnessUIModel extends ContentReferenceUIModel<HealthnessDto> { - - private static final long serialVersionUID = 1L; - - public HealthnessUIModel() { - super(HealthnessDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HookPositionUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HookPositionUI.jaxx deleted file mode 100644 index 2d0420a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HookPositionUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='HookPositionDto' - contentTitle='{n("observe.content.title.hookPositions")}' - listText='{n("observe.content.list.hookPosition")}' - createToolTip='{n("observe.content.action.hookPosition.create.tip")}' - detailToolTip='{n("observe.content.action.hookPosition.detail.tip")}' - modifyToolTip='{n("observe.content.action.hookPosition.modify.tip")}' - deleteToolTip='{n("observe.content.action.hookPosition.delete.tip")}' - saveToolTip='{n("observe.content.action.hookPosition.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.HookPositionDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.HookPositionDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <HookPositionUIModel id='model'/> - - <!-- edit bean --> - <HookPositionDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HookPositionUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HookPositionUIModel.java deleted file mode 100644 index 3f6385a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HookPositionUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.HookPositionDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class HookPositionUIModel extends ContentReferenceUIModel<HookPositionDto> { - - private static final long serialVersionUID = 1L; - - public HookPositionUIModel() { - super(HookPositionDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HookSizeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HookSizeUI.jaxx deleted file mode 100644 index 7d326ee..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HookSizeUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='HookSizeDto' - contentTitle='{n("observe.content.title.HookSizes")}' - listText='{n("observe.content.list.HookSize")}' - createToolTip='{n("observe.content.action.hookSize.create.tip")}' - detailToolTip='{n("observe.content.action.hookSize.detail.tip")}' - modifyToolTip='{n("observe.content.action.hookSize.modify.tip")}' - deleteToolTip='{n("observe.content.action.hookSize.delete.tip")}' - saveToolTip='{n("observe.content.action.hookSize.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.HookSizeDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.HookSizeDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <HookSizeUIModel id='model'/> - - <!-- edit bean --> - <HookSizeDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HookSizeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HookSizeUIModel.java deleted file mode 100644 index e5f584e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HookSizeUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.HookSizeDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class HookSizeUIModel extends ContentReferenceUIModel<HookSizeDto> { - - private static final long serialVersionUID = 1L; - - public HookSizeUIModel() { - super(HookSizeDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HookTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HookTypeUI.jaxx deleted file mode 100644 index f9b5af7..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HookTypeUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='HookTypeDto' - contentTitle='{n("observe.content.title.HookTypes")}' - listText='{n("observe.content.list.HookType")}' - createToolTip='{n("observe.content.action.hookType.create.tip")}' - detailToolTip='{n("observe.content.action.hookType.detail.tip")}' - modifyToolTip='{n("observe.content.action.hookType.modify.tip")}' - deleteToolTip='{n("observe.content.action.hookType.delete.tip")}' - saveToolTip='{n("observe.content.action.hookType.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.HookTypeDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.HookTypeDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <HookTypeUIModel id='model'/> - - <!-- edit bean --> - <HookTypeDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HookTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HookTypeUIModel.java deleted file mode 100644 index 1a968a9..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/HookTypeUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.HookTypeDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class HookTypeUIModel extends ContentReferenceUIModel<HookTypeDto> { - - private static final long serialVersionUID = 1L; - - public HookTypeUIModel() { - super(HookTypeDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/ItemHorizontalPositionUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/ItemHorizontalPositionUI.jaxx deleted file mode 100644 index af84eb4..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/ItemHorizontalPositionUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='ItemHorizontalPositionDto' - contentTitle='{n("observe.content.title.itemHorizontalPositions")}' - listText='{n("observe.content.list.itemHorizontalPosition")}' - createToolTip='{n("observe.content.action.itemHorizontalPosition.create.tip")}' - detailToolTip='{n("observe.content.action.itemHorizontalPosition.detail.tip")}' - modifyToolTip='{n("observe.content.action.itemHorizontalPosition.modify.tip")}' - deleteToolTip='{n("observe.content.action.itemHorizontalPosition.delete.tip")}' - saveToolTip='{n("observe.content.action.itemHorizontalPosition.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.ItemHorizontalPositionDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.ItemHorizontalPositionDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <ItemHorizontalPositionUIModel id='model'/> - - <!-- edit bean --> - <ItemHorizontalPositionDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/ItemHorizontalPositionUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/ItemHorizontalPositionUIModel.java deleted file mode 100644 index 0f6633a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/ItemHorizontalPositionUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.ItemHorizontalPositionDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ItemHorizontalPositionUIModel extends ContentReferenceUIModel<ItemHorizontalPositionDto> { - - private static final long serialVersionUID = 1L; - - public ItemHorizontalPositionUIModel() { - super(ItemHorizontalPositionDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/ItemVerticalPositionUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/ItemVerticalPositionUI.jaxx deleted file mode 100644 index 6891778..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/ItemVerticalPositionUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='ItemVerticalPositionDto' - contentTitle='{n("observe.content.title.itemVerticalPositions")}' - listText='{n("observe.content.list.itemVerticalPosition")}' - createToolTip='{n("observe.content.action.itemVerticalPosition.create.tip")}' - detailToolTip='{n("observe.content.action.itemVerticalPosition.detail.tip")}' - modifyToolTip='{n("observe.content.action.itemVerticalPosition.modify.tip")}' - deleteToolTip='{n("observe.content.action.itemVerticalPosition.delete.tip")}' - saveToolTip='{n("observe.content.action.itemVerticalPosition.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.ItemVerticalPositionDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.ItemVerticalPositionDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <ItemVerticalPositionUIModel id='model'/> - - <!-- edit bean --> - <ItemVerticalPositionDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/ItemVerticalPositionUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/ItemVerticalPositionUIModel.java deleted file mode 100644 index 8277ad9..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/ItemVerticalPositionUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.ItemVerticalPositionDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ItemVerticalPositionUIModel extends ContentReferenceUIModel<ItemVerticalPositionDto> { - - private static final long serialVersionUID = 1L; - - public ItemVerticalPositionUIModel() { - super(ItemVerticalPositionDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/LightsticksColorUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/LightsticksColorUI.jaxx deleted file mode 100644 index 70ebdbe..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/LightsticksColorUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='LightsticksColorDto' - contentTitle='{n("observe.content.title.lightsticksColors")}' - listText='{n("observe.content.list.lightsticksColor")}' - createToolTip='{n("observe.content.action.lightsticksColor.create.tip")}' - detailToolTip='{n("observe.content.action.lightsticksColor.detail.tip")}' - modifyToolTip='{n("observe.content.action.lightsticksColor.modify.tip")}' - deleteToolTip='{n("observe.content.action.lightsticksColor.delete.tip")}' - saveToolTip='{n("observe.content.action.lightsticksColor.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.LightsticksColorDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.LightsticksColorDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <LightsticksColorUIModel id='model'/> - - <!-- edit bean --> - <LightsticksColorDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/LightsticksColorUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/LightsticksColorUIModel.java deleted file mode 100644 index 153f618..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/LightsticksColorUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.LightsticksColorDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class LightsticksColorUIModel extends ContentReferenceUIModel<LightsticksColorDto> { - - private static final long serialVersionUID = 1L; - - public LightsticksColorUIModel() { - super(LightsticksColorDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/LightsticksTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/LightsticksTypeUI.jaxx deleted file mode 100644 index b352603..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/LightsticksTypeUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='LightsticksTypeDto' - contentTitle='{n("observe.content.title.lightsticksTypes")}' - listText='{n("observe.content.list.lightsticksType")}' - createToolTip='{n("observe.content.action.lightsticksType.create.tip")}' - detailToolTip='{n("observe.content.action.lightsticksType.detail.tip")}' - modifyToolTip='{n("observe.content.action.lightsticksType.modify.tip")}' - deleteToolTip='{n("observe.content.action.lightsticksType.delete.tip")}' - saveToolTip='{n("observe.content.action.lightsticksType.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.LightsticksTypeDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.LightsticksTypeDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <LightsticksTypeUIModel id='model'/> - - <!-- edit bean --> - <LightsticksTypeDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/LightsticksTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/LightsticksTypeUIModel.java deleted file mode 100644 index a08ffe4..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/LightsticksTypeUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.LightsticksTypeDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class LightsticksTypeUIModel extends ContentReferenceUIModel<LightsticksTypeDto> { - - private static final long serialVersionUID = 1L; - - public LightsticksTypeUIModel() { - super(LightsticksTypeDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/LineTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/LineTypeUI.jaxx deleted file mode 100644 index 870addf..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/LineTypeUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='LineTypeDto' - contentTitle='{n("observe.content.title.lineTypes")}' - listText='{n("observe.content.list.lineType")}' - createToolTip='{n("observe.content.action.lineType.create.tip")}' - detailToolTip='{n("observe.content.action.lineType.detail.tip")}' - modifyToolTip='{n("observe.content.action.lineType.modify.tip")}' - deleteToolTip='{n("observe.content.action.lineType.delete.tip")}' - saveToolTip='{n("observe.content.action.lineType.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.LineTypeDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.LineTypeDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <LineTypeUIModel id='model'/> - - <!-- edit bean --> - <LineTypeDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/LineTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/LineTypeUIModel.java deleted file mode 100644 index b3e4355..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/LineTypeUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.LineTypeDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class LineTypeUIModel extends ContentReferenceUIModel<LineTypeDto> { - - private static final long serialVersionUID = 1L; - - public LineTypeUIModel() { - super(LineTypeDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/MaturityStatusUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/MaturityStatusUI.jaxx deleted file mode 100644 index bab2072..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/MaturityStatusUI.jaxx +++ /dev/null @@ -1,179 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='MaturityStatusDto' - contentTitle='{n("observe.content.title.maturityStatuss")}' - listText='{n("observe.content.list.maturityStatus")}' - createToolTip='{n("observe.content.action.maturityStatus.create.tip")}' - detailToolTip='{n("observe.content.action.maturityStatus.detail.tip")}' - modifyToolTip='{n("observe.content.action.maturityStatus.modify.tip")}' - deleteToolTip='{n("observe.content.action.maturityStatus.delete.tip")}' - saveToolTip='{n("observe.content.action.maturityStatus.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.MaturityStatusDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.MaturityStatusDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <MaturityStatusUIModel id='model'/> - - <!-- edit bean --> - <MaturityStatusDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- lowerValue / upperValue --> - <row> - <cell anchor="west"> - <JLabel id='lowerValueUpperValueLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='lowerValueUpperValuePanel' layout='{new GridLayout()}'> - <JTextField id='lowerValue' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setLowerValue(lowerValue.getText())'/> - <JTextField id='upperValue' - onKeyReleased='getBean().setUpperValue(upperValue.getText())'/> - </JPanel> - - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/MaturityStatusUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/MaturityStatusUIModel.java deleted file mode 100644 index ed86bb8..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/MaturityStatusUIModel.java +++ /dev/null @@ -1,45 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.MaturityStatusDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class MaturityStatusUIModel extends ContentReferenceUIModel<MaturityStatusDto> { - - private static final long serialVersionUID = 1L; - - public MaturityStatusUIModel() { - super(MaturityStatusDto.class, - new String[]{MaturityStatusDto.PROPERTY_LOWER_VALUE, MaturityStatusDto.PROPERTY_UPPER_VALUE}, - new String[]{MaturityStatusUI.BINDING_LOWER_VALUE_TEXT, MaturityStatusUI.BINDING_UPPER_VALUE_TEXT} - ); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/MitigationTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/MitigationTypeUI.jaxx deleted file mode 100644 index 192189e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/MitigationTypeUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='MitigationTypeDto' - contentTitle='{n("observe.content.title.mitigationTypes")}' - listText='{n("observe.content.list.mitigationType")}' - createToolTip='{n("observe.content.action.mitigationType.create.tip")}' - detailToolTip='{n("observe.content.action.mitigationType.detail.tip")}' - modifyToolTip='{n("observe.content.action.mitigationType.modify.tip")}' - deleteToolTip='{n("observe.content.action.mitigationType.delete.tip")}' - saveToolTip='{n("observe.content.action.mitigationType.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.MitigationTypeDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.MitigationTypeDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <MitigationTypeUIModel id='model'/> - - <!-- edit bean --> - <MitigationTypeDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/MitigationTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/MitigationTypeUIModel.java deleted file mode 100644 index f7bb86c..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/MitigationTypeUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.MitigationTypeDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class MitigationTypeUIModel extends ContentReferenceUIModel<MitigationTypeDto> { - - private static final long serialVersionUID = 1L; - - public MitigationTypeUIModel() { - super(MitigationTypeDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SensorBrandUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SensorBrandUI.jaxx deleted file mode 100644 index 2cd615a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SensorBrandUI.jaxx +++ /dev/null @@ -1,108 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='SensorBrandDto' - contentTitle='{n("observe.content.title.sensorBrands")}' - listText='{n("observe.content.list.sensorBrand")}' - createToolTip='{n("observe.content.action.sensorBrand.create.tip")}' - detailToolTip='{n("observe.content.action.sensorBrand.detail.tip")}' - modifyToolTip='{n("observe.content.action.sensorBrand.modify.tip")}' - deleteToolTip='{n("observe.content.action.sensorBrand.delete.tip")}' - saveToolTip='{n("observe.content.action.sensorBrand.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.SensorBrandDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.SensorBrandDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <SensorBrandUIModel id='model'/> - - <!-- edit bean --> - <SensorBrandDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- brandName --> - <row> - <cell anchor="west"> - <JLabel id='brandNameLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='brandName' - onKeyReleased='getBean().setBrandName(brandName.getText())'/> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SensorBrandUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SensorBrandUIModel.java deleted file mode 100644 index 09c1742..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SensorBrandUIModel.java +++ /dev/null @@ -1,45 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.SensorBrandDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class SensorBrandUIModel extends ContentReferenceUIModel<SensorBrandDto> { - - private static final long serialVersionUID = 1L; - - public SensorBrandUIModel() { - super(SensorBrandDto.class, - new String[]{SensorBrandDto.PROPERTY_BRAND_NAME}, - new String[]{SensorBrandUI.BINDING_BRAND_NAME_TEXT} - ); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SensorDataFormatUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SensorDataFormatUI.jaxx deleted file mode 100644 index 3d67eb5..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SensorDataFormatUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='SensorDataFormatDto' - contentTitle='{n("observe.content.title.sensorDataFormats")}' - listText='{n("observe.content.list.sensorDataFormat")}' - createToolTip='{n("observe.content.action.sensorDataFormat.create.tip")}' - detailToolTip='{n("observe.content.action.sensorDataFormat.detail.tip")}' - modifyToolTip='{n("observe.content.action.sensorDataFormat.modify.tip")}' - deleteToolTip='{n("observe.content.action.sensorDataFormat.delete.tip")}' - saveToolTip='{n("observe.content.action.sensorDataFormat.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.SensorDataFormatDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.SensorDataFormatDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <SensorDataFormatUIModel id='model'/> - - <!-- edit bean --> - <SensorDataFormatDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SensorDataFormatUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SensorDataFormatUIModel.java deleted file mode 100644 index e495d99..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SensorDataFormatUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.SensorDataFormatDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class SensorDataFormatUIModel extends ContentReferenceUIModel<SensorDataFormatDto> { - - private static final long serialVersionUID = 1L; - - public SensorDataFormatUIModel() { - super(SensorDataFormatDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SensorTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SensorTypeUI.jaxx deleted file mode 100644 index 7d5aa35..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SensorTypeUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='SensorTypeDto' - contentTitle='{n("observe.content.title.sensorTypes")}' - listText='{n("observe.content.list.sensorType")}' - createToolTip='{n("observe.content.action.sensorType.create.tip")}' - detailToolTip='{n("observe.content.action.sensorType.detail.tip")}' - modifyToolTip='{n("observe.content.action.sensorType.modify.tip")}' - deleteToolTip='{n("observe.content.action.sensorType.delete.tip")}' - saveToolTip='{n("observe.content.action.sensorType.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.SensorTypeDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.SensorTypeDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <SensorTypeUIModel id='model'/> - - <!-- edit bean --> - <SensorTypeDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SensorTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SensorTypeUIModel.java deleted file mode 100644 index ce9199b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SensorTypeUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.SensorTypeDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class SensorTypeUIModel extends ContentReferenceUIModel<SensorTypeDto> { - - private static final long serialVersionUID = 1L; - - public SensorTypeUIModel() { - super(SensorTypeDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SettingShapeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SettingShapeUI.jaxx deleted file mode 100644 index 3fc8a42..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SettingShapeUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='SettingShapeDto' - contentTitle='{n("observe.content.title.settingShapes")}' - listText='{n("observe.content.list.settingShape")}' - createToolTip='{n("observe.content.action.settingShape.create.tip")}' - detailToolTip='{n("observe.content.action.settingShape.detail.tip")}' - modifyToolTip='{n("observe.content.action.settingShape.modify.tip")}' - deleteToolTip='{n("observe.content.action.settingShape.delete.tip")}' - saveToolTip='{n("observe.content.action.settingShape.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.SettingShapeDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.SettingShapeDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <SettingShapeUIModel id='model'/> - - <!-- edit bean --> - <SettingShapeDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SettingShapeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SettingShapeUIModel.java deleted file mode 100644 index 42d65f6..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SettingShapeUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.SettingShapeDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class SettingShapeUIModel extends ContentReferenceUIModel<SettingShapeDto> { - - private static final long serialVersionUID = 1L; - - public SettingShapeUIModel() { - super(SettingShapeDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SizeMeasureTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SizeMeasureTypeUI.jaxx deleted file mode 100644 index 40a8e02..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SizeMeasureTypeUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='SizeMeasureTypeDto' - contentTitle='{n("observe.content.title.sizeMeasureTypes")}' - listText='{n("observe.content.list.sizeMeasureType")}' - createToolTip='{n("observe.content.action.sizeMeasureType.create.tip")}' - detailToolTip='{n("observe.content.action.sizeMeasureType.detail.tip")}' - modifyToolTip='{n("observe.content.action.sizeMeasureType.modify.tip")}' - deleteToolTip='{n("observe.content.action.sizeMeasureType.delete.tip")}' - saveToolTip='{n("observe.content.action.sizeMeasureType.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.SizeMeasureTypeDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.SizeMeasureTypeDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <SizeMeasureTypeUIModel id='model'/> - - <!-- edit bean --> - <SizeMeasureTypeDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SizeMeasureTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SizeMeasureTypeUIModel.java deleted file mode 100644 index 3aab59b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/SizeMeasureTypeUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.SizeMeasureTypeDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class SizeMeasureTypeUIModel extends ContentReferenceUIModel<SizeMeasureTypeDto> { - - private static final long serialVersionUID = 1L; - - public SizeMeasureTypeUIModel() { - super(SizeMeasureTypeDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/StomacFullnessUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/StomacFullnessUI.jaxx deleted file mode 100644 index 999ba74..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/StomacFullnessUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='StomacFullnessDto' - contentTitle='{n("observe.content.title.stomacFullnesss")}' - listText='{n("observe.content.list.stomacFullness")}' - createToolTip='{n("observe.content.action.stomacFullness.create.tip")}' - detailToolTip='{n("observe.content.action.stomacFullness.detail.tip")}' - modifyToolTip='{n("observe.content.action.stomacFullness.modify.tip")}' - deleteToolTip='{n("observe.content.action.stomacFullness.delete.tip")}' - saveToolTip='{n("observe.content.action.stomacFullness.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.StomacFullnessDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.StomacFullnessDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <StomacFullnessUIModel id='model'/> - - <!-- edit bean --> - <StomacFullnessDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/StomacFullnessUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/StomacFullnessUIModel.java deleted file mode 100644 index dbd5259..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/StomacFullnessUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.StomacFullnessDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class StomacFullnessUIModel extends ContentReferenceUIModel<StomacFullnessDto> { - - private static final long serialVersionUID = 1L; - - public StomacFullnessUIModel() { - super(StomacFullnessDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/TripTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/TripTypeUI.jaxx deleted file mode 100644 index 6866cfc..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/TripTypeUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='TripTypeDto' - contentTitle='{n("observe.content.title.tripTypes")}' - listText='{n("observe.content.list.tripType")}' - createToolTip='{n("observe.content.action.tripType.create.tip")}' - detailToolTip='{n("observe.content.action.tripType.detail.tip")}' - modifyToolTip='{n("observe.content.action.tripType.modify.tip")}' - deleteToolTip='{n("observe.content.action.tripType.delete.tip")}' - saveToolTip='{n("observe.content.action.tripType.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.TripTypeDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.TripTypeDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <TripTypeUIModel id='model'/> - - <!-- edit bean --> - <TripTypeDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/TripTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/TripTypeUIModel.java deleted file mode 100644 index e3d3073..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/TripTypeUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.TripTypeDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class TripTypeUIModel extends ContentReferenceUIModel<TripTypeDto> { - - private static final long serialVersionUID = 1L; - - public TripTypeUIModel() { - super(TripTypeDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/VesselActivityLonglineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/VesselActivityLonglineUI.jaxx deleted file mode 100644 index a522d4a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/VesselActivityLonglineUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='VesselActivityLonglineDto' - contentTitle='{n("observe.content.title.vesselActivityLonglines")}' - listText='{n("observe.content.list.vesselActivityLongline")}' - createToolTip='{n("observe.content.action.vesselActivityLongline.create.tip")}' - detailToolTip='{n("observe.content.action.vesselActivityLongline.detail.tip")}' - modifyToolTip='{n("observe.content.action.vesselActivityLongline.modify.tip")}' - deleteToolTip='{n("observe.content.action.vesselActivityLongline.delete.tip")}' - saveToolTip='{n("observe.content.action.vesselActivityLongline.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.VesselActivityLonglineDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.VesselActivityLonglineDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <VesselActivityLonglineUIModel id='model'/> - - <!-- edit bean --> - <VesselActivityLonglineDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/VesselActivityLonglineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/VesselActivityLonglineUIModel.java deleted file mode 100644 index c15b747..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/VesselActivityLonglineUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.VesselActivityLonglineDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class VesselActivityLonglineUIModel extends ContentReferenceUIModel<VesselActivityLonglineDto> { - - private static final long serialVersionUID = 1L; - - public VesselActivityLonglineUIModel() { - super(VesselActivityLonglineDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/WeightMeasureTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/WeightMeasureTypeUI.jaxx deleted file mode 100644 index f08503f..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/WeightMeasureTypeUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='WeightMeasureTypeDto' - contentTitle='{n("observe.content.title.weightMeasureTypes")}' - listText='{n("observe.content.list.weightMeasureType")}' - createToolTip='{n("observe.content.action.weightMeasureType.create.tip")}' - detailToolTip='{n("observe.content.action.weightMeasureType.detail.tip")}' - modifyToolTip='{n("observe.content.action.weightMeasureType.modify.tip")}' - deleteToolTip='{n("observe.content.action.weightMeasureType.delete.tip")}' - saveToolTip='{n("observe.content.action.weightMeasureType.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.longline.WeightMeasureTypeDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.longline.WeightMeasureTypeDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <WeightMeasureTypeUIModel id='model'/> - - <!-- edit bean --> - <WeightMeasureTypeDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/WeightMeasureTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/WeightMeasureTypeUIModel.java deleted file mode 100644 index 8bab194..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/longline/WeightMeasureTypeUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.longline.WeightMeasureTypeDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class WeightMeasureTypeUIModel extends ContentReferenceUIModel<WeightMeasureTypeDto> { - - private static final long serialVersionUID = 1L; - - public WeightMeasureTypeUIModel() { - super(WeightMeasureTypeDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/DetectionModeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/DetectionModeUI.jaxx deleted file mode 100644 index a11428a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/DetectionModeUI.jaxx +++ /dev/null @@ -1,164 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='DetectionModeDto' - contentTitle='{n("observe.content.title.detectionModes")}' - listText='{n("observe.content.list.detectionMode")}' - createToolTip='{n("observe.content.action.detectionMode.create.tip")}' - detailToolTip='{n("observe.content.action.detectionMode.detail.tip")}' - modifyToolTip='{n("observe.content.action.detectionMode.modify.tip")}' - deleteToolTip='{n("observe.content.action.detectionMode.delete.tip")}' - saveToolTip='{n("observe.content.action.detectionMode.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.seine.DetectionModeDto - - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.seine.DetectionModeDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <DetectionModeUIModel id='model'/> - - <!-- edit bean --> - <DetectionModeDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/DetectionModeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/DetectionModeUIModel.java deleted file mode 100644 index 04e6dfa..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/DetectionModeUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.seine.DetectionModeDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class DetectionModeUIModel extends ContentReferenceUIModel<DetectionModeDto> { - - private static final long serialVersionUID = 1L; - - public DetectionModeUIModel() { - super(DetectionModeDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObjectFateUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObjectFateUI.jaxx deleted file mode 100644 index de73a48..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObjectFateUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='ObjectFateDto' - contentTitle='{n("observe.content.title.objectFates")}' - listText='{n("observe.content.list.objectFate")}' - createToolTip='{n("observe.content.action.objectFate.create.tip")}' - detailToolTip='{n("observe.content.action.objectFate.detail.tip")}' - modifyToolTip='{n("observe.content.action.objectFate.modify.tip")}' - deleteToolTip='{n("observe.content.action.objectFate.delete.tip")}' - saveToolTip='{n("observe.content.action.objectFate.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.seine.ObjectFateDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.seine.ObjectFateDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <ObjectFateUIModel id='model'/> - - <!-- edit bean --> - <ObjectFateDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObjectFateUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObjectFateUIModel.java deleted file mode 100644 index e162d6d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObjectFateUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.seine.ObjectFateDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ObjectFateUIModel extends ContentReferenceUIModel<ObjectFateDto> { - - private static final long serialVersionUID = 1L; - - public ObjectFateUIModel() { - super(ObjectFateDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObjectOperationUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObjectOperationUI.jaxx deleted file mode 100644 index 83510cd..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObjectOperationUI.jaxx +++ /dev/null @@ -1,164 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='ObjectOperationDto' - contentTitle='{n("observe.content.title.objectOperations")}' - listText='{n("observe.content.list.objectOperation")}' - createToolTip='{n("observe.content.action.objectOperation.create.tip")}' - detailToolTip='{n("observe.content.action.objectOperation.detail.tip")}' - modifyToolTip='{n("observe.content.action.objectOperation.modify.tip")}' - deleteToolTip='{n("observe.content.action.objectOperation.delete.tip")}' - saveToolTip='{n("observe.content.action.objectOperation.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.seine.ObjectOperationDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.seine.ObjectOperationDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <ObjectOperationUIModel id='model'/> - - <!-- edit bean --> - <ObjectOperationDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' - onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObjectOperationUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObjectOperationUIModel.java deleted file mode 100644 index 3cb26a1..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObjectOperationUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.seine.ObjectOperationDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ObjectOperationUIModel extends ContentReferenceUIModel<ObjectOperationDto> { - - private static final long serialVersionUID = 1L; - - public ObjectOperationUIModel() { - super(ObjectOperationDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObjectTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObjectTypeUI.jaxx deleted file mode 100644 index 57267f6..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObjectTypeUI.jaxx +++ /dev/null @@ -1,164 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='ObjectTypeDto' - contentTitle='{n("observe.content.title.objectTypes")}' - listText='{n("observe.content.list.objectType")}' - createToolTip='{n("observe.content.action.objectType.create.tip")}' - detailToolTip='{n("observe.content.action.objectType.detail.tip")}' - modifyToolTip='{n("observe.content.action.objectType.modify.tip")}' - deleteToolTip='{n("observe.content.action.objectType.delete.tip")}' - saveToolTip='{n("observe.content.action.objectType.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.seine.ObjectTypeDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.seine.ObjectTypeDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <ObjectTypeUIModel id='model'/> - - <!-- edit bean --> - <ObjectTypeDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObjectTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObjectTypeUIModel.java deleted file mode 100644 index cf2c15d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObjectTypeUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.seine.ObjectTypeDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ObjectTypeUIModel extends ContentReferenceUIModel<ObjectTypeDto> { - - private static final long serialVersionUID = 1L; - - public ObjectTypeUIModel() { - super(ObjectTypeDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObservedSystemUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObservedSystemUI.jaxx deleted file mode 100644 index 372c95c..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObservedSystemUI.jaxx +++ /dev/null @@ -1,176 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='ObservedSystemDto' - contentTitle='{n("observe.content.title.observedSystems")}' - listText='{n("observe.content.list.observedSystem")}' - createToolTip='{n("observe.content.action.observedSystem.create.tip")}' - detailToolTip='{n("observe.content.action.observedSystem.detail.tip")}' - modifyToolTip='{n("observe.content.action.observedSystem.modify.tip")}' - deleteToolTip='{n("observe.content.action.observedSystem.delete.tip")}' - saveToolTip='{n("observe.content.action.observedSystem.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.constants.seine.SchoolType - fr.ird.observe.services.dto.referential.seine.ObservedSystemDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.seine.ObservedSystemDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <fr.ird.observe.ui.content.ref.impl.seine.ObservedSystemUIModel id='model'/> - - <!-- edit bean --> - <ObservedSystemDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- schoolType --> - <row> - <cell anchor='west'> - <JLabel id='schoolTypeLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <EnumEditor id='schoolType' constructorParams='SchoolType.class' - genericType='SchoolType' - onItemStateChanged='getBean().setSchoolType((SchoolType)schoolType.getSelectedItem())'/> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObservedSystemUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObservedSystemUIModel.java deleted file mode 100644 index 9c73aae..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ObservedSystemUIModel.java +++ /dev/null @@ -1,45 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.seine.ObservedSystemDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ObservedSystemUIModel extends ContentReferenceUIModel<ObservedSystemDto> { - - private static final long serialVersionUID = 1L; - - public ObservedSystemUIModel() { - super(ObservedSystemDto.class, - new String[]{ObservedSystemDto.PROPERTY_SCHOOL_TYPE}, - new String[]{ObservedSystemUI.BINDING_SCHOOL_TYPE_SELECTED_ITEM} - ); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ReasonForDiscardUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ReasonForDiscardUI.jaxx deleted file mode 100644 index b3d8b04..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ReasonForDiscardUI.jaxx +++ /dev/null @@ -1,164 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='ReasonForDiscardDto' - contentTitle='{n("observe.content.title.reasonForDiscards")}' - listText='{n("observe.content.list.reasonForDiscard")}' - createToolTip='{n("observe.content.action.reasonForDiscard.create.tip")}' - detailToolTip='{n("observe.content.action.reasonForDiscard.detail.tip")}' - modifyToolTip='{n("observe.content.action.reasonForDiscard.modify.tip")}' - deleteToolTip='{n("observe.content.action.reasonForDiscard.delete.tip")}' - saveToolTip='{n("observe.content.action.reasonForDiscard.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.seine.ReasonForDiscardDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.seine.ReasonForDiscardDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <ReasonForDiscardUIModel id='model'/> - - <!-- edit bean --> - <ReasonForDiscardDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' - onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ReasonForDiscardUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ReasonForDiscardUIModel.java deleted file mode 100644 index 9d98b63..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ReasonForDiscardUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.seine.ReasonForDiscardDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ReasonForDiscardUIModel extends ContentReferenceUIModel<ReasonForDiscardDto> { - - private static final long serialVersionUID = 1L; - - public ReasonForDiscardUIModel() { - super(ReasonForDiscardDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ReasonForNoFishingUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ReasonForNoFishingUI.jaxx deleted file mode 100644 index 13903ad..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ReasonForNoFishingUI.jaxx +++ /dev/null @@ -1,164 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='ReasonForNoFishingDto' - contentTitle='{n("observe.content.title.reasonForNoFishings")}' - listText='{n("observe.content.list.reasonForNoFishing")}' - createToolTip='{n("observe.content.action.reasonForNoFishing.create.tip")}' - detailToolTip='{n("observe.content.action.reasonForNoFishing.detail.tip")}' - modifyToolTip='{n("observe.content.action.reasonForNoFishing.modify.tip")}' - deleteToolTip='{n("observe.content.action.reasonForNoFishing.delete.tip")}' - saveToolTip='{n("observe.content.action.reasonForNoFishing.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.seine.ReasonForNoFishingDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' - autoField='true' - beanClass='fr.ird.observe.services.dto.referential.seine.ReasonForNoFishingDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <ReasonForNoFishingUIModel id='model'/> - - <!-- edit bean --> - <ReasonForNoFishingDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ReasonForNoFishingUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ReasonForNoFishingUIModel.java deleted file mode 100644 index fa6f3f3..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ReasonForNoFishingUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.seine.ReasonForNoFishingDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ReasonForNoFishingUIModel extends ContentReferenceUIModel<ReasonForNoFishingDto> { - - private static final long serialVersionUID = 1L; - - public ReasonForNoFishingUIModel() { - super(ReasonForNoFishingDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ReasonForNullSetUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ReasonForNullSetUI.jaxx deleted file mode 100644 index 4590664..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ReasonForNullSetUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='ReasonForNullSetDto' - contentTitle='{n("observe.content.title.reasonForNullSets")}' - listText='{n("observe.content.list.reasonForNullSet")}' - createToolTip='{n("observe.content.action.reasonForNullSet.create.tip")}' - detailToolTip='{n("observe.content.action.reasonForNullSet.detail.tip")}' - modifyToolTip='{n("observe.content.action.reasonForNullSet.modify.tip")}' - deleteToolTip='{n("observe.content.action.reasonForNullSet.delete.tip")}' - saveToolTip='{n("observe.content.action.reasonForNullSet.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.seine.ReasonForNullSetDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.seine.ReasonForNullSetDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <ReasonForNullSetUIModel id='model'/> - - <!-- edit bean --> - <ReasonForNullSetDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ReasonForNullSetUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ReasonForNullSetUIModel.java deleted file mode 100644 index adca93f..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/ReasonForNullSetUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.seine.ReasonForNullSetDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ReasonForNullSetUIModel extends ContentReferenceUIModel<ReasonForNullSetDto> { - - private static final long serialVersionUID = 1L; - - public ReasonForNullSetUIModel() { - super(ReasonForNullSetDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/SpeciesFateUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/SpeciesFateUI.jaxx deleted file mode 100644 index e7fc8af..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/SpeciesFateUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='SpeciesFateDto' - contentTitle='{n("observe.content.title.speciesFates")}' - listText='{n("observe.content.list.speciesFate")}' - createToolTip='{n("observe.content.action.speciesFate.create.tip")}' - detailToolTip='{n("observe.content.action.speciesFate.detail.tip")}' - modifyToolTip='{n("observe.content.action.speciesFate.modify.tip")}' - deleteToolTip='{n("observe.content.action.speciesFate.delete.tip")}' - saveToolTip='{n("observe.content.action.speciesFate.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.seine.SpeciesFateDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.seine.SpeciesFateDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <SpeciesFateUIModel id='model'/> - - <!-- edit bean --> - <SpeciesFateDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/SpeciesFateUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/SpeciesFateUIModel.java deleted file mode 100644 index 3b016d7..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/SpeciesFateUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.seine.SpeciesFateDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class SpeciesFateUIModel extends ContentReferenceUIModel<SpeciesFateDto> { - - private static final long serialVersionUID = 1L; - - public SpeciesFateUIModel() { - super(SpeciesFateDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/SpeciesStatusUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/SpeciesStatusUI.jaxx deleted file mode 100644 index 8b79ebd..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/SpeciesStatusUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='SpeciesStatusDto' - contentTitle='{n("observe.content.title.speciesStatuss")}' - listText='{n("observe.content.list.speciesStatus")}' - createToolTip='{n("observe.content.action.speciesStatus.create.tip")}' - detailToolTip='{n("observe.content.action.speciesStatus.detail.tip")}' - modifyToolTip='{n("observe.content.action.speciesStatus.modify.tip")}' - deleteToolTip='{n("observe.content.action.speciesStatus.delete.tip")}' - saveToolTip='{n("observe.content.action.speciesStatus.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.seine.SpeciesStatusDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.seine.SpeciesStatusDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <SpeciesStatusUIModel id='model'/> - - <!-- edit bean --> - <SpeciesStatusDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/SpeciesStatusUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/SpeciesStatusUIModel.java deleted file mode 100644 index 3f5c550..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/SpeciesStatusUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.seine.SpeciesStatusDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class SpeciesStatusUIModel extends ContentReferenceUIModel<SpeciesStatusDto> { - - private static final long serialVersionUID = 1L; - - public SpeciesStatusUIModel() { - super(SpeciesStatusDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/SurroundingActivityUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/SurroundingActivityUI.jaxx deleted file mode 100644 index f498a57..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/SurroundingActivityUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='SurroundingActivityDto' - contentTitle='{n("observe.content.title.surroundingActivitys")}' - listText='{n("observe.content.list.surroundingActivity")}' - createToolTip='{n("observe.content.action.surroundingActivity.create.tip")}' - detailToolTip='{n("observe.content.action.surroundingActivity.detail.tip")}' - modifyToolTip='{n("observe.content.action.surroundingActivity.modify.tip")}' - deleteToolTip='{n("observe.content.action.surroundingActivity.delete.tip")}' - saveToolTip='{n("observe.content.action.surroundingActivity.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.seine.SurroundingActivityDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.seine.SurroundingActivityDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <SurroundingActivityUIModel id='model'/> - - <!-- edit bean --> - <SurroundingActivityDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/SurroundingActivityUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/SurroundingActivityUIModel.java deleted file mode 100644 index 18e5640..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/SurroundingActivityUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.seine.SurroundingActivityDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class SurroundingActivityUIModel extends ContentReferenceUIModel<SurroundingActivityDto> { - - private static final long serialVersionUID = 1L; - - public SurroundingActivityUIModel() { - super(SurroundingActivityDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/TransmittingBuoyOperationUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/TransmittingBuoyOperationUI.jaxx deleted file mode 100644 index 431af2b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/TransmittingBuoyOperationUI.jaxx +++ /dev/null @@ -1,164 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='TransmittingBuoyOperationDto' - contentTitle='{n("observe.content.title.transmittingBuoyOperations")}' - listText='{n("observe.content.list.operation")}' - createToolTip='{n("observe.content.action.transmittingBuoyOperation.create.tip")}' - detailToolTip='{n("observe.content.action.transmittingBuoyOperation.detail.tip")}' - modifyToolTip='{n("observe.content.action.transmittingBuoyOperation.modify.tip")}' - deleteToolTip='{n("observe.content.action.transmittingBuoyOperation.delete.tip")}' - saveToolTip='{n("observe.content.action.transmittingBuoyOperation.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.seine.TransmittingBuoyOperationDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.seine.TransmittingBuoyOperationDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <fr.ird.observe.ui.content.ref.impl.seine.TransmittingBuoyOperationUIModel id='model'/> - - <!-- edit bean --> - <TransmittingBuoyOperationDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' - onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/TransmittingBuoyOperationUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/TransmittingBuoyOperationUIModel.java deleted file mode 100644 index 430e7c8..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/TransmittingBuoyOperationUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.seine.TransmittingBuoyOperationDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class TransmittingBuoyOperationUIModel extends ContentReferenceUIModel<TransmittingBuoyOperationDto> { - - private static final long serialVersionUID = 1L; - - public TransmittingBuoyOperationUIModel() { - super(TransmittingBuoyOperationDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/TransmittingBuoyTypeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/TransmittingBuoyTypeUI.jaxx deleted file mode 100644 index a197194..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/TransmittingBuoyTypeUI.jaxx +++ /dev/null @@ -1,164 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='TransmittingBuoyTypeDto' - contentTitle='{n("observe.content.title.transmittingBuoyTypes")}' - listText='{n("observe.content.list.transmittingBuoyType")}' - createToolTip='{n("observe.content.action.transmittingBuoyType.create.tip")}' - detailToolTip='{n("observe.content.action.transmittingBuoyType.detail.tip")}' - modifyToolTip='{n("observe.content.action.transmittingBuoyType.modify.tip")}' - deleteToolTip='{n("observe.content.action.transmittingBuoyType.delete.tip")}' - saveToolTip='{n("observe.content.action.transmittingBuoyType.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.seine.TransmittingBuoyTypeDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.seine.TransmittingBuoyTypeDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <TransmittingBuoyTypeUIModel id='model'/> - - <!-- edit bean --> - <TransmittingBuoyTypeDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/TransmittingBuoyTypeUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/TransmittingBuoyTypeUIModel.java deleted file mode 100644 index add1e13..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/TransmittingBuoyTypeUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.seine.TransmittingBuoyTypeDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class TransmittingBuoyTypeUIModel extends ContentReferenceUIModel<TransmittingBuoyTypeDto> { - - private static final long serialVersionUID = 1L; - - public TransmittingBuoyTypeUIModel() { - super(TransmittingBuoyTypeDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/VesselActivitySeineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/VesselActivitySeineUI.jaxx deleted file mode 100644 index 6071874..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/VesselActivitySeineUI.jaxx +++ /dev/null @@ -1,165 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='VesselActivitySeineDto' - contentTitle='{n("observe.content.title.vesselActivitySeines")}' - listText='{n("observe.content.list.vesselActivitySeine")}' - createToolTip='{n("observe.content.action.vesselActivitySeine.create.tip")}' - detailToolTip='{n("observe.content.action.vesselActivitySeine.detail.tip")}' - modifyToolTip='{n("observe.content.action.vesselActivitySeine.modify.tip")}' - deleteToolTip='{n("observe.content.action.vesselActivitySeine.delete.tip")}' - saveToolTip='{n("observe.content.action.vesselActivitySeine.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.seine.VesselActivitySeineDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' - autoField='true' - beanClass='fr.ird.observe.services.dto.referential.seine.VesselActivitySeineDto' - errorTableModel='{getErrorTableModel()}' - context='ui-create'/> - - <!-- model --> - <VesselActivitySeineUIModel id='model'/> - - <!-- edit bean --> - <VesselActivitySeineDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel' styleClass='unique'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' styleClass='unique' - onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/VesselActivitySeineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/VesselActivitySeineUIModel.java deleted file mode 100644 index 1f26f72..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/VesselActivitySeineUIModel.java +++ /dev/null @@ -1,42 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.seine.VesselActivitySeineDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class VesselActivitySeineUIModel extends ContentReferenceUIModel<VesselActivitySeineDto> { - - private static final long serialVersionUID = 1L; - - public VesselActivitySeineUIModel() { - super(VesselActivitySeineDto.class); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/WeightCategoryUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/WeightCategoryUI.jaxx deleted file mode 100644 index 5b03d6d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/WeightCategoryUI.jaxx +++ /dev/null @@ -1,197 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='WeightCategoryDto' - contentTitle='{n("observe.content.title.weightCategory")}' - listText='{n("observe.content.list.weightCategory")}' - createToolTip='{n("observe.content.action.weightCategory.create.tip")}' - detailToolTip='{n("observe.content.action.weightCategory.detail.tip")}' - modifyToolTip='{n("observe.content.action.weightCategory.modify.tip")}' - deleteToolTip='{n("observe.content.action.weightCategory.delete.tip")}' - saveToolTip='{n("observe.content.action.weightCategory.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.seine.WeightCategoryDto - fr.ird.observe.services.dto.referential.SpeciesDto - fr.ird.observe.ui.UIHelper - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - jaxx.runtime.swing.editor.bean.BeanComboBox - - javax.swing.JScrollPane - javax.swing.JTable - javax.swing.table.TableCellRenderer - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.seine.WeightCategoryDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <WeightCategoryUIModel id='model'/> - - <!-- edit bean --> - <WeightCategoryDto id='bean'/> - - <script><![CDATA[ - -@Override -public void decorateUniqueKeyTable(JTable table, - TableCellRenderer renderer, - JScrollPane pane) { - - UIHelper.fixTableColumnWidth(table, 0, 240); - UIHelper.fixTableColumnWidth(table, 1, 60); - UIHelper.fixTableColumnWidth(table, 2, 200); - table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); -} -]]></script> - - <Table id='editTable'> - - <!-- species --> - <row> - <cell anchor='west'> - <JLabel id='speciesLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <BeanComboBox id='species' constructorParams='this' - genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class'/> - </cell> - </row> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/WeightCategoryUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/WeightCategoryUIModel.java deleted file mode 100644 index 776fdb1..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/WeightCategoryUIModel.java +++ /dev/null @@ -1,46 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.seine.WeightCategoryDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class WeightCategoryUIModel extends ContentReferenceUIModel<WeightCategoryDto> { - - private static final long serialVersionUID = 1L; - - public WeightCategoryUIModel() { - super(WeightCategoryDto.class, - new String[]{WeightCategoryDto.PROPERTY_CODE, WeightCategoryDto.PROPERTY_SPECIES}, - new String[]{WeightCategoryDto.PROPERTY_CODE, WeightCategoryDto.PROPERTY_SPECIES}, - new String[]{WeightCategoryUI.BINDING_CODE_TEXT, WeightCategoryUI.BINDING_SPECIES_SELECTED_ITEM} - ); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/WindUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/WindUI.jaxx deleted file mode 100644 index 7afb280..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/WindUI.jaxx +++ /dev/null @@ -1,186 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ref.ContentReferenceUI - superGenericType='WindDto' - contentTitle='{n("observe.content.title.windSpeeds")}' - listText='{n("observe.content.list.wind")}' - createToolTip='{n("observe.content.action.wind.create.tip")}' - detailToolTip='{n("observe.content.action.wind.detail.tip")}' - modifyToolTip='{n("observe.content.action.wind.modify.tip")}' - deleteToolTip='{n("observe.content.action.wind.delete.tip")}' - saveToolTip='{n("observe.content.action.wind.save.tip")}' - - > - - <style source="../ReferenceEntity.jcss"/> - <style source="../I18nReferenceEntity.jcss"/> - - <import> - fr.ird.observe.services.dto.constants.ReferenceStatus - fr.ird.observe.services.dto.referential.seine.WindDto - fr.ird.observe.ui.content.ref.ContentReferenceUIModel - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- validator --> - <BeanValidator id='validator' autoField='true' - beanClass='fr.ird.observe.services.dto.referential.seine.WindDto' - context='ui-create' - errorTableModel='{getErrorTableModel()}'/> - - <!-- model --> - <WindUIModel id='model'/> - - <!-- edit bean --> - <WindDto id='bean'/> - - <Table id='editTable'> - - <!-- uri --> - <row> - <cell anchor="west"> - <JLabel id='uriLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='uri' onKeyReleased='getBean().setUri(uri.getText())'/> - </cell> - </row> - - <!-- code / status --> - <row> - <cell anchor="west"> - <JLabel id='codeStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel id='codeStatusPanel' layout='{new BorderLayout()}'> - <JTextField id='code' constraints='BorderLayout.WEST' - onKeyReleased='getBean().setCode(code.getText())'/> - <EnumEditor id='status' constraints='BorderLayout.CENTER' - constructorParams='ReferenceStatus.class' - genericType='ReferenceStatus' - onItemStateChanged='getBean().setStatus((ReferenceStatus)status.getSelectedItem())'/> - </JPanel> - </cell> - </row> - - <!-- speedRange --> - <row> - <cell anchor="west"> - <JLabel id='speedRangeLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='speedRange' - onKeyReleased='getBean().setSpeedRange(speedRange.getText())'/> - </cell> - </row> - - <!-- waveHeight --> - <row> - <cell anchor="west"> - <JLabel id='waveHeightLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='waveHeight' - onKeyReleased='getBean().setWaveHeight(waveHeight.getText())'/> - </cell> - </row> - - <!-- needComment --> - <row> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <JCheckBox id='needComment' - onItemStateChanged='getBean().setNeedComment(needComment.isSelected())'/> - </cell> - </row> - </Table> - - <Table id='editI18nTable'> - <row> - <cell anchor="west"> - <JLabel id='label1Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label1' - onKeyReleased='getBean().setLabel1(label1.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label2Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label2' - onKeyReleased='getBean().setLabel2(label2.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label3Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label3' - onKeyReleased='getBean().setLabel3(label3.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label4Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label4' - onKeyReleased='getBean().setLabel4(label4.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label5Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label5' - onKeyReleased='getBean().setLabel5(label5.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label6Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label6' - onKeyReleased='getBean().setLabel6(label6.getText())'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='label7Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label7' - onKeyReleased='getBean().setLabel7(label7.getText())'/> - </cell> - <cell anchor="west"> - <JLabel id='label8Label'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JTextField id='label8' - onKeyReleased='getBean().setLabel8(label8.getText())'/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.ref.ContentReferenceUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/WindUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/WindUIModel.java deleted file mode 100644 index 7ffc0a7..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/ref/impl/seine/WindUIModel.java +++ /dev/null @@ -1,45 +0,0 @@ -package fr.ird.observe.ui.content.ref.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.seine.WindDto; -import fr.ird.observe.ui.content.ref.ContentReferenceUIModel; - -/** - * Created on 9/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class WindUIModel extends ContentReferenceUIModel<WindDto> { - - private static final long serialVersionUID = 1L; - - public WindUIModel() { - super(WindDto.class, - new String[]{WindDto.PROPERTY_SPEED_RANGE, WindDto.PROPERTY_WAVE_HEIGHT}, - new String[]{WindUI.BINDING_SPEED_RANGE_TEXT, WindUI.BINDING_WAVE_HEIGHT_TEXT} - ); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableMeta.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableMeta.java deleted file mode 100644 index b7942e3..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableMeta.java +++ /dev/null @@ -1,158 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.table; - -import com.google.common.base.Preconditions; -import com.google.common.collect.Iterables; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.util.ObjectUtil; -import org.nuiton.util.beans.BeanUtil; - -import java.beans.PropertyDescriptor; -import java.io.Serializable; -import java.util.Set; -import java.util.function.Predicate; - -/** - * La définition d'une méta donnée d'un tableau, i.e la définition d'une - * colonne. - * - * @param <B> le type de la donnée encapsulée par la colonne - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class ContentTableMeta<B> implements Serializable { - - /** Logger. */ - private static final Log log = LogFactory.getLog(ContentTableMeta.class); - - private static final long serialVersionUID = 1L; - - /** le lastName de la meta (c'est le nom de la colonne) */ - protected final String name; - - /** le type de la meta (c'estle type de la colonne) */ - protected final Class<B> klass; - - /** - * un drapeau pour savoir si on peut modifier cette méta lorsque l'objet - * encapsulé existe déjà en base (pour pouvoir gérer les clefs métiers non - * mutable) - */ - protected final boolean unmodiableWhenExisting; - - /** - * le descripteur de la méta (pour pouvoir récupérer et modifier la - * colonne) - */ - protected transient PropertyDescriptor propertyDescriptor; - - public ContentTableMeta(Class<B> klass, - String name, - boolean unmodiableWhenExisting) { - this.name = name; - this.klass = klass; - this.unmodiableWhenExisting = unmodiableWhenExisting; - if (log.isDebugEnabled()) { - log.debug(this + " : " + name + " : " + getType().getName()); - } - } - - /** @return the name of this meta (will be used as columnName) */ - public String getName() { - return name; - } - - /** @return the type of this meta (will be used as columnClass) */ - public Class<?> getType() { - return getPropertyDescriptor().getPropertyType(); - } - - /** - * @param model le modele qui contient la meta - * @param bean the bean to request - * @param row the current row - * @return the value of the property of the given bean - */ - public Object getValue(ContentTableModel<?, ?> model, - B bean, - int row) { - try { - return getPropertyDescriptor().getReadMethod().invoke(bean); - } catch (Exception e) { - throw new RuntimeException(e); - } - } - - /** - * @param model the currentmodel - * @param bean the bean to modifiy - * @param aValue the new value to set - * @param row the current row modified - * @return {@code true} if bean data has changed, {@code false} - * otherwise - */ - public boolean setValue(ContentTableModel<?, ?> model, - B bean, - Object aValue, - int row) { - Object oldValue = getValue(model, bean, row); - /*try { - getPropertyDescriptor().getWriteMethod().invoke(bean, aValue); - } catch (Exception e) { - throw new RuntimeException(e); - }*/ - return oldValue == null && aValue != null || - oldValue != null && !oldValue.equals(aValue); - } - - /** - * Test if the property of a given bean is null. - * - * @param model le modele qui contient la meta - * @param bean the current bean to test - * @param row the current row - * @return {@code true} if data is null for the given meta, - * {@code false} otherwise. - */ - public boolean isNullValue(ContentTableModel<?, ?> model, - B bean, - int row) { - Object value = getValue(model, bean, row); - return ObjectUtil.isNullValue(value); - } - - /** @return the property descriptor of the meta */ - protected PropertyDescriptor getPropertyDescriptor() { - if (propertyDescriptor == null) { - Predicate<PropertyDescriptor> predicate = - input -> BeanUtil.IS_READ_DESCRIPTOR.apply(input) - && name.equals(input.getName()); - Set<PropertyDescriptor> descriptors = BeanUtil.getDescriptors(klass, predicate::test); - Preconditions.checkState(!descriptors.isEmpty(), - "could not find readable property " + name + " for bean " + klass); - propertyDescriptor = Iterables.get(descriptors, 0); - } - return propertyDescriptor; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableModel.java deleted file mode 100644 index 5a41382..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableModel.java +++ /dev/null @@ -1,748 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.table; - -import fr.ird.observe.services.dto.AbstractObserveDto; -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.ui.UIHelper; -import jaxx.runtime.validator.swing.SwingValidator; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.i18n.I18n; - -import javax.swing.JOptionPane; -import javax.swing.table.AbstractTableModel; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -/** - * Le modele d'un tableau où les données sont une association sur une entité. - * - * Ce modèle n'est pas éditable. - * - * Les données sont stockées dans la liste {@link #data} qui sert de cache, car - * on veut pouvoir valider en temps réel l'entité principale (celle qui contient - * l'association), il faut donc toujours que les données de l'association soient - * synchronisées. L'utilisation d'un cache est cependant requise car sinon cela - * est trop couteux (notamment pour le rendu du tableau...). - * - * Le cache sera recalculé à chaque fois que l'on modifie la structure des - * données de l'association (ajout d'une entrée, suppression d'une entrée). - * - * De plus le cache permet de travailler sur une liste (alors que l'association - * n'est peut-être pas ordonnée) et cela facilite les opérations sur les données - * du tableau). - * - * Le modèle définit plusieurs propriétés : <ul> <li>{@link #editable} : un - * drapeau pour savoir si le modèle est editable</li> <li>{@link #modified} : un - * drapeau pour savoir si le modèle est modifié</li> <li>{@link #create} : un - * drapeau pour savoir si l'entrée en cours d'édition est une nouvelle - * entrée</li> <li>{@link #selectedRow} : l'index de l'entrée sélectionnée</li> - * </ul> FIXME a finir... - * - * @param <P> le type de l'entité qui contient la liste - * @param <B> le type de l'entite d'une entrée de la liste - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public abstract class ContentTableModel<P extends IdDto, B extends IdDto> extends AbstractTableModel { - - /** Le nom de la propriété de la ligne en cours d'édition */ - public static final String SELECTED_ROW_PROPERTY = "selectedRow"; - - /** Le nom de la propriété modifié du modèle */ - public static final String MODIFIED_PROPERTY = "modified"; - - /** Le nom de la propriété pour editer le modele */ - public static final String EDITABLE_PROPERTY = "editable"; - - /** - * Le nom de la propriété pour indiquer que l'entrée en cours d'édition est - * en mode création - */ - public static final String CREATE_PROPERTY = "create"; - - /** Le nom de la propriété pour savoir si le modèle est vide */ - public static final String EMPTY_PROPERTY = "empty"; - - private static final long serialVersionUID = 1L; - - /** Logger */ - private static final Log log = LogFactory.getLog(ContentTableModel.class); - - /** la liste des métas du modèle */ - protected final List<ContentTableMeta<B>> metas; - - /** pour la propagation des modifications d'états */ - protected final PropertyChangeSupport pcs = new PropertyChangeSupport(this); - - /** la liste des données du modèle */ - protected List<B> data = new ArrayList<>(); - - /** un drapeau pour savoir si le modèle a été modifié */ - protected boolean modified; - - /** un drapeau pour savoir si le modèle est éditable */ - protected boolean editable; - - /** un drapeau pour savoir si on edite une nouvelle entree */ - protected boolean create; - - /** - * un drapeau pour modifier la selection de la ligne en cours sans aucune - * verification. - */ - protected boolean valueAdjusting; - - /** l'entrée sélectionnée (-1 quand pas de sélection) */ - protected int selectedRow = -1; - - /** un message supplémentaire à afficher lors d'une suppression de ligne */ - protected String deleteExtraMessage; - - /** un drapeau pour savoir si le modèle a ete initialisé. */ - private boolean init; - - private ObserveContentTableUI<P, B> context; - - @SuppressWarnings("unchecked") - public ContentTableModel(ObserveContentTableUI<P, B> context, - List<ContentTableMeta<B>> metas) { - if (CollectionUtils.isEmpty(metas)) { - throw new NullPointerException("meta parameter can not be null, nor empty"); - } - - this.context = context; - this.metas = Collections.unmodifiableList(metas); - } - - public static <D extends AbstractObserveDto> ContentTableMeta<D> newTableMeta( - Class<D> childType, - String property, - boolean unmodiableWhenExisting) { - - return new ContentTableMeta<>(childType, - property, unmodiableWhenExisting); - } - - /** - * Positionne un bean dans le modèle. - * - * Cela va initialiser la liste à utiliser. - */ - public void attachModel() { - // pas de ligne selectionne - setSelectedRow(-1); - - // pas en mode creation - setCreate(false); - - setInit(true); - - updateEmpty(); - - if (log.isDebugEnabled()) { - log.debug("editable : " + isEditable()); - log.debug("size : " + getRowCount()); - } - - // notify listeners - fireTableDataChanged(); - } - - public void dettachModel() { - setModified(false); - int size = getRowCount(); - // on indique que le modele n'est plus lie au bean - // cela permet de ne plus charger l'association dans le cache - setInit(false); - if (size > 0) { - // il y avait des données que l'on a supprimé - fireTableRowsDeleted(0, size - 1); - updateEmpty(); - } - setSelectedRow(-1); - setCreate(false); - } - - /** Permet l'ajout d'une nouvelle entrée à editer */ - public void addNewEntry() { - ensureEditable(); - - if (getSelectedRow() > -1) { - // il y avait une ligne precedemment selectionnee, - // on doit verifier que l'on peut changer d'entree - if (!isCanQuitEditingRow()) { - // on ne peut pas quitter la ligne en cours d'édition - // on annule donc l'opération - return; - } - } - - // on est autorise a ajouter une nouvelle entrée - - int row = getRowCount(); - - B bean = null; - try { - bean = getModel().newTableEditBean(); - } catch (Exception e) { - UIHelper.handlingError(e); - } - data.add(bean); - - updateBeanList(false); - - fireTableRowsInserted(row, row); - updateEmpty(); - - // on est en mode creation - setCreate(true); - - // la nouvelle ligne est celle en cours d'edition - changeSelectedRow(row); - } - - protected ContentTableUIModel<P, B> getModel() { - return getHandler().getModel(); - } - - public void doRemoveRow(int rowToDelete, boolean force) { - B bean = getValueAt(rowToDelete); - ContentTableMeta<B> meta = getColumnMeta(getColumnCount() - 1); - - if (force || UIHelper.confirmForEntityDelete(null, meta.klass, bean, deleteExtraMessage)) { - // delete row - removeRow(rowToDelete); - rowToDelete--; - - // on veut selectionner la ligne precedente si elle existe - // ou bien la meme ligne (si on etait sur la premiere ligne) - - - // on force toujours le passage sur la ligne d'avant - // afin que le binding se deroule bien meme si ensuite on rechange - // la ligne selectionne (cas ou on etait sur la premier ligne et - // que le modele n'est pas vide) - changeSelectedRow(rowToDelete); - if (rowToDelete == -1 && !isEmpty()) { - // on repasse sur la premiere ligne - // car le modele n'est pas vide - changeSelectedRow(0); - } - } - } - - public boolean isCanQuitEditingRow() { - if (selectedRow == -1) { - // aucune ligne selectionne - // on peut changer la ligne sans verification - return true; - } - - if (!create && !isModelModified()) { - // on est sur une ligne en mode mise a jour - // et aucune changement n'a ete effectue - // on peut continuer sans rien tester - return true; - } - - // une ligne etait precemment en cours d'edition et a ete modifiee - - if (log.isDebugEnabled()) { - log.debug("editing row " + getSelectedRow() + " was modified, need confirmation"); - } - - boolean canContinue = false; - - if (isModelValid()) { - // la ligne est valide, on demande a l'utilisateur s'il - // veut la sauvegarder - - int reponse = UIHelper.askUser( - I18n.t("observe.title.need.confirm"), - I18n.t("observe.message.table.editBean.modified"), - JOptionPane.WARNING_MESSAGE, - new Object[]{ - I18n.t("observe.choice.save"), - I18n.t("observe.choice.doNotSave"), - I18n.t("observe.choice.cancel")}, - 0); - if (log.isDebugEnabled()) { - log.debug("response : " + reponse); - } - - switch (reponse) { - case JOptionPane.CLOSED_OPTION: - case 2: - - break; - case 0: - // will save ui - // sauvegarde des modifications - updateRowFromEditBean(); - canContinue = true; - break; - case 1: - // edition annulé - canContinue = true; - if (create) { - - // on doit supprimer la ligne de creation - removeRow(getSelectedRow()); - } else { - - // reset row - resetRow(getSelectedRow()); - } - break; - } - - } else { - - // le validateur n'est pas ok, on ne peut que proposer la perte - // des donnees car elles sont ne pas enregistrables - - int reponse = UIHelper.askUser( - I18n.t("observe.title.need.confirm"), - I18n.t("observe.message.table.editBean.modified.but.invalid"), - JOptionPane.ERROR_MESSAGE, - new Object[]{ - I18n.t("observe.choice.continue"), - I18n.t("observe.choice.cancel")}, - 0); - if (log.isDebugEnabled()) { - log.debug("response : " + reponse); - } - switch (reponse) { - case 0: - // wil reset ui - canContinue = true; - if (create) { - // on doit supprimer la ligne de creation - removeRow(getSelectedRow()); - } - break; - } - } - return canContinue; - } - - protected void resetRow(int row) { - // do nothing by default - } - - /** - * Selectionne la ligne dont l'index est donné. - * - * @param row l'index de la nouvelle ligne a editer - */ - public void changeSelectedRow(int row) { - - if (log.isDebugEnabled()) { - log.debug("row : " + row); - log.debug("editable : " + isEditable()); - log.debug("size : " + getRowCount()); - } - - if (editable) { - // on force la suppression de l'ancien validateur - getValidator().setBean(null); - } - - if (row == -1) { - // cas special lors de la suppression de la selection, par exemple - // lors d'une suppression de colonne - setSelectedRow(row); - return; - } - - ensureRowIndex(row); - - if (editable) { - // on recharge le bean dans le validateur - // cela permettre de faire fonctionner les binding - // lors de la construction du nouveau editBean - getValidator().setBean(getRowBean()); - } - - // recherche du bean d'édition - B beanToBind; - - // on recupere le bean existant - beanToBind = getValueAt(row); - - // on charge le bean d'edition - load(beanToBind, getRowBean()); - - // on modifie la ligne d'edition - setSelectedRow(row); - - if (editable) { - // pas de modification sur le validateur - getValidator().setChanged(false); - } - } - - /** - * Pour mettre a jour la ligne en cours d'edition a partir du bean - * d'edition - */ - public void updateRowFromEditBean() { - ensureEditable(); - - int editingRow = getSelectedRow(); - - // mettre a jour la ligne - B bean = getValueAt(editingRow); - load(getRowBean(), bean); - fireTableRowsUpdated(editingRow, editingRow); - - if (create) { - // la ligne n'est plus en mode creation - setCreate(false); - } - - // plus de modification sur le bean d'edition - getValidator().setChanged(false); - - // le model a ete modifie - setModified(true); - // on valide le bean principal - // pour cela on doit recharger l'association dans le bean principale - // car vu que l'on travaille sur des collections, si on ne supprime - // pas la liste avant de vouloir valider, alors aucune validation ne - // sera declanchée (car pas de propriété modifié dans le bean...) - getParentValidator().doValidate(); - } - - public void resetEditBean() { - B bean = getValueAt(getSelectedRow()); - - load(bean, getRowBean()); - // plus de modification sur le bean d'edition - getValidator().setChanged(false); - } - - @SuppressWarnings("unchecked") - protected ContentTableUIHandler<P, B> getHandler() { - ContentTableUIHandler<P, B> handler = context.getHandler(); - return handler; - } - - protected abstract Collection<B> getChilds(P bean); - - protected abstract void load(B source, B target); - - protected P getBean() { - ContentTableUIModel<P, B> model = getModel(); - return model == null ? null : model.getBean(); - } - - public B getRowBean() { - ContentTableUIModel<P, B> model = getModel(); - return model == null ? null : model.getTableEditBean(); - } - - public boolean isNewRow() { - return getRowBean().getId() == null; - } - - public boolean isCreate() { - return create; - } - - public void setCreate(boolean create) { - boolean old = this.create; - this.create = create; - firePropertyChange(CREATE_PROPERTY, old, create); - } - - public int getSelectedRow() { - return selectedRow; - } - - public void setSelectedRow(int selectedRow) { - int old = this.selectedRow; - this.selectedRow = selectedRow; - firePropertyChange(SELECTED_ROW_PROPERTY, old, selectedRow); - } - - public String getDeleteExtraMessage() { - return deleteExtraMessage; - } - - public void setDeleteExtraMessage(String deleteExtraMessage) { - this.deleteExtraMessage = deleteExtraMessage; - } - - public boolean isModified() { - return modified; - } - - public void setModified(boolean modified) { - boolean oldModified = this.modified; - this.modified = modified; - firePropertyChange(MODIFIED_PROPERTY, oldModified, modified); - } - - public boolean isEditable() { - return editable; - } - - public void setEditable(boolean editable) { - boolean oldModified = this.editable; - this.editable = editable; - firePropertyChange(EDITABLE_PROPERTY, oldModified, editable); - } - - public boolean isValueAdjusting() { - return valueAdjusting; - } - - public boolean isEmpty() { - return getRowCount() == 0; - } - - public List<B> getData() { - if (data == null) { - if (init) { - // le modèle a ete initialise - // on recupere donc la liste a partir du bean principal - P bean = getBean(); - - Collection<B> childs = getChilds(bean); - if (childs == null || childs.isEmpty()) { - data = new ArrayList<>(); - } else { - data = new ArrayList<>(childs); - } - } else { - // le modèle n'est pas encore initialisé - // on retourne donc une liste vide - data = new ArrayList<>(); - } - } - return data; - } - - public int getColumn(String columnName) { - int i = 0; - for (ContentTableMeta<B> m : metas) { - if (m.getName().equals(columnName)) { - return i; - } - i++; - } - return -1; - } - - @Override - public int getRowCount() { - List<B> list = getData(); - return list == null ? 0 : list.size(); - } - - @Override - public int getColumnCount() { - return metas.size(); - } - - @Override - public String getColumnName(int columnIndex) { - ensureColumnIndex(columnIndex); - return metas.get(columnIndex).getName(); - } - - @Override - public Class<?> getColumnClass(int columnIndex) { - ensureColumnIndex(columnIndex); - return metas.get(columnIndex).getType(); - } - - public ContentTableMeta<B> getColumnMeta(int columnIndex) { - ensureColumnIndex(columnIndex); - return metas.get(columnIndex); - } - - @Override - public boolean isCellEditable(int rowIndex, int columnIndex) { - // dans ce type de modele rien n'est editable - return false; - } - - @Override - public Object getValueAt(int row, int column) { - ensureColumnIndex(column); - ContentTableMeta<B> meta = getColumnMeta(column); - B bean = getValueAt(row); - return bean == null ? null : getValueAt(bean, row, meta); - } - - public B getValueAt(int row) { - ensureRowIndex(row); - List<B> list = getData(); - return list == null ? null : list.get(row); - } - - public void updateEmpty() { - firePropertyChange(EMPTY_PROPERTY, null, isEmpty()); - } - - /** - * @param <T> the type of the column property - * @param column the column to scan - * @return the list of used properties for a given column - */ - @SuppressWarnings({"unchecked"}) - public <T> List<T> getColumnValues(int column) { - List<T> result = new ArrayList<>(); - if (!isEmpty()) { - for (int i = 0; i < getRowCount(); i++) { - T value = (T) getValueAt(i, column); - if (value != null) { - result.add(value); - } - } - } - - return result; - } - - public void addPropertyChangeListener(PropertyChangeListener listener) { - pcs.addPropertyChangeListener(listener); - } - - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { - pcs.addPropertyChangeListener(propertyName, listener); - } - - public void removePropertyChangeListener(PropertyChangeListener listener) { - pcs.removePropertyChangeListener(listener); - } - - public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { - pcs.removePropertyChangeListener(propertyName, listener); - } - - public void firePropertyChange(String propertyName, Object oldValue, Object newValue) { - pcs.firePropertyChange(propertyName, oldValue, newValue); - } - - @SuppressWarnings("unchecked") - protected SwingValidator<B> getValidator() { - return context == null ? null : context.getValidatorTable(); - } - - @SuppressWarnings("unchecked") - protected SwingValidator<P> getParentValidator() { - return context == null ? null : context.getValidator(); - } - - protected void removeRow(int row) { - ensureRowIndex(row); - setSelectedRow(-1); - getData().remove(row); - - updateBeanList(!create); - - if (log.isDebugEnabled()) { - log.debug(row); - } - // model has changed - if (!create) { - setModified(true); - } - fireTableRowsDeleted(row, row); - if (create) { - // on quitte le mode creation - setCreate(false); - } - updateEmpty(); - } - - protected Object getValueAt(B bean, int row, ContentTableMeta<B> meta) { - return meta.getValue(this, bean, row); - } - - protected boolean setValueAt(B bean, Object aValue, int row, ContentTableMeta<B> meta) { - return meta.setValue(this, bean, aValue, row); - } - - protected void ensureColumnIndex(int columnIndex) throws ArrayIndexOutOfBoundsException { - if (columnIndex < 0 || columnIndex >= metas.size()) { - throw new ArrayIndexOutOfBoundsException("column index should be in [0," + metas.size() + "], but was " + columnIndex); - } - } - - protected void ensureRowIndex(int rowIndex) throws ArrayIndexOutOfBoundsException { - int size = getRowCount(); - if (rowIndex < 0 || rowIndex >= size) { - throw new ArrayIndexOutOfBoundsException("row index should be in [0," + (getRowCount() - 1) + "], but was " + rowIndex); - } - } - - protected void ensureEditable() throws IllegalStateException { - if (!editable) { - throw new IllegalStateException("can not edit this model since it is marked as none editable " + this); - } - } - - protected void setInit(boolean init) { - this.init = init; - // le changement de l'état init provoque toujours le vidage du cache - clearCache(); - } - - protected void clearCache() { - data = null; - } - - protected void updateBeanList(boolean shouldChanged) { - SwingValidator<P> parentValidator = getParentValidator(); - boolean wasChanged = parentValidator.isChanged(); - - // on repositionne la liste sur le bean principal - // pour avoir la validation en temps reel sur le bean principal - setChilds(getBean(), data); - parentValidator.doValidate(); - if (!shouldChanged && !wasChanged) { - // on repositionne le drapeau changed a faux - parentValidator.setChanged(false); - } - } - - protected abstract void setChilds(P parent, List<B> childs); - - protected boolean isModelModified() { - return getValidator().isChanged(); - } - - protected boolean isModelValid() { - return getValidator().isValid(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableUI.jaxx deleted file mode 100644 index 9e66d97..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableUI.jaxx +++ /dev/null @@ -1,201 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.ContentUI - abstract='true' - superGenericType='E' implements="fr.ird.observe.ui.content.table.ObserveContentTableUI<E,D>" - genericType='E extends IdDto, D extends IdDto'> - - <import> - fr.ird.observe.ui.actions.shared.ResetEditUIAction - fr.ird.observe.ui.actions.shared.SaveEditUIAction - - jaxx.runtime.swing.BlockingLayerUI - jaxx.runtime.validator.swing.SwingValidator - - fr.ird.observe.services.dto.AbstractObserveDto - fr.ird.observe.services.dto.IdDto - - java.awt.Dimension - - javax.swing.UIManager - - static org.nuiton.i18n.I18n.n - - </import> - - <!-- les libellés et info-bulles des actions sur l'éditeur d'un entrée --> - <String id='newEntryText' javaBean='n("observe.action.new.entry")'/> - <String id='newEntryTip' javaBean='n("observe.action.new.entry.tip")'/> - <String id='resetEntryText' javaBean='n("observe.content.action.reset")'/> - <String id='resetEntryTip' javaBean='n("observe.content.action.reset.entry.tip")'/> - <String id='resetNewEntryText' javaBean='n("observe.content.action.reset")'/> - <String id='resetNewEntryTip' javaBean='n("observe.content.action.reset.new.entry.tip")'/> - <String id='saveEntryText' javaBean='n("observe.action.save")'/> - <String id='saveEntryTip' javaBean='n("observe.action.save.entry.tip")'/> - <String id='saveNewEntryText' javaBean='n("observe.action.create")'/> - <String id='saveNewEntryTip' javaBean='n("observe.content.action.create.entry.tip")'/> - <String id='deleteEntryText' javaBean='n("observe.action.delete")'/> - <String id='deleteEntryTip' javaBean='n("observe.action.delete.entry.tip")'/> - - <!-- Handler --> - <ContentTableUIHandler id='handler' genericType='E, D'/> - - <!-- Model --> - <ContentTableUIModel id='model' genericType='E, D' initializer='ContentTableUIModel.newModel(this)'/> - - <!-- le modèle du tableau --> - <ContentTableModel id='tableModel' genericType='E, D' initializer='getModel().getTableModel()'/> - - <!-- le modèle de selection dans le tableau --> - <ListSelectionModel id='selectionModel' initializer='getModel().getSelectionModel()' - onValueChanged='getHandler().updateEditor(event)'/> - - <!-- le bloqueur de l'editeur d'une entrée du tableau --> - <BlockingLayerUI id='editorBlockLayerUI'/> - - <IdDto id='tableEditBean' initializer='getModel().getTableEditBean()'/> - - <!-- icone des donnees observees --> - <Icon id='iconDataObserve' initializer='SwingUtil.getUIManagerActionIcon("data-observe")'/> - - <!-- icone des donnees calculees --> - <Icon id='iconDataCalcule' initializer='SwingUtil.getUIManagerActionIcon("data-calcule")'/> - - <script><![CDATA[ - -public abstract SwingValidator<E> getValidator(); - -public abstract SwingValidator<D> getValidatorTable(); - -]]> - </script> - - <JPanel id="body"> - - <JPanel id='hideForm' layout='{new BorderLayout()}' - constraints="BorderLayout.CENTER"> - <JLabel id='hideFormInformation'/> - </JPanel> - - <Table id='showForm' insets="0" weightx="1" fill="both" - constraints="BorderLayout.CENTER"> - - <row weighty="0.3"> - <cell> - - <!-- le tableau --> - <JScrollPane id='tableScrollPane'> - <JTable id='table'/> - </JScrollPane> - - </cell> - </row> - - <row> - <cell> - - <!-- éditeur d'une entrée du tableau --> - <Table id='editor' fill='both' insets='0' decorator='boxed'> - - <!-- le panel d'edition d'une entrée à surcharger pour chaque écran --> - - <row> - <cell fill='both' weightx='1'> - <Table id='editorPanel' decorator='boxed'/> - </cell> - </row> - - <!--les actions sur l'éditeur d'une entrée du tableau --> - - <row> - <cell> - <Table fill='both' id='editorActions'> - <row> - <cell weightx='1'> - <!-- ajouter une nouvelle entrée --> - <JButton id='newEntry' - onActionPerformed='getTableModel().addNewEntry()'/> - </cell> - <cell weightx='1'> - <!-- annuler la création d'une nouvelle entrée (en mode creation) --> - <JButton id='resetNewEntry' - onActionPerformed='getTableModel().doRemoveRow(getTableModel().getSelectedRow(), true)'/> - </cell> - <cell weightx='1'> - <!-- réinitialiser l'entrée en cours d'édition (en mode mise a jour) --> - <JButton id='resetEntry' - onActionPerformed='getHandler().resetEditBean()'/> - </cell> - <cell weightx='1'> - <!-- sauver dans le tableau l'entrée en cours d'édition (en mode mise a jour)--> - <JButton id='saveEntry' - onActionPerformed='getTableModel().updateRowFromEditBean()'/> - </cell> - <cell weightx='1'> - <!-- sauver dans le tableau la nouvelle entrée (en mode creation) --> - <JButton id='saveNewEntry' - onActionPerformed='getTableModel().updateRowFromEditBean()'/> - </cell> - <cell weightx='1'> - <!-- supprimer l'entrée courante dans le tableau (en mode mise a jour)--> - <JButton id='deleteEntry' - onActionPerformed='getHandler().removeSelectedRow(getTableModel().getSelectedRow())'/> - </cell> - </row> - </Table> - </cell> - </row> - </Table> - </cell> - </row> - <row> - <cell> - - <Table id='extraZone' decorator='boxed'/> - - </cell> - </row> - </Table> - - </JPanel> - - <!-- actions de l'écran --> - - <Table id="actions" fill='both' weightx='1' insets='0'> - <row fill="both"> - <!-- remonter dans l'arbre de navigation --> - <!--cell weightx="0.5"> - <JButton id='up'/> - </cell--> - <cell weightx="0.5"> - <!-- réinitialiser l'écran --> - <JButton id='reset'/> - </cell> - <cell weightx="0.5"> - <!-- sauver les modifications de l'écran --> - <JButton id='save'/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.ContentUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableUI.jcss deleted file mode 100644 index bef74b9..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableUI.jcss +++ /dev/null @@ -1,144 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#model { - valid:{getValidator().isValid() && getValidatorTable().isValid()}; - modified:{tableModel.isModified() || getValidator().isChanged()}; - canSaveRow:{getValidatorTable().isChanged() && getValidatorTable().isValid()}; - canResetRow:{getValidatorTable().isChanged()}; - editable:true; - enabled:{!model.isReadingMode()}; -} - -#body { - layout:{new BorderLayout()}; -} - -#tableModel { - editable:{!model.isReadingMode()}; -} - -#selectionModel { - selectionMode:{ListSelectionModel.SINGLE_SELECTION}; -} - -#editorBlockLayerUI { - useIcon:false; - blockingColor:{UIManager.getColor("BlockingLayerUI.blockingColor")}; - block:{!tableModel.isEditable()}; -} - -#tableScrollPane { - columnHeaderView:{table.getTableHeader()}; - minimumSize:{new Dimension(10, 100)}; -} - -#table { - model:{tableModel}; - selectionModel:{selectionModel}; - rowSelectionAllowed:true; - autoResizeMode:2; - fillsViewportHeight:true; -} - -#editor { - border:{new TitledBorder("")}; -} - -#editorPanel { - visible:{!tableModel.isEmpty()}; -} - -#editorActions { - visible:{tableModel.isEditable()}; -} - -#newEntry { - text:{getNewEntryText()}; - toolTipText:{getNewEntryTip()}; - actionIcon:"add"; - visible:{tableModel.isEditable() && !tableModel.isCreate()}; -} - -#resetNewEntry{ - text:{getResetNewEntryText()}; - toolTipText:{getResetNewEntryTip()}; - actionIcon:"revert"; - enabled:true; - visible:{tableModel.isEditable() && tableModel.isCreate()}; -} - -#resetEntry { - text:{getResetEntryText()}; - toolTipText:{getResetEntryTip()}; - actionIcon:"revert"; - enabled:{model.isCanResetRow()}; - visible:{tableModel.isEditable() && !tableModel.isEmpty() && !tableModel.isCreate()}; -} - -#saveEntry{ - text:{getSaveEntryText()}; - toolTipText:{getSaveEntryTip()}; - actionIcon:"save"; - visible:{tableModel.isEditable() && !tableModel.isEmpty() && !tableModel.isCreate()}; - enabled:{model.isCanSaveRow()}; -} - -#saveNewEntry { - text:{getSaveNewEntryText()}; - toolTipText:{getSaveNewEntryTip()}; - actionIcon:"add"; - visible:{tableModel.isEditable() && !tableModel.isEmpty() && tableModel.isCreate()}; - enabled:{model.isCanSaveRow()}; -} - -#deleteEntry { - text:{getDeleteEntryText()}; - toolTipText:{getDeleteEntryTip()}; - actionIcon:"delete"; - visible:{tableModel.isEditable() && !tableModel.isEmpty() && !tableModel.isCreate()}; -} - -#up { - _observeAction:{fr.ird.observe.ui.actions.shared.GoUpUIAction.ACTION_NAME}; - visible:{!model.isCreatingMode()}; -} - -#reset { - _observeAction:{ResetEditUIAction.ACTION_NAME}; - visible:{model.isEnabled()}; - enabled:{model.isModified()}; -} - -#save { - _observeAction:{SaveEditUIAction.ACTION_NAME}; - _toolTipText:{t("observe.action.save.all.tip")}; - visible:{model.isEnabled()}; - enabled:{model.isModified() && model.isValid() && !tableModel.isCreate()}; -} - -#hideFormInformation { - actionIcon:"information"; - font-size:11; - verticalAlignment:"center"; - horizontalAlignment:"center"; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableUIHandler.java deleted file mode 100644 index c33f1a6..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableUIHandler.java +++ /dev/null @@ -1,484 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.table; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.SpeciesDto; -import fr.ird.observe.services.dto.referential.seine.WeightCategoryDto; -import fr.ird.observe.services.dto.seine.TargetCatchDto; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.ContentUIHandler; -import fr.ird.observe.ui.content.ContentUIModel; -import fr.ird.observe.ui.content.table.impl.longline.WeightMeasuresTableModel; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.util.table.EditableTableModelSupport; -import fr.ird.observe.ui.util.table.InlineTableAutotSelectRowAndShowPopupAction; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.SwingUtilities; -import javax.swing.event.ListSelectionEvent; -import javax.swing.event.TableModelEvent; -import javax.swing.table.DefaultTableCellRenderer; -import java.awt.Rectangle; -import java.beans.PropertyChangeListener; -import java.io.Serializable; -import java.util.List; -import java.util.Optional; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Le controleur d'un écran d'édition avec tableau. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public abstract class ContentTableUIHandler<E extends IdDto, D extends IdDto> extends ContentUIHandler<E> { - - /** Logger */ - private static final Log log = LogFactory.getLog(ContentTableUIHandler.class); - - protected ContentTableUIHandler(ObserveContentTableUI<E, D> ui, DataContextType dataContextType) { - super(ui, dataContextType, null); - } - - /** - * Hook lors du changement d'entrée éditée. - * - * @param editingRow la nouvelle entrée à editer - * @param bean le bean d'édition d'une entrée - * @param create un drapeau pour savoir si l'entrée est en création - */ - protected abstract void onSelectedRowChanged(int editingRow, D bean, boolean create); - - @Override - protected boolean computeCanWrite(ObserveSwingDataSource source) { - return source.canWriteData(); - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - // par defaut, on suppose qu'on peut afficher les données - getModel().setShowData(true); - - String activityId = dataContext.getSelectedActivityId(); - - if (getOpenDataManager().isOpenActivity(activityId)) { - - // mode mise a jour - return ContentMode.UPDATE; - } - - // mode lecture - - if (dataContext.isSelectedActivityLongline()) { - - addInfoMessage(t("observe.storage.activityLongline.message.not.open")); - - } else { - - addInfoMessage(t("observe.storage.activitySeine.message.not.open")); - - } - - return ContentMode.READ; - } - - @Override - public ContentTableUIModel<E, D> getModel() { - return (ContentTableUIModel<E, D>) super.getModel(); - } - - @Override - public ObserveContentTableUI<E, D> getUi() { - return (ObserveContentTableUI<E, D>) super.getUi(); - } - - public final D getTableEditBean() { - return getModel().getTableEditBean(); - } - - public final void updateEditor(ListSelectionEvent event) { - - final ObserveContentTableUI<E, D> ui = getUi(); - - if (ui.getValidatorTable() == null) { - log.debug("skip validator is null!"); - return; - } - if (getBean() == null) { - log.debug("skip bean is null!"); - return; - } - if (log.isDebugEnabled()) { - log.debug(event); - } - if (getTableModel().isEmpty()) { - // le modele est vide, on ne propage rien - //FIXME le modèle de selection ne devrait plus declancher des evenement - //FIXME des que le modele est vide ? - log.debug("empty model, do nothing"); - return; - } - - ListSelectionModel sModel = (ListSelectionModel) event.getSource(); - int newIndex = sModel.getAnchorSelectionIndex(); - - if (newIndex == -1 || sModel.isSelectionEmpty()) { - //FIXME le modèle de selection ne devrait plus declancher des evenement - //FIXME des que le modele est vide ? - log.debug("skip with row == -1, or empty selection, do nothing"); - return; - } - - SwingUtilities.invokeLater(() -> { - if (!ui.getSelectionModel().isSelectionEmpty()) { - // on veut toujours que la ligne sélectionnée soit visible - Rectangle rect = ui.getTable().getCellRect(ui.getSelectionModel().getAnchorSelectionIndex(), 0, false); - ui.getTable().scrollRectToVisible(rect); - } - }); - - int selectedRow = getTableModel().getSelectedRow(); - if (newIndex == selectedRow) { - // on bloque du code re-entrant - log.debug("new index already set in model " + newIndex + ", do nothing"); - return; - } - // on doit changer de ligne selectionne dans le modele - getTableModel().changeSelectedRow(newIndex); - } - - protected abstract void initTableUI(DefaultTableCellRenderer renderer); - - protected abstract String getEditBeanIdToLoad(); - - protected E loadEditBean(ContentMode mode) { - - String id = getEditBeanIdToLoad(); - - if (id == null) { - throw new IllegalStateException("Could not find id form " + this); - } - - E editBean = getBean(); - - // preparation du bean d'édition - loadEditBean(id); - - // initialisation du modèle du tableau - getUi().getTableModel().attachModel(); - - return editBean; - } - - protected abstract void loadEditBean(String beanId); - - //FIXME -// @Override -// protected final void onLoad(TopiaContext tx, E bean) throws TopiaException { -// super.onLoad(tx, bean); -// -// // on duplique la liste des fils traites dans le tableau -// // sinon on reste sur les references d'origine et on aura pas -// // la possibilité d'annuler l'edition ensuite car on aura modifie -// // les entrées d'origine... -// E editBean = getBean(); -// Collection<D> data = loadChilds(tx, editBean); -// getModel().getChildsUpdator().setChilds(editBean, data); -// } - - //FIXME -// protected Collection<D> loadChilds(TopiaContext tx, E bean) throws TopiaException { -// Collection<D> childs = getModel().getChildsUpdator().getChilds(bean); -// Collection<D> data = new ArrayList<D>(); -// if (CollectionUtils.isNotEmpty(childs)) { -// Loador<D> loader = getModel().getChildLoador(); -// TopiaDAO<D> dao = getMainDataSource().getDAO(tx, getTableEditBean()); -// for (D c : childs) { -// try { -// D cUp = dao.findByTopiaId(c.getTopiaId()); -// D c2 = getModel().newTableEditBean(); -// loader.load(cUp, c2, true); -// data.add(c2); -// } catch (Exception e) { -// throw new RuntimeException(e); -// } -// } -// } -// return data; -// } - - @Override - public void initUI() { - - final ContentTableUIInitializer<E, D, ObserveContentTableUI<E, D>> uiInitializer = - new ContentTableUIInitializer<>(getUi()); - uiInitializer.initUI(); - - getModel().addPropertyChangeListener(ContentUIModel.PROPERTY_FORM, evt -> updateUiWithReferenceSetsFromModel()); - - } - - @Override - public void openUI() { - - super.openUI(); - - // récupération du mode de l'écran - ContentMode mode = computeContentMode(); - - ObserveContentTableUI<E, D> ui = getUi(); - - int oldIndex = ui.getTableModel().getSelectedRow(); - - ui.getTableModel().dettachModel(); - - getModel().setMode(mode); - - // chargement du bean d'édition - loadEditBean(mode); - - boolean canEdit = mode == ContentMode.UPDATE; - - if (canEdit) { - // on lance le mode edition - ui.startEdit(null); - } - - if (!ui.getTableModel().isEmpty()) { - if (ui.getTableModel().getRowCount() <= oldIndex) { - oldIndex = 0; - } - if (oldIndex == -1) { - oldIndex = 0; - } - - // le tableau contient au moins une entrée - // on la sélectionne la première entrée - ui.getTableModel().changeSelectedRow(oldIndex); - } - - if (canEdit) { - - // on force l'ecran en non modification - //FIXME normalement, on ne devrait pas a avoir a faire ca ? - //FIXME mais il est possible que les validateurs modifient l'état - //FIXME modified sur l'ecran lors des bindings d'initilisation... - getModel().setModified(false); - } - } - - @Override - public void startEditUI(String... binding) { - - addUpdateInfoMessage(); - super.startEditUI(binding); - } - - protected void addUpdateInfoMessage() { - String message = n("observe.entity.message.updating"); - ObserveNode node = getTreeHelper(getUi()).getSelectedNode(); - String entityLabel = - getEntityLabel(node.getParent().getInternalClass()); - message = t(message, t(entityLabel)); - addMessage(getUi(), NuitonValidatorScope.INFO, entityLabel, message); - } - - public void removeSelectedRow(int selectedRow) { - try { - getTableModel().doRemoveRow(selectedRow, false); - } finally { - - // always reset busy model to false - ObserveSwingApplicationContext.get().getMainUI().setBusy(false); - } - } - - @Override - protected boolean doSave(E bean) throws Exception { - - ObserveContentTableUI<E, D> ui = getUi(); - - List<D> objets = ui.getTableModel().getData(); - - boolean canContinue; - try { - canContinue = prepareSave(bean, objets); - } catch (Exception e) { - UIHelper.handlingError(e); - canContinue = false; - } - if (!canContinue) { - - // l'utilisateur a choisi de ne pas sauvegarder - return false; - } - doPersist(bean); - - return true; - } - - protected abstract void doPersist(E bean); - - //FIXME -// @Override -// protected E onUpdate(TopiaContext tx, Object parentBean, E beanToSave) throws TopiaException { -// -// List<D> childs = getUi().getTableModel().getData(); -// -// E editBean = getBean(); -// -// TopiaEntityBinder<E> binder = getLoadBinder(); -// -// Loador<D> childBinder = getModel().getChildLoador(); -// -// EntityListUpdator<E, D> childUpdator = getModel().getChildsUpdator(); -// -// // recopie des propriétés du bean en excluant toujours la liste des fils -// binder.copyExcluding(editBean, beanToSave, childUpdator.getPropertyName()); -// -// // on conserve l'ancienne liste des fils (pour traitement ultérieure) -// Collection<D> oldChilds = -// new ArrayList<D>(childUpdator.getChilds(beanToSave)); -// -// // suppression des fils dans le bean a sauver -// childUpdator.removeAll(beanToSave); -// -// TopiaDAO<D> dao = ObserveDAOHelper.getDAO(tx, getModel().getChildType()); -// -// for (D child : childs) { -// -// D childToSave; -// -// if (child.getTopiaId() == null) { -// -// // creation du fils -// Map<String, Object> map = childBinder.obtainProperties(child); -// -// childToSave = dao.create(map); -// -// } else { -// -// // mise a jour du fils -// -// childToSave = dao.findByTopiaId(child.getTopiaId()); -// -// childBinder.load(child, childToSave, false); -// } -// -// // ajout du fils au bean à sauver -// childUpdator.addToList(beanToSave, childToSave); -// } -// -// // on donne la main aux implantations pour faire des traitements -// // supplémentaires -// onUpdateFinalize(tx, beanToSave, oldChilds); -// -// return beanToSave; -// } - - @Override - protected void afterSave(boolean refresh) { - - // on recharge l'écran - resetEditUI(); - } - - protected boolean prepareSave(E editBean, List<D> objets) throws Exception { - - // par defaut, rien de specifique a faire avant de faire la sauvegarde - return true; - } - - //FIXME -// protected void onUpdateFinalize(TopiaContext tx, E bean, Collection<D> oldChilds) throws TopiaException { -// // par défaut, rien à faire -// } - - protected ContentTableModel<E, D> getTableModel() { - return getUi().getTableModel(); - } - - protected void resetEditBean() { - getTableModel().resetEditBean(); - } - - /** - * @param weightCategory la catégorie de poids - * @return la référence sur l'espèce de la catégorie de poids - */ - protected Optional<ReferentialReference<SpeciesDto>> getWeightCategorySpecies(ReferentialReference<WeightCategoryDto> weightCategory) { - - String speciesId = (String) weightCategory.getPropertyValue(WeightCategoryDto.PROPERTY_SPECIES); - - Optional<ReferentialReference<SpeciesDto>> optionalSpecies = getModel().tryGetReferentialReferenceById(TargetCatchDto.PROPERTY_SPECIES, speciesId); - - return optionalSpecies; - } - - protected <EE extends Serializable, MM extends EditableTableModelSupport<EE>> void initInlineTable(JScrollPane pane, - JTable table, - MM tableModel, - PropertyChangeListener modifiedListener, - JPopupMenu popup, - JMenuItem addMeasure, - JMenuItem deleteMeasure) { - - tableModel.addPropertyChangeListener(WeightMeasuresTableModel.MODIFIED_PROPERTY, modifiedListener); - - ListSelectionModel selectionModel = table.getSelectionModel(); - selectionModel.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - tableModel.installSelectionListener(table); - tableModel.installTableKeyListener(table); - - tableModel.addTableModelListener(e -> { - if (e.getType() == TableModelEvent.DELETE) { - tableModel.validate(); - } - }); - - new InlineTableAutotSelectRowAndShowPopupAction<>( - pane, - table, - tableModel, - popup, - addMeasure, - deleteMeasure); - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableUIInitializer.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableUIInitializer.java deleted file mode 100644 index 1e47a6d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableUIInitializer.java +++ /dev/null @@ -1,257 +0,0 @@ -package fr.ird.observe.ui.content.table; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.ui.content.ContentUIInitializer; -import fr.ird.observe.ui.util.BooleanEditor; -import jaxx.runtime.SwingUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.jaxx.application.bean.JavaBeanObjectUtil; - -import javax.swing.AbstractButton; -import javax.swing.ActionMap; -import javax.swing.JCheckBox; -import javax.swing.JComponent; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.table.DefaultTableCellRenderer; -import java.awt.BorderLayout; -import java.awt.event.ItemEvent; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; - -/** - * To initialize ui. - * - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class ContentTableUIInitializer<E extends IdDto, D extends IdDto, UI extends ObserveContentTableUI<E, D>> extends ContentUIInitializer<E, UI> { - - public static final String CLIENT_PROPERTY_TABLE_PROPERTY_NAME = "tablePropertyName"; - - public static final String CLIENT_PROPERTY_RESET_TABLE_PROPERTY_NAME = "resetTablePropertyName"; - - /** Logger. */ - private static final Log log = LogFactory.getLog(ContentTableUIInitializer.class); - - public ContentTableUIInitializer(UI ui) { - super(ui); - } - - protected D getTableEditBean() { - return getModel().getTableEditBean(); - } - - protected ContentTableUIModel<E, D> getModel() { - return ui.getModel(); - } - - protected ContentTableUIHandler<E, D> getHandler() { - return ui.getHandler(); - } - - @Override - public void initUI() { - - super.initUI(); - - ContentTableModel<?, ?> tableModel = ui.getTableModel(); - ui.setContextValue(tableModel); - - if (ui.getBody() != null) { - - // on supprime le layer de blocage en mode disable - SwingUtil.setLayerUI(ui.getBody(), null); - - } - - if (ui.getExtraZone() != null) { - - // et on le remet sur les zones non clicables de l'ui - SwingUtil.setLayerUI(ui.getExtraZone(), ui.getBlockLayerUI()); - - } - - // on ajoute un layer pour bloquer l'édition des entrées si nécessaire - SwingUtil.setLayerUI(ui.getEditor(), ui.getEditorBlockLayerUI()); - - // préparation du tableau dans l'ui - getHandler().initTableUI(new DefaultTableCellRenderer()); - - // ajout d'un listener pour preparer l'éditeur d'une entrée selectionnée - tableModel.addPropertyChangeListener( - ContentTableModel.SELECTED_ROW_PROPERTY, - evt -> { - ContentTableModel<E, D> model; - model = (ContentTableModel<E, D>) evt.getSource(); - D bean = model.getRowBean(); - boolean create = bean.getId() == null; - Integer selectedRow = (Integer) evt.getNewValue(); - if (log.isDebugEnabled()) { - log.debug("callback new selectedRow : " + selectedRow + " : " + bean.getId()); - } - getHandler().onSelectedRowChanged(selectedRow, bean, create); - getModel().setRowSaved(!create); - if (selectedRow == -1) { - if (log.isDebugEnabled()) { - log.debug(">>>>>>>>>> will clear selection..."); - } - // on supprime la selection - ui.getSelectionModel().clearSelection(); - if (log.isDebugEnabled()) { - log.debug("<<<<<<<<<< has clear selection..."); - } - } else { - // on met a jour le modele de selection - ui.getSelectionModel().setSelectionInterval( - selectedRow, selectedRow); - } - }); - - getModel().addPropertyChangeListener( - ContentTableUIModel.PROPERTY_SHOW_DATA, - evt -> { - - Boolean newValue = (Boolean) evt.getNewValue(); - onShowDataChanged(newValue); - - }); - - } - - @Override - protected void initBlockLayerUI(String... doNotBlockComponentIds) { - - super.initBlockLayerUI(doNotBlockComponentIds); - - //tchemit-2014-12-29 We should use a spearate list for this, but there is no collision possible... - ui.getEditorBlockLayerUI().setAcceptedComponentNames(doNotBlockComponentIds); - - } - - protected void onShowDataChanged(Boolean showData) { - - JComponent body = ui.getBody(); - if (showData != null && showData) { - body.remove(ui.getHideForm()); - body.add(ui.getShowForm(), BorderLayout.CENTER); - } else { - body.remove(ui.getShowForm()); - body.add(ui.getHideForm(), BorderLayout.CENTER); - } - } - - @Override - protected void init(ActionMap actionMap, - AbstractButton editor) { - - super.init(actionMap, editor); - - String actionId = (String) editor.getClientProperty(ContentUIInitializer.OBSERVE_ACTION); - if (actionId == null) { - - // le boutton n'est pas commun - - final String propertyName = (String) editor.getClientProperty(CLIENT_PROPERTY_RESET_TABLE_PROPERTY_NAME); - if (propertyName != null) { - editor.addActionListener(e -> JavaBeanObjectUtil.setProperty(getTableEditBean(), propertyName, null)); - } - - } - - } - - @Override - protected void init(JTextField editor) { - - super.init(editor); - - final String propertyName = (String) editor.getClientProperty(CLIENT_PROPERTY_TABLE_PROPERTY_NAME); - if (propertyName != null) { - editor.addKeyListener(new KeyAdapter() { - @Override - public void keyReleased(KeyEvent e) { - JTextField source = (JTextField) e.getSource(); - String text = source.getText(); - JavaBeanObjectUtil.setProperty(getTableEditBean(), propertyName, text); - } - }); - } - - } - - @Override - protected void init(JTextArea editor) { - - final String propertyName = (String) editor.getClientProperty(CLIENT_PROPERTY_TABLE_PROPERTY_NAME); - if (propertyName != null) { - editor.addKeyListener(new KeyAdapter() { - @Override - public void keyReleased(KeyEvent e) { - JTextArea source = (JTextArea) e.getSource(); - String text = source.getText(); - JavaBeanObjectUtil.setProperty(getTableEditBean(), propertyName, text); - } - }); - } - - } - - @Override - protected void init(final JCheckBox editor) { - - super.init(editor); - - final String propertyName = (String) editor.getClientProperty(CLIENT_PROPERTY_TABLE_PROPERTY_NAME); - if (propertyName != null) { - editor.addItemListener(event -> { - Boolean newValue = ((JCheckBox) event.getSource()).isSelected(); - JavaBeanObjectUtil.setProperty(getTableEditBean(), propertyName, newValue); - }); - } - - } - - @Override - protected void init(BooleanEditor editor) { - - super.init(editor); - - final String propertyName = (String) editor.getClientProperty(CLIENT_PROPERTY_TABLE_PROPERTY_NAME); - if (propertyName != null) { - editor.addItemListener(event -> { - if (event.getStateChange() == ItemEvent.SELECTED) { - - Boolean newValue = ((BooleanEditor) event.getSource()).getBooleanValue(); - JavaBeanObjectUtil.setProperty(getTableEditBean(), propertyName, newValue); - } - }); - } - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableUIModel.java deleted file mode 100644 index 778a655..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ContentTableUIModel.java +++ /dev/null @@ -1,313 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.table; - -import fr.ird.observe.ObserveSwingBinderService; -import fr.ird.observe.ObserveSwingTechnicalException; -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.ui.content.ContentUIModel; -import org.apache.commons.lang3.reflect.ConstructorUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.util.beans.BinderModelBuilder; - -import javax.swing.DefaultListSelectionModel; -import javax.swing.ListSelectionModel; -import java.util.List; - -/** - * Le modèle d'un écran d'édition avec tableau. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public abstract class ContentTableUIModel<E extends IdDto, D extends IdDto> extends ContentUIModel<E> { - - public static final String PROPERTY_CAN_SAVE_ROW = "canSaveRow"; - - public static final String PROPERTY_CAN_RESET_ROW = "canResetRow"; - - public static final String PROPERTY_SHOW_DATA = "showData"; - - public static final String PROPERTY_ROW_SAVED = "rowSaved"; - - private static final long serialVersionUID = 1L; - - /** Logger */ - private static final Log log = LogFactory.getLog(ContentTableUIModel.class); - - protected final Class<D> childType; - - protected final String[] parentProperties; - - protected final String[] childProperties; - - private final transient ListSelectionModel selectionModel; - - protected D tableEditBean; - - protected boolean canSaveRow; - - protected boolean canResetRow; - - /** - * Pour savoir si on peut voir les données du l'écran. - * - * Cela diffère du mode de l'écran, à utiliser par exemple pour les écrans - * d'échantillons lorsqu'aucune discarded n'est effectuée. on se retrouve en - * mode ContentMode.READ mais ce n'est pas suffisant. - * - * @since 3.0 - */ - protected boolean showData; - - protected boolean rowSaved; - - private ContentTableModel<E, D> tableModel; - - public ContentTableUIModel(Class<E> beanType, - Class<D> childType, - String[] parentProperties, - String[] childProperties) { - super(beanType); - this.childType = childType; - this.parentProperties = parentProperties; - this.childProperties = childProperties; - this.selectionModel = new ContentTableListSelectionModel(); - } - - public static <E extends IdDto, D extends IdDto> ContentTableUIModel<E, D> newModel(ObserveContentTableUI<E, D> ui) { - - String uiName = ui.getClass().getName(); - String modelName = uiName + "Model"; - - try { - - Class<ContentTableUIModel<E, D>> modelClass = (Class<ContentTableUIModel<E, D>>) Class.forName(modelName); - ContentTableUIModel<E, D> model = ConstructorUtils.invokeConstructor(modelClass, ui); - return model; - - } catch (Exception e) { - throw new ObserveSwingTechnicalException("Could not create model for ui: " + ui, e); - } - - } - - public void initModel(ObserveContentTableUI<E, D> ui, List<ContentTableMeta<D>> metas) { - - this.tableModel = createTableModel(ui, metas); - - } - - protected abstract ContentTableModel<E, D> createTableModel(ObserveContentTableUI<E, D> ui, List<ContentTableMeta<D>> metas) ; - - public Class<D> getChildType() { - return childType; - } - - public String[] getParentProperties() { - return parentProperties; - } - - public String[] getChildProperties() { - return childProperties; - } - - public ContentTableModel<E, D> getTableModel() { - return tableModel; - } - - public ListSelectionModel getSelectionModel() { - return selectionModel; - } - - /** @return le bean d'une ligne du tableau actuellement sélectionné */ - public D getTableEditBean() { - if (tableEditBean == null) { - try { - tableEditBean = newTableEditBean(); - } catch (Exception e) { - - // ne devrait jamais arrive... - if (log.isErrorEnabled()) { - log.error(e); - } - } - } - return tableEditBean; - } - - public final D newTableEditBean() { - try { - - D result = getChildType().getConstructor().newInstance(); - return result; - - } catch (Exception ex) { - throw new RuntimeException(ex); - - } - } - - public boolean isCanSaveRow() { - return canSaveRow; - } - - public void setCanSaveRow(boolean canSaveRow) { - boolean oldValue = this.canSaveRow; - this.canSaveRow = canSaveRow; - firePropertyChange(PROPERTY_CAN_SAVE_ROW, oldValue, canSaveRow); - } - - public boolean isCanResetRow() { - return canResetRow; - } - - public void setCanResetRow(boolean canResetRow) { - boolean oldValue = this.canResetRow; - this.canResetRow = canResetRow; - firePropertyChange(PROPERTY_CAN_RESET_ROW, oldValue, canResetRow); - } - - public boolean isRowSaved() { - return rowSaved; - } - - public void setRowSaved(boolean rowSaved) { - boolean oldValue = this.rowSaved; - this.rowSaved = rowSaved; - firePropertyChange(PROPERTY_ROW_SAVED, oldValue, rowSaved); - } - - public boolean isShowData() { - return showData; - } - - public void setShowData(boolean showData) { - boolean oldValue = this.showData; - this.showData = showData; - firePropertyChange(PROPERTY_SHOW_DATA, oldValue, showData); - } - - protected BinderModelBuilder<D, D> prepareChildLoador(ObserveSwingBinderService binderService, String binderName) { - - String[] properties = getChildProperties(); - - BinderModelBuilder<D, D> builder = binderService.newBinderBuilder(childType, properties); - - return builder; - - } - - /** - * Le modèle de sélection pour un tableau. - * - * Le modèle permet le blocage du changement de ligne selectionnee dans le - * tableau lorsque les conditions suivantes sont remplies : - * - * - le tableau est editable - une entrée etait precedemment selectionne - - * l'entrée en cours d'édition est modifié - * - * Si on ne peut pas explicitement changer de ligne d'édition, on demande alors - * à l'utilisateur s'il veut sauver l'entrée en cours d'édition (si elle est - * valide), ou bien la perte des données (si elle n'est pas valide). - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ - public class ContentTableListSelectionModel extends DefaultListSelectionModel { - - private static final long serialVersionUID = 1L; - - public ContentTableListSelectionModel() { - } - - @Override - public void setSelectionInterval(int index0, int index1) { - if (log.isTraceEnabled()) { - log.trace(index0 + " - " + index1); - } - - ContentTableModel<?, ?> model = getTableModel(); - - boolean canContinue = canContinue(model, index0); - - if (log.isDebugEnabled()) { - log.debug("can continue for row " + index0 + " : " + canContinue); - } - - if (canContinue) { - // on peut aller sur la nouvelle ligne demandée - super.setSelectionInterval(index0, index1); - } - } - - protected boolean canContinue(ContentTableModel<?, ?> model, int newIndex) { - boolean canContinue; - if (model == null) { - // le model n'est pas encore disponible - return false; - } - - if (!model.isEditable()) { - // le modèle n'est pas editable - // donc aucun controle a effectuer - // on peut change de selection - return true; - } - - if (model.isValueAdjusting()) { - // le modele a demande un ajustement - // donc rien a valider - return true; - } - - // le modèle est editable - - int editingRow = model.getSelectedRow(); - - if (isSelectionEmpty() || editingRow == -1) { - // pas de precedente selection - // ou pas de ligne en cours d'edition - // on peut donc selectionner cette nouvelle ligne - return true; - } - - // le modele a une ligne en cours d'edition - - if (editingRow == newIndex) { - // on veut aller sur la ligne en cours d'edition - // aucune verification a faire - // ce cas peut arriver lors d'un adjustement de ligne - return true; - } - - // une ligne en cours d'edition est différente de celle qu'on - // veut attendre on demande au modèle si on peut quitter cette ligne - canContinue = model.isCanQuitEditingRow(); - - return canContinue; - } - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ObserveContentTableUI.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ObserveContentTableUI.java deleted file mode 100644 index 1725599..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/ObserveContentTableUI.java +++ /dev/null @@ -1,68 +0,0 @@ -package fr.ird.observe.ui.content.table; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.ui.content.ObserveContentUI; -import jaxx.runtime.swing.BlockingLayerUI; -import jaxx.runtime.validator.swing.SwingValidator; - -import javax.swing.*; - -/** - * Created on 10/5/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public interface ObserveContentTableUI<E extends IdDto, D extends IdDto> extends ObserveContentUI<E> { - - ContentTableUIHandler<E, D> getHandler(); - - ContentTableUIModel<E, D> getModel(); - - ContentTableModel<E, D> getTableModel(); - - JTable getTable(); - - - JComponent getBody(); - - JComponent getExtraZone(); - - JComponent getEditor(); - - JComponent getHideForm(); - - JComponent getShowForm(); - - ListSelectionModel getSelectionModel(); - - BlockingLayerUI getBlockLayerUI(); - - BlockingLayerUI getEditorBlockLayerUI(); - - SwingValidator<E> getValidator(); - - SwingValidator<D> getValidatorTable(); -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BaitsCompositionUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BaitsCompositionUI.jaxx deleted file mode 100644 index 55073a9..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BaitsCompositionUI.jaxx +++ /dev/null @@ -1,141 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.table.ContentTableUI - superGenericType='SetLonglineGlobalCompositionDto, BaitsCompositionDto' - contentTitle='{n("observe.content.baitsComposition.title")}' - saveNewEntryText='{n("observe.content.baitsComposition.action.create")}' - saveNewEntryTip='{n("observe.content.baitsComposition.action.create.tip")}'> - - <style source="../../CommonTable.jcss"/> - - <import> - fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto - fr.ird.observe.services.dto.longline.BaitsCompositionDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.longline.BaitTypeDto - fr.ird.observe.services.dto.referential.longline.BaitSettingStatusDto - fr.ird.observe.ui.content.table.* - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <BaitsCompositionUIHandler id='handler'/> - - <!-- model --> - <BaitsCompositionUIModel id='model'/> - - <!-- edit bean --> - <SetLonglineGlobalCompositionDto id='bean'/> - - <!-- table edit bean --> - <BaitsCompositionDto id='tableEditBean'/> - - <!-- table model --> - <ContentTableModel id='tableModel'/> - - <!-- le validateur de l'écran --> - <BeanValidator id='validator' autoField='true' context='ui-update-baitsComposition' - beanClass='fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto' - errorTableModel='{getErrorTableModel()}'> - <field name="baitsComposition" component="editorPanel"/> - </BeanValidator> - - <!-- le validateur d'une entrée de tableau --> - <BeanValidator id='validatorTable' autoField='true' context='ui-update' - beanClass='fr.ird.observe.services.dto.longline.BaitsCompositionDto' - errorTableModel='{getErrorTableModel()}'/> - - <Table id='editorPanel' fill='both' insets='1'> - - <!-- baitType --> - <row> - <cell> - <JLabel id='baitTypeLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='baitType' constructorParams='this' genericType='ReferentialReference<BaitTypeDto>' _entityClass='BaitTypeDto.class'/> - </cell> - </row> - - <!-- baitSettingStatus --> - <row> - <cell> - <JLabel id='baitSettingStatusLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='baitSettingStatus' constructorParams='this' genericType='ReferentialReference<BaitSettingStatusDto>' _entityClass='BaitSettingStatusDto.class'/> - </cell> - </row> - - <!-- individualSize --> - <row> - <cell> - <JLabel id='individualSizeLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='individualSize' constructorParams='this'/> - </cell> - </row> - - <!-- individualWeight --> - <row> - <cell> - <JLabel id='individualWeightLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='individualWeight' constructorParams='this'/> - </cell> - </row> - - <!-- proportion --> - <row> - <cell> - <JLabel id='proportionLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='proportion' constructorParams='this'/> - </cell> - </row> - - </Table> - - <Table id='extraZone' fill='both'> - - <!-- proportion sum --> - <row> - <cell> - <JLabel id='baitsCompositionProportionSumLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <JLabel id='baitsCompositionProportionSum'/> - </cell> - </row> - - </Table> - -</fr.ird.observe.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BaitsCompositionUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BaitsCompositionUI.jcss deleted file mode 100644 index 9bfb87e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BaitsCompositionUI.jcss +++ /dev/null @@ -1,90 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#baitTypeLabel { - text:"observe.content.baitsComposition.baitType"; - labelFor:{baitType}; -} - -#baitType { - property:{BaitsCompositionDto.PROPERTY_BAIT_TYPE}; - selectedItem:{tableEditBean.getBaitType()}; - _validatorLabel:{t("observe.content.baitsComposition.baitType")}; -} - -#baitSettingStatusLabel { - text:"observe.content.baitsComposition.baitSettingStatus"; - labelFor:{baitSettingStatus}; -} - -#baitSettingStatus { - property:{BaitsCompositionDto.PROPERTY_BAIT_SETTING_STATUS}; - selectedItem:{tableEditBean.getBaitSettingStatus()}; - _validatorLabel:{t("observe.content.baitsComposition.baitSettingStatus")}; -} - -#individualSizeLabel { - text:"observe.content.baitsComposition.individualSize"; - labelFor:{individualSize}; -} - -#individualSize { - property:{BaitsCompositionDto.PROPERTY_INDIVIDUAL_SIZE}; - model:{tableEditBean.getIndividualSize()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.baitsComposition.individualSize")}; -} - -#individualWeightLabel { - text:"observe.content.baitsComposition.individualWeight"; - labelFor:{individualWeight}; -} - -#individualWeight { - property:{BaitsCompositionDto.PROPERTY_INDIVIDUAL_WEIGHT}; - model:{tableEditBean.getIndividualWeight()}; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL3_PATTERN}; - _validatorLabel:{t("observe.content.baitsComposition.individualWeight")}; -} - -#proportionLabel { - text:"observe.content.baitsComposition.proportion"; - labelFor:{proportion}; -} - -#proportion { - property:{BaitsCompositionDto.PROPERTY_PROPORTION}; - model:{tableEditBean.getProportion()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.baitsComposition.proportion")}; -} - -#baitsCompositionProportionSumLabel { - text:"observe.content.baitsComposition.proportionSum"; - labelFor:{baitsCompositionProportionSum}; -} - -#baitsCompositionProportionSum { - text:{getStringValue(bean.getBaitsCompositionProportionSum())}; - _validatorLabel:{t("observe.content.baitsComposition.proportionSum")}; - font-weight:bold; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BaitsCompositionUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BaitsCompositionUIHandler.java deleted file mode 100644 index 4b2d3dd..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BaitsCompositionUIHandler.java +++ /dev/null @@ -1,124 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.longline.BaitsCompositionDto; -import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto; -import fr.ird.observe.services.dto.referential.longline.BaitSettingStatusDto; -import fr.ird.observe.services.dto.referential.longline.BaitTypeDto; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.table.ContentTableUIHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; - -import static org.nuiton.i18n.I18n.n; - -/** - * Created on 12/6/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.9 - */ -public class BaitsCompositionUIHandler extends ContentTableUIHandler<SetLonglineGlobalCompositionDto, BaitsCompositionDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(BaitsCompositionUIHandler.class); - - public BaitsCompositionUIHandler(BaitsCompositionUI ui) { - super(ui, DataContextType.SetLongline); - } - - @Override - public BaitsCompositionUI getUi() { - return (BaitsCompositionUI) super.getUi(); - } - - @Override - protected void onSelectedRowChanged(int editingRow, BaitsCompositionDto bean, boolean create) { - - if (getTableModel().isEditable()) { - if (log.isDebugEnabled()) { - log.debug("Row has changed to " + editingRow); - } - getUi().getBaitType().requestFocus(); - } - - } - - @Override - protected void initTableUI(DefaultTableCellRenderer renderer) { - - JTable table = getUi().getTable(); - - UIHelper.setI18nTableHeaderRenderer( - table, - n("observe.content.baitsComposition.table.baitType"), - n("observe.content.baitsComposition.table.baitType.tip"), - n("observe.content.baitsComposition.table.baitSettingStatus"), - n("observe.content.baitsComposition.table.baitSettingStatus.tip"), - n("observe.content.baitsComposition.table.individualSize"), - n("observe.content.baitsComposition.table.individualSize.tip"), - n("observe.content.baitsComposition.table.individualWeight"), - n("observe.content.baitsComposition.table.individualWeight.tip"), - n("observe.content.baitsComposition.table.proportion"), - n("observe.content.baitsComposition.table.proportion.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, BaitTypeDto.class)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, BaitSettingStatusDto.class)); - UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 4, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - - // when model change in table, let's recompute the proportion sum - table.getModel().addTableModelListener(e -> { - int proportionSum = getBean().getBaitsCompositionProportionSum(); - getBean().setBaitsCompositionProportionSum(proportionSum); - }); - - } - - @Override - protected String getEditBeanIdToLoad() { - return getDataContext().getSelectedSetId(); - } - - @Override - protected void doPersist(SetLonglineGlobalCompositionDto bean) { - // fait par le doSave de LonglineGlobalCompositionUIHandler - } - - @Override - protected void loadEditBean(String beanId) { - // fait par le loadEditBean de LonglineGlobalCompositionUIHandler - } - - @Override - public void afterSave(boolean refresh) { - super.afterSave(refresh); - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BaitsCompositionUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BaitsCompositionUIModel.java deleted file mode 100644 index c83b88b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BaitsCompositionUIModel.java +++ /dev/null @@ -1,94 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import fr.ird.observe.services.dto.longline.BaitsCompositionDto; -import fr.ird.observe.services.dto.longline.BaitsCompositionDtos; -import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; - -import java.util.Collection; -import java.util.List; - -/** - * Created on 12/6/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.9 - */ -public class BaitsCompositionUIModel extends ContentTableUIModel<SetLonglineGlobalCompositionDto, BaitsCompositionDto> { - - private static final long serialVersionUID = 1L; - - public BaitsCompositionUIModel(BaitsCompositionUI ui) { - super(SetLonglineGlobalCompositionDto.class, - BaitsCompositionDto.class, - new String[]{ - SetLonglineGlobalCompositionDto.PROPERTY_BAITS_COMPOSITION - }, - new String[]{BaitsCompositionDto.PROPERTY_BAIT_TYPE, - BaitsCompositionDto.PROPERTY_BAIT_SETTING_STATUS, - BaitsCompositionDto.PROPERTY_INDIVIDUAL_SIZE, - BaitsCompositionDto.PROPERTY_INDIVIDUAL_WEIGHT, - BaitsCompositionDto.PROPERTY_PROPORTION}); - - List<ContentTableMeta<BaitsCompositionDto>> metas = Lists.newArrayList( - ContentTableModel.newTableMeta(BaitsCompositionDto.class, BaitsCompositionDto.PROPERTY_BAIT_TYPE, false), - ContentTableModel.newTableMeta(BaitsCompositionDto.class, BaitsCompositionDto.PROPERTY_BAIT_SETTING_STATUS, false), - ContentTableModel.newTableMeta(BaitsCompositionDto.class, BaitsCompositionDto.PROPERTY_INDIVIDUAL_SIZE, false), - ContentTableModel.newTableMeta(BaitsCompositionDto.class, BaitsCompositionDto.PROPERTY_INDIVIDUAL_WEIGHT, false), - ContentTableModel.newTableMeta(BaitsCompositionDto.class, BaitsCompositionDto.PROPERTY_PROPORTION, false)); - - initModel(ui, metas); - - } - - @Override - protected ContentTableModel<SetLonglineGlobalCompositionDto, BaitsCompositionDto> createTableModel( - ObserveContentTableUI<SetLonglineGlobalCompositionDto, BaitsCompositionDto> ui, - List<ContentTableMeta<BaitsCompositionDto>> contentTableMetas) { - - return new ContentTableModel<SetLonglineGlobalCompositionDto, BaitsCompositionDto>(ui, contentTableMetas) { - private static final long serialVersionUID = 1L; - - @Override - protected Collection<BaitsCompositionDto> getChilds(SetLonglineGlobalCompositionDto bean) { - return bean.getBaitsComposition(); - } - - @Override - protected void load(BaitsCompositionDto source, BaitsCompositionDto target) { - BaitsCompositionDtos.copyBaitsCompositionDto(source, target); - } - - @Override - protected void setChilds(SetLonglineGlobalCompositionDto parent, List<BaitsCompositionDto> childs) { - parent.setBaitsComposition(childs); - } - }; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BranchlinesCompositionUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BranchlinesCompositionUI.jaxx deleted file mode 100644 index a9773a4..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BranchlinesCompositionUI.jaxx +++ /dev/null @@ -1,130 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.table.ContentTableUI - superGenericType='SetLonglineGlobalCompositionDto, BranchlinesCompositionDto' - contentTitle='{n("observe.content.branchlinesComposition.title")}' - saveNewEntryText='{n("observe.content.branchlinesComposition.action.create")}' - saveNewEntryTip='{n("observe.content.branchlinesComposition.action.create.tip")}'> - - <style source="../../CommonTable.jcss"/> - - <import> - fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto - fr.ird.observe.services.dto.longline.BranchlinesCompositionDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.longline.LineTypeDto - fr.ird.observe.ui.content.table.* - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <BranchlinesCompositionUIHandler id='handler'/> - - <!-- model --> - <BranchlinesCompositionUIModel id='model'/> - - <!-- edit bean --> - <SetLonglineGlobalCompositionDto id='bean'/> - - <!-- table edit bean --> - <BranchlinesCompositionDto id='tableEditBean'/> - - <!-- table model --> - <ContentTableModel id='tableModel'/> - - <!-- le validateur de l'écran --> - <BeanValidator id='validator' autoField='true' context='ui-update-branchlinesComposition' - beanClass='fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto' - errorTableModel='{getErrorTableModel()}'> - <field name="branchlinesComposition" component="editorPanel"/> - </BeanValidator> - - <!-- le validateur d'une entrée de tableau --> - <BeanValidator id='validatorTable' autoField='true' context='ui-update' - beanClass='fr.ird.observe.services.dto.longline.BranchlinesCompositionDto' - errorTableModel='{getErrorTableModel()}'/> - - <Table id='editorPanel' fill='both' insets='1'> - - <!-- topType --> - <row> - <cell> - <JLabel id='topTypeLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='topType' constructorParams='this' genericType='ReferentialReference<LineTypeDto>' _entityClass='LineTypeDto.class'/> - </cell> - </row> - - <!-- tracelineType --> - <row> - <cell> - <JLabel id='tracelineTypeLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='tracelineType' constructorParams='this' genericType='ReferentialReference<LineTypeDto>' _entityClass='LineTypeDto.class'/> - </cell> - </row> - - <!-- length --> - <row> - <cell> - <JLabel id='lengthLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='length' constructorParams='this'/> - </cell> - </row> - - <!-- proportion --> - <row> - <cell> - <JLabel id='proportionLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='proportion' constructorParams='this'/> - </cell> - </row> - - </Table> - - <Table id='extraZone' fill='both'> - - <!-- proportion sum --> - <row> - <cell> - <JLabel id='branchlinesCompositionProportionSumLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <JLabel id='branchlinesCompositionProportionSum'/> - </cell> - </row> - - </Table> - -</fr.ird.observe.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BranchlinesCompositionUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BranchlinesCompositionUI.jcss deleted file mode 100644 index 0b7b968..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BranchlinesCompositionUI.jcss +++ /dev/null @@ -1,78 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#topTypeLabel { - text:"observe.content.branchlinesComposition.topType"; - labelFor:{topType}; -} - -#topType { - property:{BranchlinesCompositionDto.PROPERTY_TOP_TYPE}; - selectedItem:{tableEditBean.getTopType()}; - _validatorLabel:{t("observe.content.branchlinesComposition.topType")}; -} - -#tracelineTypeLabel { - text:"observe.content.branchlinesComposition.tracelineType"; - labelFor:{tracelineType}; -} - -#tracelineType { - property:{BranchlinesCompositionDto.PROPERTY_TRACELINE_TYPE}; - selectedItem:{tableEditBean.getTracelineType()}; - _validatorLabel:{t("observe.content.branchlinesComposition.tracelineType")}; -} - -#lengthLabel { - text:"observe.content.branchlinesComposition.length"; - labelFor:{length}; -} - -#length { - property:{BranchlinesCompositionDto.PROPERTY_LENGTH}; - model:{tableEditBean.getLength()}; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL3_PATTERN}; - _validatorLabel:{t("observe.content.branchlinesComposition.length")}; -} - -#proportionLabel { - text:"observe.content.branchlinesComposition.proportion"; - labelFor:{proportion}; -} - -#proportion { - property:{BranchlinesCompositionDto.PROPERTY_PROPORTION}; - model:{tableEditBean.getProportion()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.branchlinesComposition.proportion")}; -} - -#branchlinesCompositionProportionSumLabel { - text:"observe.content.branchlinesComposition.proportionSum"; - labelFor:{branchlinesCompositionProportionSum}; -} - -#branchlinesCompositionProportionSum { - text:{getStringValue(bean.getBranchlinesCompositionProportionSum())}; - _validatorLabel:{t("observe.content.branchlinesComposition.proportionSum")}; - font-weight:bold; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BranchlinesCompositionUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BranchlinesCompositionUIHandler.java deleted file mode 100644 index ffcecef..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BranchlinesCompositionUIHandler.java +++ /dev/null @@ -1,121 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.longline.BranchlinesCompositionDto; -import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto; -import fr.ird.observe.services.dto.referential.longline.HookSizeDto; -import fr.ird.observe.services.dto.referential.longline.HookTypeDto; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.table.ContentTableUIHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; - -import static org.nuiton.i18n.I18n.n; - -/** - * Created on 12/6/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.9 - */ -public class BranchlinesCompositionUIHandler extends ContentTableUIHandler<SetLonglineGlobalCompositionDto, BranchlinesCompositionDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(BranchlinesCompositionUIHandler.class); - - public BranchlinesCompositionUIHandler(BranchlinesCompositionUI ui) { - super(ui, DataContextType.SetLongline); - } - - @Override - public BranchlinesCompositionUI getUi() { - return (BranchlinesCompositionUI) super.getUi(); - } - - @Override - protected void onSelectedRowChanged(int editingRow, BranchlinesCompositionDto bean, boolean create) { - - if (getTableModel().isEditable()) { - if (log.isDebugEnabled()) { - log.debug("Row has changed to " + editingRow); - } - getUi().getTopType().requestFocus(); - } - - } - - @Override - protected void initTableUI(DefaultTableCellRenderer renderer) { - - JTable table = getUi().getTable(); - - UIHelper.setI18nTableHeaderRenderer( - table, - n("observe.content.branchlinesComposition.table.topType"), - n("observe.content.branchlinesComposition.table.topType.tip"), - n("observe.content.branchlinesComposition.table.tracelineType"), - n("observe.content.branchlinesComposition.table.tracelineType.tip"), - n("observe.content.branchlinesComposition.table.length"), - n("observe.content.branchlinesComposition.table.length.tip"), - n("observe.content.branchlinesComposition.table.proportion"), - n("observe.content.branchlinesComposition.table.proportion.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, HookTypeDto.class)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, HookSizeDto.class)); - UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - - // when model change in table, let's recompute the proportion sum - table.getModel().addTableModelListener(e -> { - int proportionSum = getBean().getBranchlinesCompositionProportionSum(); - getBean().setBranchlinesCompositionProportionSum(proportionSum); - }); - - } - - @Override - protected String getEditBeanIdToLoad() { - return getDataContext().getSelectedSetId(); - } - - @Override - public void afterSave(boolean refresh) { - super.afterSave(refresh); - } - - @Override - protected void doPersist(SetLonglineGlobalCompositionDto bean) { - // fait par le doSave de LonglineGlobalCompositionUIHandler - } - - @Override - protected void loadEditBean(String beanId) { - // fait par le loadEditBean de LonglineGlobalCompositionUIHandler - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BranchlinesCompositionUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BranchlinesCompositionUIModel.java deleted file mode 100644 index 7520cd5..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/BranchlinesCompositionUIModel.java +++ /dev/null @@ -1,93 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import fr.ird.observe.services.dto.longline.BranchlinesCompositionDto; -import fr.ird.observe.services.dto.longline.BranchlinesCompositionDtos; -import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; - -import java.util.Collection; -import java.util.List; - -/** - * Created on 12/6/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.9 - */ -public class BranchlinesCompositionUIModel extends ContentTableUIModel<SetLonglineGlobalCompositionDto, BranchlinesCompositionDto> { - - private static final long serialVersionUID = 1L; - - public BranchlinesCompositionUIModel(BranchlinesCompositionUI ui) { - super(SetLonglineGlobalCompositionDto.class, - BranchlinesCompositionDto.class, - new String[]{ - SetLonglineGlobalCompositionDto.PROPERTY_BRANCHLINES_COMPOSITION - }, - new String[]{BranchlinesCompositionDto.PROPERTY_TOP_TYPE, - BranchlinesCompositionDto.PROPERTY_TRACELINE_TYPE, - BranchlinesCompositionDto.PROPERTY_LENGTH, - BranchlinesCompositionDto.PROPERTY_PROPORTION}); - - List<ContentTableMeta<BranchlinesCompositionDto>> metas = Lists.newArrayList( - ContentTableModel.newTableMeta(BranchlinesCompositionDto.class, BranchlinesCompositionDto.PROPERTY_TOP_TYPE, false), - ContentTableModel.newTableMeta(BranchlinesCompositionDto.class, BranchlinesCompositionDto.PROPERTY_TRACELINE_TYPE, false), - ContentTableModel.newTableMeta(BranchlinesCompositionDto.class, BranchlinesCompositionDto.PROPERTY_LENGTH, false), - ContentTableModel.newTableMeta(BranchlinesCompositionDto.class, BranchlinesCompositionDto.PROPERTY_PROPORTION, false)); - - initModel(ui, metas); - - } - - - @Override - protected ContentTableModel<SetLonglineGlobalCompositionDto, BranchlinesCompositionDto> createTableModel( - ObserveContentTableUI<SetLonglineGlobalCompositionDto, BranchlinesCompositionDto> ui, - List<ContentTableMeta<BranchlinesCompositionDto>> contentTableMetas) { - - return new ContentTableModel<SetLonglineGlobalCompositionDto, BranchlinesCompositionDto>(ui, contentTableMetas) { - private static final long serialVersionUID = 1L; - - @Override - protected Collection<BranchlinesCompositionDto> getChilds(SetLonglineGlobalCompositionDto bean) { - return bean.getBranchlinesComposition(); - } - - @Override - protected void load(BranchlinesCompositionDto source, BranchlinesCompositionDto target) { - BranchlinesCompositionDtos.copyBranchlinesCompositionDto(source, target); - } - - @Override - protected void setChilds(SetLonglineGlobalCompositionDto parent, List<BranchlinesCompositionDto> childs) { - parent.setBranchlinesComposition(childs); - } - }; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchAcquisitionModeEnum.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchAcquisitionModeEnum.java deleted file mode 100644 index 2292198..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchAcquisitionModeEnum.java +++ /dev/null @@ -1,66 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 9/10/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public enum CatchAcquisitionModeEnum { - - INDIVIDUAL(n("observe.catchAcquisitionModeEnum.INDIVIDUAL")), - - GROUPED(n("observe.catchAcquisitionModeEnum.GROUPED")); - - private final String i18nKey; - - CatchAcquisitionModeEnum(String i18nKey) { - this.i18nKey = i18nKey; - } - - public static CatchAcquisitionModeEnum valueOf(int ordinal) - throws IllegalArgumentException { - for (CatchAcquisitionModeEnum o : values()) { - if (o.ordinal() == ordinal) { - return o; - } - } - throw new IllegalArgumentException( - "could not find a " + CatchAcquisitionModeEnum.class.getSimpleName() + - " value for ordinal " + ordinal); - } - - public String getI18nKey() { - return i18nKey; - } - - @Override - public String toString() { - return t(i18nKey); - } -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchLonglineContentTableUIInitializer.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchLonglineContentTableUIInitializer.java deleted file mode 100644 index 20be675..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchLonglineContentTableUIInitializer.java +++ /dev/null @@ -1,65 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - - -import fr.ird.observe.services.dto.longline.CatchLonglineDto; -import fr.ird.observe.services.dto.longline.SetLonglineCatchDto; -import fr.ird.observe.ui.content.table.ContentTableUIInitializer; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.jaxx.application.bean.JavaBeanObjectUtil; - -import javax.swing.JCheckBox; - -/** - * Created on 3/17/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.15 - */ -public class CatchLonglineContentTableUIInitializer extends ContentTableUIInitializer<SetLonglineCatchDto, CatchLonglineDto, CatchLonglineUI> { - - /** Logger. */ - private static final Log log = LogFactory.getLog(CatchLonglineContentTableUIInitializer.class); - - public CatchLonglineContentTableUIInitializer(CatchLonglineUI ui) { - super(ui); - } - - @Override - protected void init(JCheckBox editor) { - if (log.isDebugEnabled()) { - log.debug("init simple boolean editor " + editor.getName()); - } - super.init(editor); - final String propertyName = (String) editor.getClientProperty("branchlineBeanPropertyName"); - if (propertyName != null) { - editor.addItemListener(event -> { - Boolean newValue = ((JCheckBox) event.getSource()).isSelected(); - JavaBeanObjectUtil.setProperty(ui.getBranchlineBean(), propertyName, newValue); - }); - } - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchLonglineTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchLonglineTableModel.java deleted file mode 100644 index f2a0b06..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchLonglineTableModel.java +++ /dev/null @@ -1,161 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.longline.CatchLonglineDto; -import fr.ird.observe.services.dto.longline.CatchLonglineDtos; -import fr.ird.observe.services.dto.longline.SetLonglineCatchDto; -import fr.ird.observe.services.dto.longline.SizeMeasureDto; -import fr.ird.observe.services.dto.longline.WeightMeasureDto; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; - -/** - * Created on 12/4/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.8 - */ -public class CatchLonglineTableModel extends ContentTableModel<SetLonglineCatchDto, CatchLonglineDto> { - - /** Logger. */ - private static final Log log = LogFactory.getLog(CatchLonglineTableModel.class); - - private static final long serialVersionUID = 1L; - - public CatchLonglineTableModel(ObserveContentTableUI<SetLonglineCatchDto, CatchLonglineDto> context, - List<ContentTableMeta<CatchLonglineDto>> contentTableMetas) { - super(context, contentTableMetas); - } - - @Override - public void addNewEntry() { - - int editingRow = getSelectedRow(); - - if (editingRow > -1) { - - // store sizes and weights for the selected row - // before creating a new one ? - CatchLonglineUIModel model = getModel(); - model.getSizeMeasuresTableModel().storeInCacheForRow(editingRow); - model.getWeightMeasuresTableModel().storeInCacheForRow(editingRow); - - } - - super.addNewEntry(); - } - - @Override - public void updateRowFromEditBean() { - - // store sizes and weights for the selected row - - int editingRow = getSelectedRow(); - - CatchLonglineUIModel model = getModel(); - - model.getSizeMeasuresTableModel().storeInCacheForRow(editingRow); - - List<SizeMeasureDto> sizeMeasures = model.getSizeMeasuresTableModel().getData().stream() - .filter(sizeMeasureDto -> sizeMeasureDto.getSizeMeasureType() != null) - .collect(Collectors.toList()); - - getRowBean().setSizeMeasure(sizeMeasures); - - model.getWeightMeasuresTableModel().storeInCacheForRow(editingRow); - - List<WeightMeasureDto> weightMeasures = model.getWeightMeasuresTableModel().getData().stream() - .filter(weightMeasureDto -> weightMeasureDto.getWeightMeasureType() != null) - .collect(Collectors.toList()); - - getRowBean().setWeightMeasure(weightMeasures); - - super.updateRowFromEditBean(); - - - } - - @Override - protected void removeRow(int row) { - super.removeRow(row); - - // remove sizes and weights for the deleted row - // also update rows to row - 1 (when after the deleted row) - CatchLonglineUIModel model = getModel(); - model.getSizeMeasuresTableModel().removeCacheForRow(row); - model.getWeightMeasuresTableModel().removeCacheForRow(row); - - } - - @Override - protected void setChilds(SetLonglineCatchDto parent, List<CatchLonglineDto> childs) { - parent.setCatchLongline(childs); - } - - @Override - public void resetEditBean() { - - int row = getSelectedRow(); - if (log.isInfoEnabled()) { - log.info("Reset edit bean at row: " + row); - } - CatchLonglineUIModel model = getModel(); - model.getSizeMeasuresTableModel().resetCacheForRow(row); - model.getWeightMeasuresTableModel().resetCacheForRow(row); - - super.resetEditBean(); - - } - - @Override - protected Collection<CatchLonglineDto> getChilds(SetLonglineCatchDto bean) { - return bean.getCatchLongline(); - } - - @Override - protected void load(CatchLonglineDto source, CatchLonglineDto target) { - CatchLonglineDtos.copyCatchLonglineDto(source, target); - } - - @Override - protected void resetRow(int row) { - super.resetRow(row); - - CatchLonglineUIModel model = getModel(); - model.getSizeMeasuresTableModel().resetCacheForRow(row); - model.getWeightMeasuresTableModel().resetCacheForRow(row); - } - - @Override - protected CatchLonglineUIModel getModel() { - return (CatchLonglineUIModel) super.getModel(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchLonglineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchLonglineUI.jaxx deleted file mode 100644 index ec30612..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchLonglineUI.jaxx +++ /dev/null @@ -1,434 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.table.ContentTableUI superGenericType='SetLonglineCatchDto, CatchLonglineDto' - contentTitle='{n("observe.content.catchLongline.title")}' - newEntryText='{n("observe.content.catchLongline.action.new")}' - newEntryTip='{n("observe.content.catchLongline.action.new.tip")}' - saveNewEntryText='{n("observe.content.catchLongline.action.create")}' - saveNewEntryTip='{n("observe.content.catchLongline.action.create.tip")}'> - - <style source="../../CommonTable.jcss"/> - - <import> - fr.ird.observe.services.dto.DataReference - fr.ird.observe.services.dto.CommentableDto - fr.ird.observe.services.dto.longline.BasketDto - fr.ird.observe.services.dto.longline.BranchlineDto - fr.ird.observe.services.dto.longline.CatchLonglineDto - fr.ird.observe.services.dto.longline.SectionDto - fr.ird.observe.services.dto.longline.SetLonglineCatchDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.SpeciesDto - fr.ird.observe.services.dto.referential.SexDto - fr.ird.observe.services.dto.referential.longline.BaitHaulingStatusDto - fr.ird.observe.services.dto.referential.longline.CatchFateLonglineDto - fr.ird.observe.services.dto.referential.longline.HealthnessDto - fr.ird.observe.services.dto.referential.longline.HookPositionDto - fr.ird.observe.services.dto.referential.longline.MaturityStatusDto - fr.ird.observe.services.dto.referential.longline.StomacFullnessDto - fr.ird.observe.ui.content.table.* - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - org.nuiton.jaxx.widgets.select.FilterableDoubleList - org.nuiton.jaxx.widgets.datetime.DateTimeEditor - - java.awt.Dimension - - java.util.Collection - - org.apache.commons.lang3.BooleanUtils - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <CatchLonglineUIHandler id='handler'/> - - <!-- model --> - <CatchLonglineUIModel id='model'/> - - <SizeMeasuresTableModel id='sizeMeasuresTableModel' initializer="getModel().getSizeMeasuresTableModel()"/> - - <WeightMeasuresTableModel id='weightMeasuresTableModel' initializer="getModel().getWeightMeasuresTableModel()"/> - - <!-- edit bean --> - <SetLonglineCatchDto id='bean'/> - - <!-- table edit bean --> - <CatchLonglineDto id='tableEditBean'/> - - <!-- table model --> - <ContentTableModel id='tableModel'/> - - <!-- edit branchline --> - <BranchlineDto id='branchlineBean' initializer='new BranchlineDto()'/> - - <!-- le validateur de l'écran --> - <BeanValidator id='validator' context='ui-update' - beanClass='fr.ird.observe.services.dto.longline.SetLonglineCatchDto' - errorTableModel='{getErrorTableModel()}'> - </BeanValidator> - - <!-- le validateur d'une entrée de tableau --> - <BeanValidator id='validatorTable' autoField='true' context='ui-update' - beanClass='fr.ird.observe.services.dto.longline.CatchLonglineDto' - errorTableModel='{getErrorTableModel()}' - parentValidator='{validator}'/> - - <!-- le validateur de la branchline --> - <BeanValidator id='branchlineValidator' context='ui-update-catchLongline' - beanClass='fr.ird.observe.services.dto.longline.BranchlineDto' - errorTableModel='{getErrorTableModel()}' - parentValidator='{validator}'> - <field name='depthRecorder' component='depthRecorder'/> - <field name='hookLost' component='hookLost'/> - <field name='traceCutOff' component='traceCutOff'/> - <field name='timer' component='timer'/> - <field name='timeSinceContact' component='timeSinceContact'/> - <field name='timerTimeOnBoard' component='timerTimeOnBoard'/> - <field name='baitHaulingStatus' component='baitHaulingStatus'/> - - </BeanValidator> - - <JPopupMenu id='sizeMeasuresTablePopup'> - <JMenuItem id='addSizeMeasure' onActionPerformed='getHandler().addSizeMeasure()'/> - <JMenuItem id='deleteSelectedSizeMeasure' onActionPerformed='getHandler().deleteSelectedSizeMeasure()'/> - </JPopupMenu> - - <JPopupMenu id='weightMeasuresTablePopup'> - <JMenuItem id='addWeightMeasure' onActionPerformed='getHandler().addWeightMeasure()'/> - <JMenuItem id='deleteSelectedWeightMeasure' onActionPerformed='getHandler().deleteSelectedWeightMeasure()'/> - </JPopupMenu> - - <ButtonGroup id='acquisitionModeGroup' - onStateChanged='getHandler().updateCatchAcquisitionMode((CatchAcquisitionModeEnum) acquisitionModeGroup.getSelectedValue())'/> - - <Table id='editorPanel' fill='both' insets='0'> - <row> - <cell weightx="1" weighty="1"> - <JTabbedPane id='fishingOperationTabPane'> - <tab id='caracteristicTab'> - <Table id='editForm' fill='both' insets='1'> - - <row> - <cell columns="4"> - <JPanel layout="{new GridLayout()}"> - - <!-- acquisition Mode --> - <JPanel id='acquisitionModePanel'> - <JRadioButton id='acquisitionModeIndividual'/> - <JRadioButton id='acquisitionModeGrouped'/> - </JPanel> - - <!-- location on longline --> - <Table id="locationOnLonglinePanel"> - <row> - <cell anchor="west"> - <JLabel id='sectionLabel'/> - </cell> - <cell fill="both" weightx="1"> - <BeanComboBox id='section' genericType='DataReference<SectionDto>' _entityClass='SectionDto.class' constructorParams='this'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='basketLabel'/> - </cell> - <cell fill="both" weightx="1"> - <BeanComboBox id='basket' genericType='DataReference<BasketDto>' _entityClass='BasketDto.class' constructorParams='this'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='branchlineLabel'/> - </cell> - <cell fill="both" weightx="1"> - <BeanComboBox id='branchline' genericType='DataReference<BranchlineDto>' _entityClass='BranchlineDto.class' constructorParams='this'/> - </cell> - </row> - </Table> - </JPanel> - </cell> - </row> - - <!-- speciesCatch --> - <row> - <cell> - <JLabel id='speciesCatchLabel'/> - </cell> - <cell weightx='1' anchor='east' columns="3"> - <BeanComboBox id='speciesCatch' genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class' constructorParams='this'/> - </cell> - - </row> - - <!-- count --> - <!-- total weight --> - <row> - <cell> - <JLabel id='countLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='count' constructorParams='this'/> - </cell> - <cell> - <JLabel id='totalWeightLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='totalWeight' constructorParams='this'/> - </cell> - </row> - - <!-- catch healthness --> - <!-- hook position --> - <row> - <cell> - <JLabel id='catchHealthnessLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='catchHealthness' constructorParams='this' genericType='ReferentialReference<HealthnessDto>' _entityClass='HealthnessDto.class'/> - </cell> - <cell> - <JLabel id='hookPositionLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='hookPosition' constructorParams='this' genericType='ReferentialReference<HookPositionDto>' _entityClass='HookPositionDto.class'/> - </cell> - </row> - - <!-- catch fate --> - <!-- discard healthness --> - <row> - <cell> - <JLabel id='catchFateLonglineLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='catchFateLongline' constructorParams='this' genericType='ReferentialReference<CatchFateLonglineDto>' _entityClass='CatchFateLonglineDto.class'/> - </cell> - <cell> - <JLabel id='discardHealthnessLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='discardHealthness' constructorParams='this' genericType='ReferentialReference<HealthnessDto>' _entityClass='HealthnessDto.class'/> - </cell> - </row> - - <!-- hookWhenDiscarded --> - <!-- photoReferences --> - <row> - <cell anchor='west' fill="both" columns="2"> - <JCheckBox id='hookWhenDiscarded'/> - </cell> - <cell anchor='west'> - <JLabel id='photoReferencesLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both"> - <JPanel layout='{new BorderLayout()}'> - <JToolBar id='photoReferencesToolbar' constraints='BorderLayout.WEST'> - <JButton id='resetPhotoReferences' styleClass='resetButton'/> - </JToolBar> - <JTextField id='photoReferences' constraints='BorderLayout.CENTER'/> - </JPanel> - </cell> - </row> - - </Table> - </tab> - - <tab id='depredatedFormTab'> - - <Table id='depredatedForm' fill='both' insets='1'> - - <!-- depredated --> - <row> - <cell anchor='west' fill="both"> - <JCheckBox id='depredated'/> - </cell> - </row> - - <!-- beatDiameter --> - <row> - <cell> - <JLabel id='beatDiameterLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='beatDiameter' constructorParams='this'/> - </cell> - </row> - - <!-- predator --> - <row> - <cell columns="2" fill="both" weighty="0.7"> - <JScrollPane id='predatorPane'> - <FilterableDoubleList id='predator' genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class'/> - </JScrollPane> - </cell> - </row> - - </Table> - </tab> - - <tab id='foodAndSexualFormTab'> - - <JPanel layout="{new BorderLayout()}"> - <Table id='foodAndSexualForm' fill='both' insets='1' constraints='BorderLayout.NORTH'> - - <!-- stomac fullness --> - <row> - <cell> - <JLabel id='stomacFullnessLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='stomacFullness' constructorParams='this' genericType='ReferentialReference<StomacFullnessDto>' _entityClass='StomacFullnessDto.class'/> - </cell> - </row> - - <!-- sex --> - <row> - <cell> - <JLabel id='sexLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='sex' constructorParams='this' genericType='ReferentialReference<SexDto>' _entityClass='SexDto.class'/> - </cell> - </row> - - <!-- maturity status --> - <row> - <cell> - <JLabel id='maturityStatusLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='maturityStatus' constructorParams='this' genericType='ReferentialReference<MaturityStatusDto>' _entityClass='MaturityStatusDto.class'/> - </cell> - </row> - - <!-- gonadeWeight --> - <row> - <cell> - <JLabel id='gonadeWeightLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='gonadeWeight' constructorParams='this'/> - </cell> - </row> - - </Table> - </JPanel> - - </tab> - - <tab id='sizeMeasuresFormTab'> - - <JScrollPane id='sizeMeasuresScrollPane'> - <JTable id='sizeMeasuresTable'/> - </JScrollPane> - - </tab> - - <tab id='weightMeasuresFormTab'> - - <JScrollPane id='weightMeasuresScrollPane'> - <JTable id='weightMeasuresTable'/> - </JScrollPane> - - </tab> - - <tab id='branchlineFormTab'> - - <JPanel layout="{new BorderLayout()}"> - <Table id='branchlineForm' fill='both' insets='3' constraints='BorderLayout.NORTH'> - - <!-- depthRecorder --> - <!-- hookLost --> - <!-- traceCutOff --> - <row> - <cell columns="3"> - <JPanel layout="{new GridLayout()}"> - <JCheckBox id='depthRecorder'/> - <JCheckBox id='hookLost'/> - <JCheckBox id='traceCutOff'/> - </JPanel> - </cell> - </row> - - <!-- timer --> - <!-- timeSinceContact --> - <row> - <cell anchor='east'> - <JCheckBox id='timer'/> - </cell> - <cell> - <JLabel id='timeSinceContactLabel'/> - </cell> - <cell> - <NumberEditor id='timeSinceContact' constructorParams='this'/> - </cell> - </row> - - <!-- timerTimeOnBoard --> - <row> - <cell columns="3"> - <DateTimeEditor id='timerTimeOnBoard' constructorParams='this'/> - </cell> - </row> - - <!-- baitHaulingStatus --> - <row> - <cell anchor='west'> - <JLabel id='baitHaulingStatusLabel'/> - </cell> - <cell anchor='east' weightx="1" fill="both" columns="2"> - <BeanComboBox id='baitHaulingStatus' constructorParams='this' genericType='ReferentialReference<BaitHaulingStatusDto>' _entityClass='BaitHaulingStatusDto.class'/> - </cell> - </row> - - <row> - <cell columns="3"> - <JPanel id='branchlineActions' layout="{new GridLayout()}"> - <JButton id='resetBranchline' onActionPerformed='getHandler().resetBranchline()'/> - <JButton id='saveBranchline' onActionPerformed='getHandler().saveBranchline()'/> - </JPanel> - </cell> - </row> - - </Table> - </JPanel> - - </tab> - - </JTabbedPane> - </cell> - </row> - <row> - <cell weighty='1'> - <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2'/> - </JScrollPane> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchLonglineUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchLonglineUI.jcss deleted file mode 100644 index a632997..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchLonglineUI.jcss +++ /dev/null @@ -1,475 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#model { - valid:{validator.isValid() && validatorTable.isValid() && getSizeMeasuresTableModel().isValid() && getWeightMeasuresTableModel().isValid()}; - canSaveRow:{validatorTable.isChanged() && validatorTable.isValid() && getSizeMeasuresTableModel().isValid() && getWeightMeasuresTableModel().isValid()}; - /*canSaveRow:{getHandler().canSaveRow(tableModel.isModified() , validatorTable.isChanged() , validatorTable.isValid() , getSizeMeasuresTableModel().isValid() , getWeightMeasuresTableModel().isValid())};*/ - canResetRow:{validatorTable.isChanged()}; - /*canResetRow:{getHandler().canResetRow(tableModel.isModified() , validatorTable.isChanged())};*/ -} - -/* ***************************************************************************** */ -/* CARACTERISTIC TAB ********************************************************** */ -/* ***************************************************************************** */ - -#caracteristicTab { - title:{t("observe.content.catchLongline.tab.caracteristics")}; - icon:{handler.getErrorIconIfFalse(model.isCaracteristicsTabValid())}; -} - -#acquisitionModeGroup { - selectedValue:{CatchAcquisitionModeEnum.valueOf(tableEditBean.getAcquisitionMode())}; -} - -#acquisitionModePanel { - border:{new TitledBorder(t("observe.content.catchLongline.acquisitionMode"))}; - layout:{new GridLayout(0,1)}; -} - -#acquisitionModeIndividual { - buttonGroup:acquisitionModeGroup; - value:{CatchAcquisitionModeEnum.INDIVIDUAL}; - text:{CatchAcquisitionModeEnum.INDIVIDUAL.getI18nKey()}; - selected:{tableEditBean.getAcquisitionMode() == 0}; - enabled:{!tableModel.isEditable() || tableModel.isCreate()}; -} - -#acquisitionModeGrouped { - buttonGroup:acquisitionModeGroup; - value:{CatchAcquisitionModeEnum.GROUPED}; - text:{CatchAcquisitionModeEnum.GROUPED.getI18nKey()}; - selected:{tableEditBean.getAcquisitionMode() == 1}; - enabled:{!tableModel.isEditable() || tableModel.isCreate()}; -} - -#locationOnLonglinePanel { - border:{new TitledBorder(t("observe.content.catchLongline.locationOnLongline"))}; -} -#sectionLabel { - text:"observe.content.catchLongline.section"; - labelFor:{section}; -} - -#section { - property:{CatchLonglineDto.PROPERTY_SECTION}; - selectedItem:{tableEditBean.getSection()}; - _listNoLoad:{true}; -} - -#basketLabel { - text:"observe.content.catchLongline.basket"; - labelFor:{basket}; -} - -#basket { - property:{CatchLonglineDto.PROPERTY_BASKET}; - selectedItem:{tableEditBean.getBasket()}; - _listNoLoad:{true}; -} - -#branchlineLabel { - text:"observe.content.catchLongline.branchline"; - labelFor:{branchline}; -} - -#branchline { - property:{CatchLonglineDto.PROPERTY_BRANCHLINE}; - selectedItem:{tableEditBean.getBranchline()}; - _listNoLoad:{true}; -} - -#speciesCatchLabel { - text:"observe.content.catchLongline.speciesCatch"; - labelFor:{speciesCatch}; -} - -#speciesCatch { - property:{CatchLonglineDto.PROPERTY_SPECIES_CATCH}; - selectedItem:{tableEditBean.getSpeciesCatch()}; - _validatorLabel:{t("observe.content.catchLongline.speciesCatch")}; -} - -#photoReferencesLabel{ - text:"observe.content.catchLongline.photoReferences"; - labelFor:{photoReferences}; -} - -#resetPhotoReferences{ - toolTipText:"observe.content.catchLongline.action.reset.photoReferences.tip"; - _resetTablePropertyName:{CatchLonglineDto.PROPERTY_PHOTO_REFERENCES}; -} - -#photoReferences { - text:{getStringValue(tableEditBean.getPhotoReferences())}; - _tablePropertyName:{CatchLonglineDto.PROPERTY_PHOTO_REFERENCES}; -} - -#countLabel { - text:"observe.content.catchLongline.count"; - labelFor:{count}; -} - -#count { - property:{CatchLonglineDto.PROPERTY_COUNT}; - model:{tableEditBean.getCount()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel: {t("observe.content.catchLongline.count")}; -} - -#totalWeightLabel { - text:"observe.content.catchLongline.totalWeight"; - labelFor:{totalWeight}; -} - -#totalWeight { - property:{CatchLonglineDto.PROPERTY_TOTAL_WEIGHT}; - model:{tableEditBean.getTotalWeight()}; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL3_PATTERN}; - _validatorLabel: {t("observe.content.catchLongline.totalWeight")}; -} - -#hookWhenDiscarded { - horizontalTextPosition:{JCheckBox.LEFT}; - text:"observe.content.catchLongline.hookWhenDiscarded"; - _tablePropertyName:{CatchLonglineDto.PROPERTY_HOOK_WHEN_DISCARDED}; - selected:{BooleanUtils.isTrue(tableEditBean.getHookWhenDiscarded())}; -} - -#catchFateLonglineLabel { - text:"observe.content.catchLongline.catchFateLongline"; - labelFor:{catchFateLongline}; -} - -#catchFateLongline { - property:{CatchLonglineDto.PROPERTY_CATCH_FATE_LONGLINE}; - selectedItem:{tableEditBean.getCatchFateLongline()}; - _validatorLabel: {t("observe.content.catchLongline.catchFateLongline")}; -} - -#catchHealthnessLabel { - text:"observe.content.catchLongline.catchHealthness"; - labelFor:{catchHealthness}; -} - -#catchHealthness { - property:{CatchLonglineDto.PROPERTY_CATCH_HEALTHNESS}; - selectedItem:{tableEditBean.getCatchHealthness()}; - _validatorLabel: {t("observe.content.catchLongline.catchHealthness")}; -} - -#discardHealthnessLabel { - text:"observe.content.catchLongline.discardHealthness"; - labelFor:{discardHealthness}; -} - -#discardHealthness { - property:{CatchLonglineDto.PROPERTY_DISCARD_HEALTHNESS}; - selectedItem:{tableEditBean.getDiscardHealthness()}; - _validatorLabel: {t("observe.content.catchLongline.discardHealthness")}; -} - -#catchFateLonglineLabel { - text:"observe.content.catchLongline.catchFateLongline"; - labelFor:{catchFateLongline}; -} - -#catchFateLongline { - property:{CatchLonglineDto.PROPERTY_CATCH_FATE_LONGLINE}; - selectedItem:{tableEditBean.getCatchFateLongline()}; - _validatorLabel: {t("observe.content.catchLongline.catchFateLongline")}; -} - -#hookPositionLabel { - text:"observe.content.catchLongline.hookPosition"; - labelFor:{hookPosition}; -} - -#hookPosition { - property:{CatchLonglineDto.PROPERTY_HOOK_POSITION}; - selectedItem:{tableEditBean.getHookPosition()}; - _validatorLabel: {t("observe.content.catchLongline.hookPosition")}; -} - -#comment { - columnHeaderView:{new JLabel(t("observe.content.catchLongline.comment"))}; -} - -#comment2 { - _tablePropertyName: {CommentableDto.PROPERTY_COMMENT}; - text:{getStringValue(tableEditBean.getComment())}; -} - -/* ***************************************************************************** */ -/* DEPREDATED TAB ************************************************************* */ -/* ***************************************************************************** */ - -#depredatedFormTab { - title:{t("observe.content.catchLongline.tab.depredated")}; - icon:{handler.getErrorIconIfFalse(model.isDepredatedTabValid())}; -} - -#beatDiameterLabel { - text:"observe.content.catchLongline.beatDiameter"; - labelFor:{beatDiameter}; -} - -#beatDiameter { - property:{CatchLonglineDto.PROPERTY_BEAT_DIAMETER}; - model:{tableEditBean.getBeatDiameter()}; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL3_PATTERN}; - _validatorLabel: {t("observe.content.catchLongline.beatDiameter")}; -} - -#depredated { - horizontalTextPosition:{JCheckBox.LEFT}; - text:"observe.content.catchLongline.depredated"; - _tablePropertyName:{CatchLonglineDto.PROPERTY_DEPREDATED}; - selected:{BooleanUtils.isTrue(tableEditBean.getDepredated())}; -} - -#predatorPane { - minimumSize:{new Dimension(10,150)}; -} - -#predator { - property: predator; - selected:{(Collection)tableEditBean.getPredator()}; - _validatorLabel: {t("observe.content.catchLongline.predator")}; - showListLabel: true; - universeLabel:{t("observe.content.catchLongline.availablePredator")}; - selectedLabel:{t("observe.content.catchLongline.selectedPredator")}; -} - -/* ***************************************************************************** */ -/* FOOD AND SEXUAL TAB ******************************************************** */ -/* ***************************************************************************** */ - -#foodAndSexualFormTab { - title:{t("observe.content.catchLongline.tab.foodAndSexual")}; - icon:{handler.getErrorIconIfFalse(model.isFoodAndSexualTabValid())}; -} - -#foodAndSexualForm { - border:{new TitledBorder( (String) null)}; -} - -#sexLabel { - text:"observe.content.catchLongline.sex"; - labelFor:{sex}; -} - -#sex { - property:{CatchLonglineDto.PROPERTY_SEX}; - selectedItem:{tableEditBean.getSex()}; - _validatorLabel:{t("observe.content.catchLongline.sex")}; -} - -#stomacFullnessLabel { - text:"observe.content.catchLongline.stomacFullness"; - labelFor:{stomacFullness}; -} - -#stomacFullness { - property:{CatchLonglineDto.PROPERTY_STOMAC_FULLNESS}; - selectedItem:{tableEditBean.getStomacFullness()}; - _validatorLabel:{t("observe.content.catchLongline.stomacFullness")}; -} - -#maturityStatusLabel { - text:"observe.content.catchLongline.maturityStatus"; - labelFor:{maturityStatus}; -} - -#maturityStatus { - property:{CatchLonglineDto.PROPERTY_MATURITY_STATUS}; - selectedItem:{tableEditBean.getMaturityStatus()}; - _validatorLabel:{t("observe.content.catchLongline.maturityStatus")}; -} - -#gonadeWeightLabel { - text:"observe.content.catchLongline.gonadeWeight"; - labelFor:{gonadeWeight}; -} - -#gonadeWeight { - property:{CatchLonglineDto.PROPERTY_GONADE_WEIGHT}; - model:{tableEditBean.getGonadeWeight()}; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL3_PATTERN}; - _validatorLabel:{t("observe.content.catchLongline.gonadeWeight")}; -} - -/* ***************************************************************************** */ -/* SIZE MEASURES TAB ********************************************************** */ -/* ***************************************************************************** */ - -#sizeMeasuresFormTab { - title:{t("observe.content.catchLongline.tab.sizeMeasures")}; - icon:{handler.getErrorIconIfFalse(sizeMeasuresTableModel.isValid())}; -} - -#sizeMeasuresTable { - model: {sizeMeasuresTableModel}; -} - -#addSizeMeasure { - text: "observe.content.catchLongline.action.addSizeMeasure"; - toolTipText: "observe.content.catchLongline.action.addSizeMeasure.tip"; - actionIcon: add; -} - -#deleteSelectedSizeMeasure { - text: "observe.content.catchLongline.action.deleteSelectedSizeMeasure"; - toolTipText: "observe.content.catchLongline.action.deleteSelectedSizeMeasure.tip"; - actionIcon: delete; -} - -/* ***************************************************************************** */ -/* WEIGHT MEASURES TAB ******************************************************** */ -/* ***************************************************************************** */ - -#weightMeasuresFormTab { - title:{t("observe.content.catchLongline.tab.weightMeasures")}; - icon:{handler.getErrorIconIfFalse(weightMeasuresTableModel.isValid())}; -} - -#weightMeasuresTable { - model: {weightMeasuresTableModel}; -} - -#addWeightMeasure { - text: "observe.content.catchLongline.action.addWeightMeasure"; - toolTipText: "observe.content.catchLongline.action.addWeightMeasure.tip"; - actionIcon: add; -} - -#deleteSelectedWeightMeasure { - text: "observe.content.catchLongline.action.deleteSelectedWeightMeasure"; - toolTipText: "observe.content.catchLongline.action.deleteSelectedWeightMeasure.tip"; - actionIcon: delete; -} - -/* ***************************************************************************** */ -/* BRANCHLINE TAB ************************************************************* */ -/* ***************************************************************************** */ - -#branchlineFormTab { - title:{t("observe.content.catchLongline.tab.branchline")}; - icon:{handler.getErrorIconIfFalse(model.isBranchlineTabValid())}; - enabled:{tableEditBean.getBranchline() != null}; -} - -#branchlineForm { - border:{new TitledBorder( (String) null)}; - visible:{tableEditBean.getBranchline() != null}; -} - - -#depthRecorder { - horizontalTextPosition:{JCheckBox.LEFT}; - text:"observe.content.branchline.depthRecorder"; - _branchlineBeanPropertyName:{BranchlineDto.PROPERTY_DEPTH_RECORDER}; - selected:{BooleanUtils.isTrue(branchlineBean.getDepthRecorder())}; - _validatorLabel:{t("observe.content.branchline.depthRecorder")}; -} - -#hookLost { - horizontalTextPosition:{JCheckBox.LEFT}; - text:"observe.content.branchline.hookLost"; - _branchlineBeanPropertyName:{BranchlineDto.PROPERTY_HOOK_LOST}; - selected:{BooleanUtils.isTrue(branchlineBean.getHookLost())}; - _validatorLabel:{t("observe.content.branchline.hookLost")}; -} - -#traceCutOff { - horizontalTextPosition:{JCheckBox.LEFT}; - text:"observe.content.branchline.traceCutOff"; - _branchlineBeanPropertyName:{BranchlineDto.PROPERTY_TRACE_CUT_OFF}; - selected:{BooleanUtils.isTrue(branchlineBean.getTraceCutOff())}; - _validatorLabel:{t("observe.content.branchline.traceCutOff")}; -} - -#timer { - text:"observe.content.branchline.timer"; - horizontalTextPosition:{JCheckBox.LEFT}; - _branchlineBeanPropertyName:{BranchlineDto.PROPERTY_TIMER}; - selected:{BooleanUtils.isTrue(branchlineBean.getTimer())}; - _validatorLabel:{t("observe.content.branchline.timer")}; -} - -#timeSinceContactLabel { - text:"observe.content.branchline.timeSinceContact"; - labelFor:{timeSinceContact}; -} - -#timeSinceContact { - property:{BranchlineDto.PROPERTY_TIME_SINCE_CONTACT}; - bean:{branchlineBean}; - enabled:{BooleanUtils.isTrue(branchlineBean.getTimer())}; - model:{branchlineBean.getTimeSinceContact()}; - numberPattern:{fr.ird.observe.ui.UIHelper.LONG_10_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.branchline.timeSinceContact")}; -} - -#timerTimeOnBoardLabel { - text:"observe.content.branchline.timerTimeOnBoard"; - labelFor:{timerTimeOnBoard}; -} - -#timerTimeOnBoard { - date:{branchlineBean.getTimerTimeOnBoard()}; - propertyDate: {BranchlineDto.PROPERTY_TIMER_TIME_ON_BOARD}; - bean:{branchlineBean}; - enabled:{BooleanUtils.isTrue(branchlineBean.getTimer())}; - label:{t("observe.content.branchline.timerTimeOnBoard")}; - _validatorLabel:{t("observe.content.branchline.timerTimeOnBoard")}; -} - -#baitHaulingStatusLabel { - text:"observe.content.branchline.baitHaulingStatus"; - labelFor:{baitHaulingStatus}; -} - -#baitHaulingStatus { - property:{BranchlineDto.PROPERTY_BAIT_HAULING_STATUS}; - bean:{branchlineBean}; - selectedItem:{branchlineBean.getBaitHaulingStatus()}; - _validatorLabel:{t("observe.content.branchline.baitHaulingStatus")}; -} - -#branchlineActions { - visible:{tableModel.isEditable()}; -} - -#resetBranchline { - text:"observe.content.catchLongline.resetBranchline"; - toolTipText:"observe.content.catchLongline.resetBranchline.tip"; - actionIcon:"revert"; - enabled:{branchlineValidator.isChanged()}; -} - -#saveBranchline{ - text:"observe.content.catchLongline.saveBranchline"; - toolTipText:"observe.content.catchLongline.saveBranchline.tip"; - actionIcon:"save"; - enabled:{branchlineValidator.isChanged() && branchlineValidator.isValid()}; -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchLonglineUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchLonglineUIHandler.java deleted file mode 100644 index c02adb3..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchLonglineUIHandler.java +++ /dev/null @@ -1,938 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.longline.BasketDto; -import fr.ird.observe.services.dto.longline.BranchlineDto; -import fr.ird.observe.services.dto.longline.BranchlineDtos; -import fr.ird.observe.services.dto.longline.CatchLonglineDto; -import fr.ird.observe.services.dto.longline.SectionDto; -import fr.ird.observe.services.dto.longline.SetLonglineCatchDto; -import fr.ird.observe.services.dto.longline.SetLonglineCatchDtos; -import fr.ird.observe.services.dto.longline.SizeMeasureDto; -import fr.ird.observe.services.dto.longline.WeightMeasureDto; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.ReferentialReferences; -import fr.ird.observe.services.dto.referential.SpeciesDto; -import fr.ird.observe.services.dto.referential.longline.CatchFateLonglineDto; -import fr.ird.observe.services.dto.referential.longline.HealthnessDto; -import fr.ird.observe.services.dto.referential.longline.SizeMeasureTypeDto; -import fr.ird.observe.services.dto.referential.longline.WeightMeasureTypeDto; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.service.longline.BranchlineService; -import fr.ird.observe.services.service.longline.SetLonglineCatchService; -import fr.ird.observe.services.service.longline.TripLonglineService; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.ContentUIInitializer; -import fr.ird.observe.ui.content.ContentUIModel; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIHandler; -import jaxx.runtime.context.JAXXContextEntryDef; -import jaxx.runtime.validator.swing.SwingValidator; -import jaxx.runtime.validator.swing.SwingValidatorMessage; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; -import org.apache.commons.lang3.BooleanUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.JTable; -import javax.swing.event.TableModelListener; -import javax.swing.table.DefaultTableCellRenderer; -import java.beans.PropertyChangeListener; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 9/11/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class CatchLonglineUIHandler extends ContentTableUIHandler<SetLonglineCatchDto, CatchLonglineDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(CatchLonglineUIHandler.class); - - // Compute valid state of tab from the error table - protected final TableModelListener computeTabValidStateListener; - - private final PropertyChangeListener catchFateChanged; - - private final PropertyChangeListener branchlineChanged; - - private final PropertyChangeListener depredatedChanged; - - private final PropertyChangeListener sizeTableModelModified; - - private final PropertyChangeListener weightTableModelModified; - - private final JAXXContextEntryDef<LonglinePositionHelper<CatchLonglineDto>> POSITION_HELPER_ENTRY = - UIHelper.newContextEntryDef("CatchLonglineUI-positionHelper", LonglinePositionHelper.class); - - public CatchLonglineUIHandler(CatchLonglineUI ui) { - super(ui, DataContextType.SetLongline); - computeTabValidStateListener = e -> { - - SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); - computeTabValidState(source); - - }; - catchFateChanged = evt -> onCatchFateChanged((ReferentialReference<CatchFateLonglineDto>) evt.getNewValue(), (CatchLonglineDto) evt.getSource()); - branchlineChanged = evt -> onBranchlineChanged((DataReference<BranchlineDto>) evt.getNewValue()); - weightTableModelModified = evt -> onWeightTableModelModified((Boolean) evt.getNewValue()); - sizeTableModelModified = evt -> onSizeTableModelModified((Boolean) evt.getNewValue()); - depredatedChanged = evt -> onDepretadedChanged((Boolean) evt.getNewValue(), (CatchLonglineDto) evt.getSource()); - } - - @Override - public CatchLonglineUI getUi() { - return (CatchLonglineUI) super.getUi(); - } - - @Override - public CatchLonglineUIModel getModel() { - return (CatchLonglineUIModel) super.getModel(); - } - - @Override - public void initUI() { - - final CatchLonglineContentTableUIInitializer uiInitializer = new CatchLonglineContentTableUIInitializer(getUi()); - uiInitializer.initUI(); - - getModel().addPropertyChangeListener(CatchLonglineUIModel.PROPERTY_SHOW_INDIVIDUAL_TABS, evt -> { - Boolean newValue = (Boolean) evt.getNewValue(); - showIndividualTabs(newValue); - }); - - getModel().addPropertyChangeListener(CatchLonglineUIModel.PROPERTY_EDITABLE, evt -> { - Boolean newValue = (Boolean) evt.getNewValue(); - setTableModelEditable(newValue); - }); - - getModel().addPropertyChangeListener(ContentUIModel.PROPERTY_FORM, evt -> updateUiWithReferenceSetsFromModel()); - - setTableModelEditable(getModel().isEditable()); - - LonglinePositionHelper<CatchLonglineDto> positionHelper = new LonglinePositionHelper<>( - getUi().getSection(), - getUi().getBasket(), - getUi().getBranchline(), - getTableEditBean()); - - POSITION_HELPER_ENTRY.setContextValue(getUi(), positionHelper); - - } - - @Override - public void openUI() { - - if (log.isInfoEnabled()) { - log.info("OpenUI: " + getModel()); - } - - super.openUI(); - - // Reset all sections - LonglinePositionHelper<CatchLonglineDto> positionHelper = POSITION_HELPER_ENTRY.getContextValue(getUi()); - getUi().getSection().setData(positionHelper.getSections()); - - // To be sure always remove listener (could prevent some leaks) - getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); - // listen messages to see if required to add - getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); - - SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); - computeTabValidState(errorTableModel); - - } - - public void resetBranchline() { - - onBranchlineChanged(null); - - onBranchlineChanged(getTableEditBean().getBranchline()); - - } - - public void saveBranchline() { - - if (log.isInfoEnabled()) { - log.info("Saved modified branchline"); - } - - CatchLonglineUI ui = getUi(); - - BranchlineDto branchline = ui.getBranchlineBean(); - - String openSetLonglineId = getDataContext().getSelectedSetLonglineId(); - SaveResultDto saveResult = getBranchLineService().save(openSetLonglineId, branchline); - saveResult.toDto(branchline); - - // on recopie le last update car c'est le laste update de SetLongline qui est renvoyé. - getBean().setLastUpdateDate(saveResult.getLastUpdateDate()); - - getUi().getBranchlineValidator().setChanged(false); - - } - - public void updateCatchAcquisitionMode(CatchAcquisitionModeEnum newMode) { - - if (log.isDebugEnabled()) { - log.debug("Change CatchAcquisitionMode " + newMode); - } - if (newMode == null) { - - // mode null (cela peut arriver avec les bindings) - return; - } - - CatchLonglineUI ui = getUi(); - - boolean createMode = ui.getTableModel().isCreate(); - - CatchLonglineDto editBean = ui.getTableEditBean(); - - switch (newMode) { - - case GROUPED: - - if (createMode) { - - editBean.setTotalWeight(null); - editBean.setCount(null); - editBean.setHookPosition(null); - - } - - break; - - case INDIVIDUAL: - - if (createMode) { - - // on positionne le count à 1 (seule valeur possible) - editBean.setCount(1); - - } - - break; - } - - boolean isGrouped = CatchAcquisitionModeEnum.GROUPED.equals(newMode); - - ui.getTotalWeight().setEnabled(isGrouped); - ui.getCount().setEnabled(isGrouped); - - boolean isIndividual = CatchAcquisitionModeEnum.INDIVIDUAL.equals(newMode); - - ui.getHookPosition().setEnabled(isIndividual); - ui.getSection().setEnabled(isIndividual); - ui.getBasket().setEnabled(isIndividual); - ui.getBranchline().setEnabled(isIndividual); - - if (createMode) { - - // on propage le mode de saisie dans le bean - editBean.setAcquisitionMode(newMode.ordinal()); - - } - - boolean showIndividualTabs = !createMode && isIndividual; - - ui.getModel().setShowIndividualTabs(showIndividualTabs); - - } - - @Override - protected void onSelectedRowChanged(int editingRow, CatchLonglineDto bean, boolean create) { - - if (log.isInfoEnabled()) { - log.info("Selected row changed: " + editingRow + ", create? " + create); - } - - CatchLonglineUI ui = getUi(); - - UIHelper.stopEditing(ui.getSizeMeasuresTable()); - UIHelper.stopEditing(ui.getWeightMeasuresTable()); - - CatchLonglineTableModel tableModel = getTableModel(); - CatchLonglineUIModel model = getModel(); - - boolean emptySelection = editingRow == -1; - - // load size measures - - SizeMeasuresTableModel sizeMeasuresTableModel = model.getSizeMeasuresTableModel(); - List<SizeMeasureDto> sizes = emptySelection ? Collections.emptyList() : sizeMeasuresTableModel.getCacheForRow(editingRow); - if (sizes == null) { - - if (log.isInfoEnabled()) { - log.info("init size measures for row " + editingRow); - } - - // first time coming on this row - - if (tableModel.isCreate()) { - - // create mode: just init with empty list - sizes = Collections.emptyList(); - - if (log.isInfoEnabled()) { - log.info("create mode, use an empty list"); - } - - } else { - - // updating mode: loading from db - sizes = Lists.newArrayList(bean.getSizeMeasure()); - if (log.isInfoEnabled()) { - log.info("Loaded sizes (" + bean.getId() + "): " + sizes.size()); - } - } - - // init size measures - sizeMeasuresTableModel.initCacheForRow(editingRow, sizes); - - } else { - - if (log.isInfoEnabled()) { - log.info("Using existing sizes for row " + editingRow + " : " + sizes.size()); - } - } - - sizeMeasuresTableModel.setData(sizes); - - // load weight measures - - WeightMeasuresTableModel weightMeasuresTableModel = model.getWeightMeasuresTableModel(); - List<WeightMeasureDto> weights = emptySelection ? Collections.emptyList() : weightMeasuresTableModel.getCacheForRow(editingRow); - - if (weights == null) { - - if (tableModel.isCreate()) { - - // create mode: just init with empty list - weights = Collections.emptyList(); - - } else { - - // updating mode: loading from db - weights = Lists.newArrayList(bean.getWeightMeasure()); - if (log.isInfoEnabled()) { - log.info("Loaded weights (" + bean.getId() + "): " + weights.size()); - } - - } - - // init weights measures - weightMeasuresTableModel.initCacheForRow(editingRow, weights); - - } else { - - if (log.isInfoEnabled()) { - log.info("Using existing weights for row " + editingRow + ": " + weights.size()); - } - } - - weightMeasuresTableModel.setData(weights); - - sizeMeasuresTableModel.setModified(false); - weightMeasuresTableModel.setModified(false); - - if (!tableModel.isEditable()) { - return; - } - - JComponent requestFocus; - - if (tableModel.isCreate()) { - - // go back to first pane - ui.getFishingOperationTabPane().setSelectedIndex(0); - - // select by default individual acquisition mode - ui.getAcquisitionModeGroup().setSelectedValue(null); - ui.getAcquisitionModeGroup().setSelectedValue(CatchAcquisitionModeEnum.INDIVIDUAL); - - ui.getPredator().setEnabled(false); - ui.getHookWhenDiscarded().setEnabled(false); - - ui.getDiscardHealthness().setEnabled(false); - ui.getBeatDiameter().setEnabled(false); - - requestFocus = ui.getSpeciesCatch(); - - } else { - - int acquisitionMode = bean.getAcquisitionMode(); - CatchAcquisitionModeEnum enumValue = CatchAcquisitionModeEnum.valueOf(acquisitionMode); - ui.getAcquisitionModeGroup().setSelectedValue(null); - ui.getAcquisitionModeGroup().setSelectedValue(enumValue); - - if (enumValue.equals(CatchAcquisitionModeEnum.GROUPED)) { - - requestFocus = ui.getCount(); - - } else { - - requestFocus = ui.getCatchHealthness(); - - } - - //FIXME Voir si pas besoin aussi de relancer les binding (catchFateChanged, branchlineChanged) ? - onDepretadedChanged(bean.getDepredated(), bean); - - } - - bean.removePropertyChangeListener(CatchLonglineDto.PROPERTY_CATCH_FATE_LONGLINE, catchFateChanged); - bean.addPropertyChangeListener(CatchLonglineDto.PROPERTY_CATCH_FATE_LONGLINE, catchFateChanged); - - bean.removePropertyChangeListener(CatchLonglineDto.PROPERTY_BRANCHLINE, branchlineChanged); - bean.addPropertyChangeListener(CatchLonglineDto.PROPERTY_BRANCHLINE, branchlineChanged); - - bean.removePropertyChangeListener(CatchLonglineDto.PROPERTY_DEPREDATED, depredatedChanged); - bean.addPropertyChangeListener(CatchLonglineDto.PROPERTY_DEPREDATED, depredatedChanged); - - LonglinePositionHelper<CatchLonglineDto> positionHelper = POSITION_HELPER_ENTRY.getContextValue(ui); - positionHelper.resetPosition(bean); - - requestFocus.requestFocus(); - - } - - @Override - protected void initTableUI(DefaultTableCellRenderer renderer) { - - CatchLonglineUI ui = getUi(); - { - // init main table - - JTable table = ui.getTable(); - - UIHelper.setI18nTableHeaderRenderer( - table, - n("observe.content.catchLongline.table.sectionHaulingId"), - n("observe.content.catchLongline.table.sectionHaulingId.tip"), - n("observe.content.catchLongline.table.basketHaulingId"), - n("observe.content.catchLongline.table.basketHaulingId.tip"), - n("observe.content.catchLongline.table.branchlineHaulingId"), - n("observe.content.catchLongline.table.branchlineHaulingId.tip"), - - n("observe.content.catchLongline.table.speciesCatch"), - n("observe.content.catchLongline.table.speciesCatch.tip"), - n("observe.content.catchLongline.table.acquisitionMode"), - n("observe.content.catchLongline.table.acquisitionMode.tip"), - n("observe.content.catchLongline.table.count"), - n("observe.content.catchLongline.table.count.tip"), - n("observe.content.catchLongline.table.catchHealthness"), - n("observe.content.catchLongline.table.catchHealthness.tip"), - n("observe.content.catchLongline.table.catchFateLongline"), - n("observe.content.catchLongline.table.catchFateLongline.tip"), - n("observe.content.catchLongline.table.discardHealthness"), - n("observe.content.catchLongline.table.discardHealthness.tip"), - n("observe.content.catchLongline.table.depredated"), - n("observe.content.catchLongline.table.depredated.tip"), - n("observe.content.catchLongline.table.comment"), - n("observe.content.catchLongline.table.comment.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newDataReferenceDecorateTableCellRenderer(renderer, SectionDto.class, DecoratorService.HAULING_IDENTIFIER)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newDataReferenceDecorateTableCellRenderer(renderer, BasketDto.class, DecoratorService.HAULING_IDENTIFIER)); - UIHelper.setTableColumnRenderer(table, 2, UIHelper.newDataReferenceDecorateTableCellRenderer(renderer, BranchlineDto.class, DecoratorService.HAULING_IDENTIFIER)); - - UIHelper.setTableColumnRenderer(table, 3, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesDto.class)); - UIHelper.setTableColumnRenderer(table, 4, UIHelper.newEnumTableCellRenderer(renderer, CatchAcquisitionModeEnum.class)); - UIHelper.setTableColumnRenderer(table, 5, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 6, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, HealthnessDto.class)); - UIHelper.setTableColumnRenderer(table, 7, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, CatchFateLonglineDto.class)); - UIHelper.setTableColumnRenderer(table, 8, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, HealthnessDto.class)); - UIHelper.setTableColumnRenderer(table, 9, UIHelper.newBooleanTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 10, UIHelper.newStringTableCellRenderer(renderer, 10, true)); - - } - - { - // init size measures table - JTable table = ui.getSizeMeasuresTable(); - - UIHelper.setI18nTableHeaderRenderer(table, - n("observe.content.catchLongline.table.sizeMeasureType"), - n("observe.content.catchLongline.table.sizeMeasureType.tip"), - n("observe.content.catchLongline.table.size"), - n("observe.content.catchLongline.table.size.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SizeMeasureTypeDto.class)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - - ReferentialReferenceDecorator<SizeMeasureTypeDto> decorator = getReferentialReferenceDecorator(SizeMeasureTypeDto.class); - - List<ReferentialReference<SizeMeasureTypeDto>> sizeMeasureTypes = - Lists.newArrayList(getDataSource().getReferentialReferences(SizeMeasureTypeDto.class)); - - UIHelper.setTableColumnEditor(table, 0, ContentUIInitializer.newDataColumnEditor(sizeMeasureTypes, decorator)); - UIHelper.setTableColumnEditor(table, 1, ContentUIInitializer.newFloatColumnEditor(table)); - - initInlineTable(ui.getSizeMeasuresScrollPane(), - table, - getModel().getSizeMeasuresTableModel(), - sizeTableModelModified, - ui.getSizeMeasuresTablePopup(), - ui.getAddSizeMeasure(), - ui.getDeleteSelectedSizeMeasure()); - - } - - { - // init weight measures table - JTable table = ui.getWeightMeasuresTable(); - - UIHelper.setI18nTableHeaderRenderer(table, - n("observe.content.catchLongline.table.weightMeasureType"), - n("observe.content.catchLongline.table.weightMeasureType.tip"), - n("observe.content.catchLongline.table.weight"), - n("observe.content.catchLongline.table.weight.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, WeightMeasureTypeDto.class)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - - ReferentialReferenceDecorator<WeightMeasureTypeDto> decorator = getReferentialReferenceDecorator(WeightMeasureTypeDto.class); - - List<ReferentialReference<WeightMeasureTypeDto>> weightMeasureTypes = - Lists.newArrayList(getDataSource().getReferentialReferences(WeightMeasureTypeDto.class)); - - UIHelper.setTableColumnEditor(table, 0, ContentUIInitializer.newDataColumnEditor(weightMeasureTypes, decorator)); - UIHelper.setTableColumnEditor(table, 1, ContentUIInitializer.newFloatColumnEditor(table)); - - initInlineTable(ui.getWeightMeasuresScrollPane(), - table, - getModel().getWeightMeasuresTableModel(), - weightTableModelModified, - ui.getWeightMeasuresTablePopup(), - ui.getAddWeightMeasure(), - ui.getDeleteSelectedWeightMeasure()); - - } - - getTableModel().addPropertyChangeListener(ContentTableModel.CREATE_PROPERTY, evt -> { - Boolean oldValue = (Boolean) evt.getOldValue(); - Boolean newValue = (Boolean) evt.getNewValue(); - setTableModelCreate(oldValue, newValue); - }); - } - - @Override - protected String getEditBeanIdToLoad() { - return getDataContext().getSelectedSetLonglineId(); - } - - @Override - protected void doPersist(SetLonglineCatchDto bean) { - SaveResultDto saveResult = getSetLonglineCatchService().save(bean); - bean.setLastUpdateDate(saveResult.getLastUpdateDate()); - } - - @Override - protected void loadEditBean(String beanId) { - - Form<SetLonglineCatchDto> form = getSetLonglineCatchService().loadForm(beanId); - - CatchLonglineUIModel model = getModel(); - - loadReferentialReferenceSetsInModel(form); - - model.setForm(form); - - LonglinePositionHelper<CatchLonglineDto> positionHelper = POSITION_HELPER_ENTRY.getContextValue(getUi()); - positionHelper.initSections( - form.getObject(), - form.getObject().getCatchLongline()); - - SetLonglineCatchDtos.copySetLonglineCatchDto(form.getObject(), getBean()); - - } - - @Override - protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { - - Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); - - switch (propertyName) { - - case CatchLonglineDto.PROPERTY_SPECIES_CATCH: - case CatchLonglineDto.PROPERTY_PREDATOR: { - String speciesListId; - - if (CatchLonglineDto.PROPERTY_SPECIES_CATCH.equals(propertyName)) { - speciesListId = ObserveSwingApplicationContext.get().getConfig().getSpeciesListLonglineCatchId(); - } else { - speciesListId = ObserveSwingApplicationContext.get().getConfig().getSpeciesListLonglineDepredatorId(); - } - - String tripLonglineId = getDataContext().getSelectedTripLonglineId(); - - TripLonglineService tripLonglineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripLonglineService(); - result = (List) tripLonglineService.getSpeciesByListAndTrip(tripLonglineId, speciesListId); - - result = ReferentialReferences.filterEnabled(result); - - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - - break; - } - - } - - return result; - - } - - @Override - protected void closeSafeUI() { - - if (log.isInfoEnabled()) { - log.info("CloseUI: " + getModel()); - } - super.closeSafeUI(); - - // remove listener - getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); - - } - - @Override - protected void resetEditBean() { - - UIHelper.stopEditing(getUi().getSizeMeasuresTable()); - UIHelper.stopEditing(getUi().getWeightMeasuresTable()); - - onBranchlineChanged(null); - - super.resetEditBean(); - - onBranchlineChanged(getTableEditBean().getBranchline()); - - } - - protected void setTableModelEditable(Boolean newValue) { - - getModel().getSizeMeasuresTableModel().setEditable(newValue); - getModel().getWeightMeasuresTableModel().setEditable(newValue); - - } - - protected void setTableModelCreate(Boolean oldValue, Boolean newValue) { - - if (BooleanUtils.isTrue(oldValue) && BooleanUtils.isFalse(newValue)) { - - // just save a row - // reload acquisition mode (will rebind some stuff) - - CatchAcquisitionModeEnum acquisitionModeEnum = (CatchAcquisitionModeEnum) getUi().getAcquisitionModeGroup().getSelectedValue(); - - getUi().getAcquisitionModeGroup().setSelectedValue(null); - getUi().getAcquisitionModeGroup().setSelectedValue(acquisitionModeEnum); - - } - - } - - protected void showIndividualTabs(boolean newValue) { - - if (log.isInfoEnabled()) { - log.info("will show individuals tabs ?" + newValue); - } - - getUi().getFoodAndSexualFormTab().setEnabled(newValue); - getUi().getSizeMeasuresFormTab().setEnabled(newValue); - getUi().getWeightMeasuresFormTab().setEnabled(newValue); - - if (!newValue && getUi().getFishingOperationTabPane().getSelectedIndex() > 2) { - - // go back to first tab - getUi().getFishingOperationTabPane().setSelectedIndex(0); - - } - - } - - protected void onCatchFateChanged(ReferentialReference<CatchFateLonglineDto> newValue, CatchLonglineDto tableEditBean) { - - CatchLonglineUI ui = getUi(); - - if (newValue == null || !"fr.ird.observe.entities.referentiel.longline.CatchFateLongline#1239832686125#0.3".equals(newValue.getId())) { - - // not discarded - ui.getDiscardHealthness().setEnabled(false); - ui.getHookWhenDiscarded().setEnabled(false); - - getTableEditBean().setHookWhenDiscarded(null); - getTableEditBean().setDiscardHealthness(null); - - } else { - - // discarded - ui.getDiscardHealthness().setEnabled(true); - ui.getHookWhenDiscarded().setEnabled(true); - - } - - } - - protected void onBranchlineChanged(DataReference<BranchlineDto> newValue) { - - CatchLonglineUI ui = getUi(); - - BranchlineDto branchline = ui.getBranchlineBean(); - - SwingValidator<BranchlineDto> branchlineValidator = ui.getBranchlineValidator(); - if (newValue == null) { - - if (log.isInfoEnabled()) { - log.info("Remove branchline"); - } - - branchlineValidator.setBean(null); - - } else { - - if (log.isInfoEnabled()) { - log.info("Use branchline: " + newValue); - } - - String setLonglineId = getDataContext().getSelectedSetLonglineId(); - - Form<BranchlineDto> form = getBranchLineService().loadForm(setLonglineId, newValue.getId()); - BranchlineDtos.copyBranchlineDto(form.getObject(), branchline); - - if (ui.getValidator().getBean() == null) { - ui.getValidator().setBean(getBean()); - } - - branchlineValidator.setBean(branchline); - - } - - branchlineValidator.setChanged(false); - - } - - protected void onDepretadedChanged(Boolean newValue, CatchLonglineDto tableEditBean) { - - CatchLonglineUI ui = getUi(); - - if (BooleanUtils.isTrue(newValue)) { - - // depredated - ui.getBeatDiameter().setEnabled(true); - ui.getPredator().setEnabled(true); - - } else { - - // not depredated - ui.getBeatDiameter().setEnabled(false); - ui.getPredator().setEnabled(false); - tableEditBean.setBeatDiameter(null); - tableEditBean.setPredator(null); - - } - - } - - public void addSizeMeasure() { - - SizeMeasuresTableModel tableModel = getUi().getSizeMeasuresTableModel(); - - tableModel.addNewRow(); - - } - - public void deleteSelectedSizeMeasure() { - - SizeMeasuresTableModel tableModel = getUi().getSizeMeasuresTableModel(); - - boolean selectionEmpty = tableModel.isSelectionEmpty(); - - if (!selectionEmpty) { - - SizeMeasureDto data = tableModel.getSelectedRow(); - - if (log.isInfoEnabled()) { - log.info("Delete: " + data); - } - - ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); - int response = UIHelper.askUser(mainUI, - t("observe.title.delete"), - t("observe.content.sizeMeasure.delete.message"), - JOptionPane.WARNING_MESSAGE, - new Object[]{t("observe.choice.confirm.delete"), - t("observe.choice.cancel")}, - 1); - - if (response != 0) { - - // user cancel - return; - } - - tableModel.removeSelectedRow(); - - } - - } - - - protected void onSizeTableModelModified(Boolean newValue) { - - if (newValue) { - - // modify the validator, since this is the best way to prevent table edit form actions - // that something was modified on the form - getUi().getValidatorTable().setChanged(true); - - } - - // recompute table model valid state - getModel().getSizeMeasuresTableModel().validate(); - - } - - public void addWeightMeasure() { - - WeightMeasuresTableModel tableModel = getUi().getWeightMeasuresTableModel(); - - tableModel.addNewRow(); - - } - - public void deleteSelectedWeightMeasure() { - - WeightMeasuresTableModel tableModel = getUi().getWeightMeasuresTableModel(); - - boolean selectionEmpty = tableModel.isSelectionEmpty(); - - if (!selectionEmpty) { - - WeightMeasureDto data = tableModel.getSelectedRow(); - - if (log.isInfoEnabled()) { - log.info("Delete: " + data); - } - - ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); - int response = UIHelper.askUser(mainUI, - t("observe.title.delete"), - t("observe.content.weightMeasure.delete.message"), - JOptionPane.WARNING_MESSAGE, - new Object[]{t("observe.choice.confirm.delete"), - t("observe.choice.cancel")}, - 1); - - if (response != 0) { - - // user cancel - return; - } - - tableModel.removeSelectedRow(); - - } - - } - - protected void onWeightTableModelModified(Boolean newValue) { - - if (newValue) { - - // modify the validator, since this is the best way to prevent table edit form actions - // that something was modified on the form - getUi().getValidatorTable().setChanged(true); - - } - - // recompute table model valid state - getModel().getWeightMeasuresTableModel().validate(); - - } - - protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { - - Set<String> errorProperties = new HashSet<>(); - int rowCount = errorTableModel.getRowCount(); - for (int i = 0; i < rowCount; i++) { - - SwingValidatorMessage row = errorTableModel.getRow(i); - if (NuitonValidatorScope.ERROR.equals(row.getScope())) { - errorProperties.add(row.getField()); - } - } - - boolean caracteristicsTabValid = !errorProperties.removeAll(CatchLonglineUIModel.CARACTERISTIC_TAB_PROPERTIES); - boolean depredatedTabValid = !errorProperties.removeAll(CatchLonglineUIModel.DEPREDATED_TAB_PROPERTIES); - boolean foodAndSexualTabValid = !errorProperties.removeAll(CatchLonglineUIModel.FOOD_AND_SEXUAL_TAB_PROPERTIES); - boolean branchlineTabValid = !errorProperties.removeAll(CatchLonglineUIModel.BRANCHLINE_TAB_PROPERTIES); - - CatchLonglineUIModel model = getModel(); - - model.setCaracteristicsTabValid(caracteristicsTabValid); - model.setDepredatedTabValid(depredatedTabValid); - model.setFoodAndSexualTabValid(foodAndSexualTabValid); - model.setBranchlineTabValid(branchlineTabValid); - - } - - @Override - protected CatchLonglineTableModel getTableModel() { - return (CatchLonglineTableModel) super.getTableModel(); - } - - protected SetLonglineCatchService getSetLonglineCatchService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newSetLonglineCatchService(); - } - - protected BranchlineService getBranchLineService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newBranchlineService(); - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchLonglineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchLonglineUIModel.java deleted file mode 100644 index da5f6b3..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/CatchLonglineUIModel.java +++ /dev/null @@ -1,233 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; -import fr.ird.observe.ObserveSwingBinderService; -import fr.ird.observe.services.dto.longline.BranchlineDto; -import fr.ird.observe.services.dto.longline.CatchLonglineDto; -import fr.ird.observe.services.dto.longline.SetLonglineCatchDto; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; -import org.nuiton.util.beans.Binder; -import org.nuiton.util.beans.BinderModelBuilder; - -import java.util.List; -import java.util.Set; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class CatchLonglineUIModel extends ContentTableUIModel<SetLonglineCatchDto, CatchLonglineDto> { - - public static final String PROPERTY_CARACTERISTICS_TAB_VALID = "caracteristicsTabValid"; - - public static final String PROPERTY_DEPREDATED_TAB_VALID = "depredatedTabValid"; - - public static final String PROPERTY_FOOD_AND_SEXUAL_TAB_VALID = "foodAndSexualTabValid"; - - public static final String PROPERTY_BRANCHLINE_TAB_VALID = "branchlineTabValid"; - - public static final String PROPERTY_SHOW_INDIVIDUAL_TABS = "showIndividualTabs"; - - public static final Set<String> CARACTERISTIC_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(CatchLonglineDto.PROPERTY_SECTION, - CatchLonglineDto.PROPERTY_BASKET, - CatchLonglineDto.PROPERTY_BRANCHLINE, - CatchLonglineDto.PROPERTY_SPECIES_CATCH, - CatchLonglineDto.PROPERTY_PHOTO_REFERENCES, - CatchLonglineDto.PROPERTY_COUNT, - CatchLonglineDto.PROPERTY_TOTAL_WEIGHT, - CatchLonglineDto.PROPERTY_CATCH_HEALTHNESS, - CatchLonglineDto.PROPERTY_HOOK_POSITION, - CatchLonglineDto.PROPERTY_CATCH_FATE_LONGLINE, - CatchLonglineDto.PROPERTY_DISCARD_HEALTHNESS, - CatchLonglineDto.PROPERTY_HOOK_WHEN_DISCARDED).build(); - - public static final Set<String> DEPREDATED_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(CatchLonglineDto.PROPERTY_DEPREDATED, - CatchLonglineDto.PROPERTY_BEAT_DIAMETER, - CatchLonglineDto.PROPERTY_PREDATOR).build(); - - public static final Set<String> FOOD_AND_SEXUAL_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(CatchLonglineDto.PROPERTY_STOMAC_FULLNESS, - CatchLonglineDto.PROPERTY_SEX, - CatchLonglineDto.PROPERTY_MATURITY_STATUS, - CatchLonglineDto.PROPERTY_GONADE_WEIGHT).build(); - - public static final Set<String> BRANCHLINE_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(BranchlineDto.PROPERTY_DEPTH_RECORDER, - BranchlineDto.PROPERTY_HOOK_LOST, - BranchlineDto.PROPERTY_TRACE_CUT_OFF, - BranchlineDto.PROPERTY_TIMER, - BranchlineDto.PROPERTY_TIME_SINCE_CONTACT, - BranchlineDto.PROPERTY_TIMER_TIME_ON_BOARD, - BranchlineDto.PROPERTY_BAIT_HAULING_STATUS).build(); - - - private static final long serialVersionUID = 1L; - - protected final SizeMeasuresTableModel sizeMeasuresTableModel; - - protected final WeightMeasuresTableModel weightMeasuresTableModel; - - /** - * flag to see the individual tabs (only on individual mode + not in create mode). - */ - protected boolean showIndividualTabs; - - protected boolean caracteristicsTabValid; - - protected boolean depredatedTabValid; - - protected boolean foodAndSexualTabValid; - - protected boolean branchlineTabValid; - - public CatchLonglineUIModel(CatchLonglineUI ui) { - super(SetLonglineCatchDto.class, - CatchLonglineDto.class, - new String[]{ - SetLonglineCatchDto.PROPERTY_CATCH_LONGLINE - }, - new String[]{CatchLonglineDto.PROPERTY_SPECIES_CATCH, - CatchLonglineDto.PROPERTY_ACQUISITION_MODE, - CatchLonglineDto.PROPERTY_COUNT, - CatchLonglineDto.PROPERTY_CATCH_HEALTHNESS, - CatchLonglineDto.PROPERTY_CATCH_FATE_LONGLINE, - CatchLonglineDto.PROPERTY_DISCARD_HEALTHNESS, - CatchLonglineDto.PROPERTY_DEPREDATED, - CatchLonglineDto.PROPERTY_NUMBER, - CatchLonglineDto.PROPERTY_HOME_ID, - CatchLonglineDto.PROPERTY_HOOK_POSITION, - CatchLonglineDto.PROPERTY_HOOK_WHEN_DISCARDED, - CatchLonglineDto.PROPERTY_MATURITY_STATUS, - CatchLonglineDto.PROPERTY_PHOTO_REFERENCES, - CatchLonglineDto.PROPERTY_SEX, - CatchLonglineDto.PROPERTY_PREDATOR, - CatchLonglineDto.PROPERTY_STOMAC_FULLNESS, - CatchLonglineDto.PROPERTY_TOTAL_WEIGHT, - CatchLonglineDto.PROPERTY_BEAT_DIAMETER, - CatchLonglineDto.PROPERTY_GONADE_WEIGHT, - CatchLonglineDto.PROPERTY_SECTION, - CatchLonglineDto.PROPERTY_BASKET, - CatchLonglineDto.PROPERTY_BRANCHLINE, - CatchLonglineDto.PROPERTY_COMMENT - }); - - this.sizeMeasuresTableModel = new SizeMeasuresTableModel(); - this.weightMeasuresTableModel = new WeightMeasuresTableModel(); - - List<ContentTableMeta<CatchLonglineDto>> metas = Lists.newArrayList( - ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_SECTION, false), - ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_BASKET, false), - ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_BRANCHLINE, false), - ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_SPECIES_CATCH, false), - ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_ACQUISITION_MODE, false), - ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_COUNT, false), - ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_CATCH_HEALTHNESS, false), - ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_CATCH_FATE_LONGLINE, false), - ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_DISCARD_HEALTHNESS, false), - ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_DEPREDATED, false), - ContentTableModel.newTableMeta(CatchLonglineDto.class, CatchLonglineDto.PROPERTY_COMMENT, false)); - - initModel(ui, metas); - - } - - public SizeMeasuresTableModel getSizeMeasuresTableModel() { - return sizeMeasuresTableModel; - } - - public WeightMeasuresTableModel getWeightMeasuresTableModel() { - return weightMeasuresTableModel; - } - - public boolean isShowIndividualTabs() { - return showIndividualTabs; - } - - public void setShowIndividualTabs(boolean showIndividualTabs) { - this.showIndividualTabs = showIndividualTabs; - firePropertyChange(PROPERTY_SHOW_INDIVIDUAL_TABS, null, showIndividualTabs); - } - - public boolean isCaracteristicsTabValid() { - return caracteristicsTabValid; - } - - public void setCaracteristicsTabValid(boolean caracteristicsTabValid) { - this.caracteristicsTabValid = caracteristicsTabValid; - firePropertyChange(PROPERTY_CARACTERISTICS_TAB_VALID, null, caracteristicsTabValid); - } - - public boolean isDepredatedTabValid() { - return depredatedTabValid; - } - - public void setDepredatedTabValid(boolean depredatedTabValid) { - this.depredatedTabValid = depredatedTabValid; - firePropertyChange(PROPERTY_DEPREDATED_TAB_VALID, null, depredatedTabValid); - } - - public boolean isFoodAndSexualTabValid() { - return foodAndSexualTabValid; - } - - public void setFoodAndSexualTabValid(boolean foodAndSexualTabValid) { - this.foodAndSexualTabValid = foodAndSexualTabValid; - firePropertyChange(PROPERTY_FOOD_AND_SEXUAL_TAB_VALID, null, foodAndSexualTabValid); - } - - public boolean isBranchlineTabValid() { - return branchlineTabValid; - } - - public void setBranchlineTabValid(boolean branchlineTabValid) { - this.branchlineTabValid = branchlineTabValid; - firePropertyChange(PROPERTY_BRANCHLINE_TAB_VALID, null, branchlineTabValid); - } - - @Override - protected ContentTableModel<SetLonglineCatchDto, CatchLonglineDto> createTableModel(ObserveContentTableUI<SetLonglineCatchDto, CatchLonglineDto> ui, List<ContentTableMeta<CatchLonglineDto>> contentTableMetas) { - return new CatchLonglineTableModel(ui, contentTableMetas); - } - - @Override - protected BinderModelBuilder<CatchLonglineDto, CatchLonglineDto> prepareChildLoador(ObserveSwingBinderService binderService, String binderName) { - - BinderModelBuilder<CatchLonglineDto, CatchLonglineDto> builder = super.prepareChildLoador(binderService, binderName); - - builder.addCollectionStrategy(Binder.CollectionStrategy.duplicate, CatchLonglineDto.PROPERTY_PREDATOR); - - return builder; - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/EncounterUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/EncounterUI.jaxx deleted file mode 100644 index 676bdf3..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/EncounterUI.jaxx +++ /dev/null @@ -1,129 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.table.ContentTableUI - superGenericType='ActivityLonglineEncounterDto, EncounterDto' - contentTitle='{n("observe.content.encounter.title")}' - saveNewEntryText='{n("observe.content.encounter.action.create")}' - saveNewEntryTip='{n("observe.content.encounter.action.create.tip")}'> - - <style source="../../CommonTable.jcss"/> - - <import> - fr.ird.observe.services.dto.CommentableDto - fr.ird.observe.services.dto.longline.ActivityLonglineEncounterDto - fr.ird.observe.services.dto.longline.EncounterDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.SpeciesDto - fr.ird.observe.services.dto.referential.longline.EncounterTypeDto - fr.ird.observe.ui.content.table.* - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - java.awt.Dimension - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <EncounterUIHandler id='handler'/> - - <!-- model --> - <EncounterUIModel id='model'/> - - <!-- edit bean --> - <ActivityLonglineEncounterDto id='bean'/> - - <!-- table edit bean --> - <EncounterDto id='tableEditBean'/> - - <!-- table model --> - <ContentTableModel id='tableModel'/> - - <!-- le validateur de l'écran --> - <BeanValidator id='validator' autoField='true' context='ui-update-encounter' - beanClass='fr.ird.observe.services.dto.longline.ActivityLonglineEncounterDto' - errorTableModel='{getErrorTableModel()}'/> - - <!-- le validateur d'une entrée de tableau --> - <BeanValidator id='validatorTable' autoField='true' context='ui-update' - beanClass='fr.ird.observe.services.dto.longline.EncounterDto' - errorTableModel='{getErrorTableModel()}'/> - - <Table id='editorPanel' fill='both' insets='1'> - - <!-- encounterType --> - <row> - <cell> - <JLabel id='encounterTypeLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='encounterType' constructorParams='this' genericType='ReferentialReference<EncounterTypeDto>' _entityClass='EncounterTypeDto.class'/> - </cell> - </row> - - <!-- species --> - <row> - <cell> - <JLabel id='speciesLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='species' constructorParams='this' genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class'/> - </cell> - </row> - - <!-- distance --> - <row> - <cell> - <JLabel id='distanceLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='distance' constructorParams='this'/> - </cell> - </row> - - <!-- count --> - <row> - <cell> - <JLabel id='countLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='count' constructorParams='this'/> - </cell> - </row> - - </Table> - - <Table id='extraZone' fill='both' weightx='1' insets='1'> - <row> - <cell weighty='1'> - <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2' - onKeyReleased='getBean().setComment(comment2.getText())'/> - </JScrollPane> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/EncounterUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/EncounterUI.jcss deleted file mode 100644 index dd822cc..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/EncounterUI.jcss +++ /dev/null @@ -1,67 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#encounterTypeLabel { - text:"observe.content.encounter.encounterType"; - labelFor:{encounterType}; -} - -#encounterType { - property:{EncounterDto.PROPERTY_ENCOUNTER_TYPE}; - selectedItem:{tableEditBean.getEncounterType()}; -} - -#speciesLabel { - text:"observe.content.encounter.species"; - labelFor:{species}; -} - -#species { - property:{EncounterDto.PROPERTY_SPECIES}; - selectedItem:{tableEditBean.getSpecies()}; -} - -#countLabel { - text:"observe.content.encounter.count"; - labelFor:{count}; -} - -#count { - property:{EncounterDto.PROPERTY_COUNT}; - model:{tableEditBean.getCount()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; -} - -#distanceLabel { - text:"observe.content.encounter.distance"; - labelFor:{distance}; -} - -#distance { - property:{EncounterDto.PROPERTY_DISTANCE}; - model:{tableEditBean.getDistance()}; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL3_PATTERN}; -} - -#comment { - columnHeaderView:{new JLabel(t("observe.common.comment.activity"))}; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/EncounterUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/EncounterUIHandler.java deleted file mode 100644 index 61e834f..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/EncounterUIHandler.java +++ /dev/null @@ -1,161 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.longline.ActivityLonglineEncounterDto; -import fr.ird.observe.services.dto.longline.ActivityLonglineEncounterDtos; -import fr.ird.observe.services.dto.longline.EncounterDto; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.ReferentialReferences; -import fr.ird.observe.services.dto.referential.SpeciesDto; -import fr.ird.observe.services.dto.referential.SpeciesListDto; -import fr.ird.observe.services.dto.referential.longline.EncounterTypeDto; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.service.ReferentialService; -import fr.ird.observe.services.service.longline.ActivityLongLineEncounterService; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.table.ContentTableUIHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; -import java.util.Collection; -import java.util.LinkedList; -import java.util.Set; - -import static org.nuiton.i18n.I18n.n; - -/** - * Created on 8/31/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class EncounterUIHandler extends ContentTableUIHandler<ActivityLonglineEncounterDto, EncounterDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(EncounterUIHandler.class); - - public EncounterUIHandler(EncounterUI ui) { - super(ui, DataContextType.ActivityLongline); - } - - @Override - public EncounterUI getUi() { - return (EncounterUI) super.getUi(); - } - - @Override - protected void onSelectedRowChanged(int editingRow, EncounterDto bean, boolean create) { - if (getTableModel().isEditable()) { - if (log.isDebugEnabled()) { - log.debug("Row has changed to " + editingRow); - } - getUi().getEncounterType().requestFocus(); - } - } - - @Override - protected void initTableUI(DefaultTableCellRenderer renderer) { - JTable table = getUi().getTable(); - - UIHelper.setI18nTableHeaderRenderer(table, - n("observe.content.encounter.table.encouterType"), - n("observe.content.encounter.table.encouterType.tip"), - n("observe.content.encounter.table.species"), - n("observe.content.encounter.table.species.tip"), - n("observe.content.encounter.table.distance"), - n("observe.content.encounter.table.distance.tip"), - n("observe.content.encounter.table.count"), - n("observe.content.encounter.table.count.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, EncounterTypeDto.class)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesDto.class)); - UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - } - - @Override - protected String getEditBeanIdToLoad() { - return getDataContext().getSelectedActivityId(); - } - - @Override - protected void doPersist(ActivityLonglineEncounterDto bean) { - - SaveResultDto saveResult = getActivityLongLineEncouterService().save(bean); - saveResult.toDto(bean); - - } - - @Override - protected void loadEditBean(String beanId) { - Form<ActivityLonglineEncounterDto> form = getActivityLongLineEncouterService().loadForm(beanId); - loadReferentialReferenceSetsInModel(form); - - getModel().setForm(form); - ActivityLonglineEncounterDtos.copyActivityLonglineEncounterDto(form.getObject(), getBean()); - } - - @Override - protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { - - Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); - - switch (propertyName) { - - case EncounterDto.PROPERTY_SPECIES: { - - String speciesListId = ObserveSwingApplicationContext.get().getConfig().getSpeciesListLonglineEncounterId(); - - ReferentialService referentialService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newReferentialService(); - - Form<SpeciesListDto> speciesListDtoForm = referentialService.loadForm(SpeciesListDto.class, speciesListId); - SpeciesListDto speciesListDto = speciesListDtoForm.getObject(); - - Set<String> speciesIds = speciesListDto.getSpeciesIds(); - - result = ReferentialReferences.filterContains(result, speciesIds); - - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - } - - break; - - } - - return result; - - } - - protected ActivityLongLineEncounterService getActivityLongLineEncouterService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivityLongLineEncounterService(); - } -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/EncounterUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/EncounterUIModel.java deleted file mode 100644 index 5fbdf08..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/EncounterUIModel.java +++ /dev/null @@ -1,92 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import fr.ird.observe.services.dto.longline.ActivityLonglineEncounterDto; -import fr.ird.observe.services.dto.longline.EncounterDto; -import fr.ird.observe.services.dto.longline.EncounterDtos; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; - -import java.util.Collection; -import java.util.List; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class EncounterUIModel extends ContentTableUIModel<ActivityLonglineEncounterDto, EncounterDto> { - - private static final long serialVersionUID = 1L; - - public EncounterUIModel(EncounterUI ui) { - super(ActivityLonglineEncounterDto.class, - EncounterDto.class, - new String[]{ - ActivityLonglineEncounterDto.PROPERTY_ENCOUNTER, - ActivityLonglineEncounterDto.PROPERTY_COMMENT}, - new String[]{ - EncounterDto.PROPERTY_SPECIES, - EncounterDto.PROPERTY_DISTANCE, - EncounterDto.PROPERTY_COUNT, - EncounterDto.PROPERTY_ENCOUNTER_TYPE}); - - List<ContentTableMeta<EncounterDto>> metas = Lists.newArrayList( - ContentTableModel.newTableMeta(EncounterDto.class, EncounterDto.PROPERTY_ENCOUNTER_TYPE, false), - ContentTableModel.newTableMeta(EncounterDto.class, EncounterDto.PROPERTY_SPECIES, false), - ContentTableModel.newTableMeta(EncounterDto.class, EncounterDto.PROPERTY_DISTANCE, false), - ContentTableModel.newTableMeta(EncounterDto.class, EncounterDto.PROPERTY_COUNT, false)); - - initModel(ui, metas); - - } - - @Override - protected ContentTableModel<ActivityLonglineEncounterDto, EncounterDto> createTableModel( - ObserveContentTableUI<ActivityLonglineEncounterDto, EncounterDto> ui, - List<ContentTableMeta<EncounterDto>> contentTableMetas) { - return new ContentTableModel<ActivityLonglineEncounterDto, EncounterDto>(ui, contentTableMetas) { - private static final long serialVersionUID = 1L; - - @Override - protected Collection<EncounterDto> getChilds(ActivityLonglineEncounterDto bean) { - return bean.getEncounter(); - } - - @Override - protected void load(EncounterDto source, EncounterDto target) { - EncounterDtos.copyEncounterDto(source, target); - } - - @Override - protected void setChilds(ActivityLonglineEncounterDto parent, List<EncounterDto> childs) { - parent.setEncounter(childs); - } - }; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/FloatlinesCompositionUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/FloatlinesCompositionUI.jaxx deleted file mode 100644 index 1403988..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/FloatlinesCompositionUI.jaxx +++ /dev/null @@ -1,121 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.table.ContentTableUI - superGenericType='SetLonglineGlobalCompositionDto, FloatlinesCompositionDto' - contentTitle='{n("observe.content.floatlinesComposition.title")}' - saveNewEntryText='{n("observe.content.floatlinesComposition.action.create")}' - saveNewEntryTip='{n("observe.content.floatlinesComposition.action.create.tip")}'> - - <style source="../../CommonTable.jcss"/> - - <import> - fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto - fr.ird.observe.services.dto.longline.FloatlinesCompositionDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.longline.LineTypeDto - fr.ird.observe.ui.content.table.* - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <FloatlinesCompositionUIHandler id='handler'/> - - <!-- model --> - <FloatlinesCompositionUIModel id='model'/> - - <!-- edit bean --> - <SetLonglineGlobalCompositionDto id='bean'/> - - <!-- table edit bean --> - <FloatlinesCompositionDto id='tableEditBean'/> - - <!-- table model --> - <ContentTableModel id='tableModel'/> - - <!-- le validateur de l'écran --> - <BeanValidator id='validator' context='ui-update-floatlinesComposition' - beanClass='fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto' - errorTableModel='{getErrorTableModel()}'> - <field name="floatlinesCompositionProportionSum" component="floatlinesCompositionProportionSum"/> - <field name="floatlinesComposition" component="editorPanel"/> - </BeanValidator> - - <!-- le validateur d'une entrée de tableau --> - <BeanValidator id='validatorTable' autoField='true' context='ui-update' - beanClass='fr.ird.observe.services.dto.longline.FloatlinesCompositionDto' - errorTableModel='{getErrorTableModel()}'/> - - <Table id='editorPanel' fill='both' insets='1'> - - <!-- lineType --> - <row> - <cell> - <JLabel id='lineTypeLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='lineType' constructorParams='this' genericType='ReferentialReference<LineTypeDto>' _entityClass='LineTypeDto.class'/> - </cell> - </row> - - <!-- length --> - <row> - <cell> - <JLabel id='lengthLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='length' constructorParams='this'/> - </cell> - </row> - - <!-- proportion --> - <row> - <cell> - <JLabel id='proportionLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='proportion' constructorParams='this'/> - </cell> - </row> - - </Table> - - <Table id='extraZone' fill='both'> - - <!-- proportion sum --> - <row> - <cell> - <JLabel id='floatlinesCompositionProportionSumLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <JLabel id='floatlinesCompositionProportionSum'/> - </cell> - </row> - - </Table> - -</fr.ird.observe.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/FloatlinesCompositionUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/FloatlinesCompositionUI.jcss deleted file mode 100644 index 5599801..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/FloatlinesCompositionUI.jcss +++ /dev/null @@ -1,67 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#lineTypeLabel { - text:"observe.content.floatlinesComposition.lineType"; - labelFor:{lineType}; -} - -#lineType { - property:{FloatlinesCompositionDto.PROPERTY_LINE_TYPE}; - selectedItem:{tableEditBean.getLineType()}; - _validatorLabel:{t("observe.content.floatlinesComposition.lineType")}; -} - -#lengthLabel { - text:"observe.content.floatlinesComposition.length"; - labelFor:{length}; -} - -#length { - property:{FloatlinesCompositionDto.PROPERTY_LENGTH}; - model:{tableEditBean.getLength()}; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL3_PATTERN}; - _validatorLabel:{t("observe.content.floatlinesComposition.length")}; -} - -#proportionLabel { - text:"observe.content.floatlinesComposition.proportion"; - labelFor:{proportion}; -} - -#proportion { - property:{FloatlinesCompositionDto.PROPERTY_PROPORTION}; - model:{tableEditBean.getProportion()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.floatlinesComposition.proportion")}; -} - -#floatlinesCompositionProportionSumLabel { - text:"observe.content.floatlinesComposition.proportionSum"; - labelFor:{floatlinesCompositionProportionSum}; -} - -#floatlinesCompositionProportionSum { - text:{getStringValue(bean.getFloatlinesCompositionProportionSum())}; - _validatorLabel:{t("observe.content.floatlinesComposition.proportionSum")}; - font-weight:bold; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/FloatlinesCompositionUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/FloatlinesCompositionUIHandler.java deleted file mode 100644 index fa2a573..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/FloatlinesCompositionUIHandler.java +++ /dev/null @@ -1,117 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.longline.FloatlinesCompositionDto; -import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto; -import fr.ird.observe.services.dto.referential.longline.LineTypeDto; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.table.ContentTableUIHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; - -import static org.nuiton.i18n.I18n.n; - -/** - * Created on 12/6/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.9 - */ -public class FloatlinesCompositionUIHandler extends ContentTableUIHandler<SetLonglineGlobalCompositionDto, FloatlinesCompositionDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(FloatlinesCompositionUIHandler.class); - - public FloatlinesCompositionUIHandler(FloatlinesCompositionUI ui) { - super(ui, DataContextType.SetLongline); - } - - @Override - public FloatlinesCompositionUI getUi() { - return (FloatlinesCompositionUI) super.getUi(); - } - - @Override - protected void onSelectedRowChanged(int editingRow, FloatlinesCompositionDto bean, boolean create) { - - if (getTableModel().isEditable()) { - if (log.isDebugEnabled()) { - log.debug("Row has changed to " + editingRow); - } - getUi().getLineType().requestFocus(); - } - - } - - @Override - protected void initTableUI(DefaultTableCellRenderer renderer) { - - JTable table = getUi().getTable(); - - UIHelper.setI18nTableHeaderRenderer( - table, - n("observe.content.floatlinesComposition.table.lineType"), - n("observe.content.floatlinesComposition.table.lineType.tip"), - n("observe.content.floatlinesComposition.table.length"), - n("observe.content.floatlinesComposition.table.length.tip"), - n("observe.content.floatlinesComposition.table.proportion"), - n("observe.content.floatlinesComposition.table.proportion.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, LineTypeDto.class)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - - // when model change in table, let's recompute the proportion sum - table.getModel().addTableModelListener(e -> { - - int proportionSum = getBean().getFloatlinesCompositionProportionSum(); - getBean().setFloatlinesCompositionProportionSum(proportionSum); - }); - - } - - @Override - protected String getEditBeanIdToLoad() { - return getDataContext().getSelectedSetId(); - } - - @Override - public void afterSave(boolean refresh) { - super.afterSave(refresh); - } - - @Override - protected void doPersist(SetLonglineGlobalCompositionDto bean) { - // fait par le doSave de LonglineGlobalCompositionUIHandler - } - - @Override - protected void loadEditBean(String beanId) { - // fait par le loadEditBean de LonglineGlobalCompositionUIHandler - } -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/FloatlinesCompositionUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/FloatlinesCompositionUIModel.java deleted file mode 100644 index ac88c62..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/FloatlinesCompositionUIModel.java +++ /dev/null @@ -1,90 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import fr.ird.observe.services.dto.longline.FloatlinesCompositionDto; -import fr.ird.observe.services.dto.longline.FloatlinesCompositionDtos; -import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; - -import java.util.Collection; -import java.util.List; - -/** - * Created on 12/6/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.9 - */ -public class FloatlinesCompositionUIModel extends ContentTableUIModel<SetLonglineGlobalCompositionDto, FloatlinesCompositionDto> { - - private static final long serialVersionUID = 1L; - - public FloatlinesCompositionUIModel(FloatlinesCompositionUI ui) { - super(SetLonglineGlobalCompositionDto.class, - FloatlinesCompositionDto.class, - new String[]{ - SetLonglineGlobalCompositionDto.PROPERTY_FLOATLINES_COMPOSITION - }, - new String[]{FloatlinesCompositionDto.PROPERTY_LINE_TYPE, - FloatlinesCompositionDto.PROPERTY_LENGTH, - FloatlinesCompositionDto.PROPERTY_PROPORTION}); - - List<ContentTableMeta<FloatlinesCompositionDto>> metas = Lists.newArrayList( - ContentTableModel.newTableMeta(FloatlinesCompositionDto.class, FloatlinesCompositionDto.PROPERTY_LINE_TYPE, false), - ContentTableModel.newTableMeta(FloatlinesCompositionDto.class, FloatlinesCompositionDto.PROPERTY_LENGTH, false), - ContentTableModel.newTableMeta(FloatlinesCompositionDto.class, FloatlinesCompositionDto.PROPERTY_PROPORTION, false)); - - initModel(ui, metas); - - } - - - @Override - protected ContentTableModel<SetLonglineGlobalCompositionDto, FloatlinesCompositionDto> createTableModel( - ObserveContentTableUI<SetLonglineGlobalCompositionDto, FloatlinesCompositionDto> ui, - List<ContentTableMeta<FloatlinesCompositionDto>> contentTableMetas) { - - return new ContentTableModel<SetLonglineGlobalCompositionDto, FloatlinesCompositionDto>(ui, contentTableMetas) { - private static final long serialVersionUID = 1L; - @Override - protected Collection<FloatlinesCompositionDto> getChilds(SetLonglineGlobalCompositionDto bean) { - return bean.getFloatlinesComposition(); - } - - @Override - protected void load(FloatlinesCompositionDto source, FloatlinesCompositionDto target) { - FloatlinesCompositionDtos.copyFloatlinesCompositionDto(source, target); - } - - @Override - protected void setChilds(SetLonglineGlobalCompositionDto parent, List<FloatlinesCompositionDto> childs) { - parent.setFloatlinesComposition(childs); - } - }; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/GearUseFeaturesLonglineTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/GearUseFeaturesLonglineTableModel.java deleted file mode 100644 index ae3ba85..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/GearUseFeaturesLonglineTableModel.java +++ /dev/null @@ -1,175 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Sets; -import fr.ird.observe.services.dto.longline.GearUseFeaturesLonglineDto; -import fr.ird.observe.services.dto.longline.GearUseFeaturesLonglineDtos; -import fr.ird.observe.services.dto.longline.GearUseFeaturesMeasurementLonglineDto; -import fr.ird.observe.services.dto.longline.TripLonglineGearUseDto; -import fr.ird.observe.services.dto.referential.GearDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.Collection; -import java.util.List; - -/** - * Created on 4/7/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.16 - */ -public class GearUseFeaturesLonglineTableModel extends ContentTableModel<TripLonglineGearUseDto, GearUseFeaturesLonglineDto> { - - /** Logger. */ - private static final Log log = LogFactory.getLog(GearUseFeaturesLonglineTableModel.class); - - private static final long serialVersionUID = 1L; - - private transient GearUseFeaturesLonglineUIHandler gearUseFeaturesLonglineUIHandler; - - public GearUseFeaturesLonglineTableModel(ObserveContentTableUI<TripLonglineGearUseDto, GearUseFeaturesLonglineDto> context, - List<ContentTableMeta<GearUseFeaturesLonglineDto>> contentTableMetas) { - super(context, contentTableMetas); - } - - public void setGearUseFeaturesLonglineUIHandler(GearUseFeaturesLonglineUIHandler gearUseFeaturesLonglineUIHandler) { - this.gearUseFeaturesLonglineUIHandler = gearUseFeaturesLonglineUIHandler; - } - - @Override - public void addNewEntry() { - - int editingRow = getSelectedRow(); - - if (editingRow > -1) { - - // store sizes and weights for the selected row - // before creating a new one ? - GearUseFeaturesLonglineUIModel model = getModel(); - model.getMeasurementsTableModel().storeInCacheForRow(editingRow); - - } - - super.addNewEntry(); - } - - @Override - public void updateRowFromEditBean() { - - GearUseFeaturesLonglineUIModel model = getModel(); - - int editingRow = getSelectedRow(); - GearUseFeaturesLonglineDto rowBean = getRowBean(); - GearUseFeaturesMeasurementLonglinesTableModel measurementsTableModel = model.getMeasurementsTableModel(); - - List<GearUseFeaturesMeasurementLonglineDto> measurements; - - if (rowBean.getId() == null && CollectionUtils.isEmpty(measurementsTableModel.getCacheForRow(editingRow))) { - - // new gear usage, add default measurements - - ReferentialReference<GearDto> gear = rowBean.getGear(); - measurements = gearUseFeaturesLonglineUIHandler.getDefaultGearUseFeaturesMeasurementLongline(gear.getId()); - if (log.isInfoEnabled()) { - log.info("Create mode, use default measurements: " + measurements.size()); - } - measurementsTableModel.removeCacheForRow(editingRow); - measurementsTableModel.initCacheForRow(editingRow, measurements); - - measurementsTableModel.setData(measurements); - measurementsTableModel.setModified(false); - - } else { - - // store current measurements for the selected row - measurementsTableModel.storeInCacheForRow(editingRow); - measurements = measurementsTableModel.getData(); - } - - rowBean.setGearUseFeaturesMeasurement(Sets.newLinkedHashSet(measurements)); - - super.updateRowFromEditBean(); - - } - - @Override - protected void removeRow(int row) { - super.removeRow(row); - - // remove sizes and weights for the deleted row - // also update rows to row - 1 (when after the deleted row) - GearUseFeaturesLonglineUIModel model = getModel(); - model.getMeasurementsTableModel().removeCacheForRow(row); - - } - - @Override - protected void setChilds(TripLonglineGearUseDto parent, List<GearUseFeaturesLonglineDto> childs) { - parent.getGearUseFeaturesLongline().clear(); - parent.addAllGearUseFeaturesLongline(childs); - } - - @Override - public void resetEditBean() { - - int row = getSelectedRow(); - if (log.isInfoEnabled()) { - log.info("Reset edit bean at row: " + row); - } - GearUseFeaturesLonglineUIModel model = getModel(); - model.getMeasurementsTableModel().resetCacheForRow(row); - - super.resetEditBean(); - - } - - @Override - protected Collection<GearUseFeaturesLonglineDto> getChilds(TripLonglineGearUseDto bean) { - return bean.getGearUseFeaturesLongline(); - } - - @Override - protected void load(GearUseFeaturesLonglineDto source, GearUseFeaturesLonglineDto target) { - GearUseFeaturesLonglineDtos.copyGearUseFeaturesLonglineDto(source, target); - } - - @Override - protected void resetRow(int row) { - super.resetRow(row); - - GearUseFeaturesLonglineUIModel model = getModel(); - model.getMeasurementsTableModel().resetCacheForRow(row); - } - - @Override - protected GearUseFeaturesLonglineUIModel getModel() { - return (GearUseFeaturesLonglineUIModel) super.getModel(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/GearUseFeaturesLonglineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/GearUseFeaturesLonglineUI.jaxx deleted file mode 100644 index d97a753..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/GearUseFeaturesLonglineUI.jaxx +++ /dev/null @@ -1,155 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.table.ContentTableUI - superGenericType='TripLonglineGearUseDto, GearUseFeaturesLonglineDto' - contentTitle='{n("observe.content.gearUseFeaturesLongline.title")}' - saveNewEntryText='{n("observe.content.action.gearUseFeaturesLongline")}' - saveNewEntryTip='{n("observe.content.action.gearUseFeaturesLongline.tip")}'> - - <style source="../../CommonTable.jcss"/> - - <import> - fr.ird.observe.services.dto.CommentableDto - fr.ird.observe.services.dto.longline.TripLonglineDto - fr.ird.observe.services.dto.longline.GearUseFeaturesLonglineDto - fr.ird.observe.services.dto.longline.GearUseFeaturesMeasurementLonglineDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.GearDto - fr.ird.observe.ui.content.table.* - fr.ird.observe.ui.util.BooleanEditor - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - java.awt.Dimension - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <GearUseFeaturesLonglineUIHandler id='handler' constructorParams='this'/> - - <!-- model --> - <GearUseFeaturesLonglineUIModel id='model' constructorParams='this'/> - - <GearUseFeaturesMeasurementLonglinesTableModel id='measurementsTableModel' - initializer="getModel().getMeasurementsTableModel()"/> - - <!-- edit bean --> - <TripLonglineDto id='bean'/> - - <!-- table edit bean --> - <GearUseFeaturesLonglineDto id='tableEditBean'/> - - <!-- table model --> - <ContentTableModel id='tableModel'/> - - <!-- le validateur de l'écran --> - <BeanValidator id='validator' - beanClass='fr.ird.observe.services.dto.longline.TripLonglineGearUseDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update'/> - - <!-- le validateur d'une entrée de tableau --> - <BeanValidator id='validatorTable' - autoField='true' - beanClass='fr.ird.observe.services.dto.longline.GearUseFeaturesLonglineDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update'/> - - <JPopupMenu id='measurementsTablePopup'> - <JMenuItem id='addMeasurement' onActionPerformed='getHandler().addMeasurement()'/> - <JMenuItem id='deleteSelectedMeasurement' onActionPerformed='getHandler().deleteSelectedMeasurement()'/> - </JPopupMenu> - - <Table id='editorPanel' fill='both' insets='0' weighty="1"> - <row> - <cell weightx="1" weighty="0.9"> - - <JTabbedPane id='gearUseFeaturesTabPane'> - - <tab id='generalTab'> - - <JPanel layout='{new BorderLayout()}'> - - <Table id='editForm' fill='both' insets='1' constraints="BorderLayout.NORTH"> - - <!-- gear --> - <row> - <cell> - <JLabel id='gearLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='gear' constructorParams='this' genericType='ReferentialReference<GearDto>' _entityClass='GearDto.class'/> - </cell> - </row> - - <!-- number --> - <row> - <cell> - <JLabel id='numberLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='number' constructorParams='this'/> - </cell> - </row> - - <!-- usedInTrip --> - <row> - <cell> - <JLabel id='usedInTripLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BooleanEditor id='usedInTrip'/> - </cell> - </row> - - </Table> - - </JPanel> - - - </tab> - - <tab id='measurementsFormTab'> - - <JScrollPane id='measurementsScrollPane'> - <JTable id='measurementsTable'/> - </JScrollPane> - - </tab> - </JTabbedPane> - - </cell> - </row> - <row> - <cell weighty='0.1'> - <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2'/> - </JScrollPane> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/GearUseFeaturesLonglineUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/GearUseFeaturesLonglineUI.jcss deleted file mode 100644 index c99cca4..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/GearUseFeaturesLonglineUI.jcss +++ /dev/null @@ -1,105 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#model { - valid:{validator.isValid() && validatorTable.isValid() && getMeasurementsTableModel().isValid()}; - canSaveRow:{validatorTable.isChanged() && validatorTable.isValid() && getMeasurementsTableModel().isValid()}; - canResetRow:{validatorTable.isChanged()}; -} - -/* ***************************************************************************** */ -/* GENERAL TAB **************************************************************** */ -/* ***************************************************************************** */ - -#generalTab { - title:{t("observe.content.gearUseFeaturesLongline.tab.general")}; - icon:{handler.getErrorIconIfFalse(model.isGeneralTabValid())}; -} - -#gearLabel { - text:"observe.content.gearUseFeaturesLongline.gear"; - labelFor:{gear}; -} - -#gear { - property:{GearUseFeaturesLonglineDto.PROPERTY_GEAR}; - selectedItem:{tableEditBean.getGear()}; -} - -#numberLabel { - text:"observe.content.gearUseFeaturesLongline.number"; - labelFor:{number}; -} - -#number { - property:{GearUseFeaturesLonglineDto.PROPERTY_NUMBER}; - model:{tableEditBean.getNumber()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; -} - -#usedInTripLabel { - text:"observe.content.gearUseFeaturesLongline.usedInTrip"; - labelFor:{usedInTrip}; -} - -#usedInTrip { - booleanValue:{tableEditBean.getUsedInTrip()}; - _tablePropertyName:{GearUseFeaturesLonglineDto.PROPERTY_USED_IN_TRIP}; -} - -/* ***************************************************************************** */ -/* MEASUREMENTS TAB *********************************************************** */ -/* ***************************************************************************** */ - -#measurementsFormTab { - title:{t("observe.content.gearUseFeaturesLongline.tab.measurements")}; - icon:{handler.getErrorIconIfFalse(measurementsTableModel.isValid())}; - enabled:{!tableModel.isCreate()}; -} - -#measurementsTable { - model: {measurementsTableModel}; -} - -#comment { - columnHeaderView:{new JLabel(t("observe.content.gearUseFeaturesLongline.comment"))}; - minimumSize:{new Dimension(10,80)}; -} - -#comment2 { - _tablePropertyName: {GearUseFeaturesLonglineDto.PROPERTY_COMMENT}; - text:{getStringValue(tableEditBean.getComment())}; -} - -#addMeasurement { - text: "observe.content.gearUseFeaturesLongline.action.addMeasurement"; - toolTipText: "observe.content.gearUseFeaturesLongline.action.addMeasurement.tip"; - actionIcon: add; -} - - - -#deleteSelectedMeasurement { - text: "observe.content.gearUseFeaturesLongline.action.deleteSelectedMeasurement"; - toolTipText: "observe.content.gearUseFeaturesLongline.action.deleteSelectedMeasurement.tip"; - actionIcon: delete; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/GearUseFeaturesLonglineUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/GearUseFeaturesLonglineUIHandler.java deleted file mode 100644 index fd9c83d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/GearUseFeaturesLonglineUIHandler.java +++ /dev/null @@ -1,508 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.longline.GearUseFeaturesLonglineDto; -import fr.ird.observe.services.dto.longline.GearUseFeaturesMeasurementLonglineDto; -import fr.ird.observe.services.dto.longline.TripLonglineGearUseDto; -import fr.ird.observe.services.dto.longline.TripLonglineGearUseDtos; -import fr.ird.observe.services.dto.referential.GearCaracteristicDto; -import fr.ird.observe.services.dto.referential.GearCaracteristicTypeDtos; -import fr.ird.observe.services.dto.referential.GearDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.service.ReferentialService; -import fr.ird.observe.services.service.longline.TripLonglineGearUseService; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.ContentUIInitializer; -import fr.ird.observe.ui.content.table.ContentTableUIHandler; -import fr.ird.observe.ui.content.table.impl.seine.GearUseFeatureMeasurementCellEditor; -import fr.ird.observe.ui.content.table.impl.seine.GearUseFeatureMeasurementCellRenderer; -import jaxx.runtime.SwingUtil; -import jaxx.runtime.validator.swing.SwingValidatorMessage; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.JTable; -import javax.swing.event.TableModelListener; -import javax.swing.table.DefaultTableCellRenderer; -import java.awt.GridBagConstraints; -import java.awt.Insets; -import java.beans.PropertyChangeListener; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 3/24/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.16 - */ -public class GearUseFeaturesLonglineUIHandler extends ContentTableUIHandler<TripLonglineGearUseDto, GearUseFeaturesLonglineDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(GearUseFeaturesLonglineUIHandler.class); - - // Compute valid state of tab from the error table - protected final TableModelListener computeTabValidStateListener; - - private final PropertyChangeListener measurementsTableModelModified; - - public GearUseFeaturesLonglineUIHandler(GearUseFeaturesLonglineUI ui) { - super(ui, DataContextType.TripLongline); - computeTabValidStateListener = e -> { - - SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); - computeTabValidState(source); - - }; - measurementsTableModelModified = evt -> onMeasurementsTableModelModified((Boolean) evt.getNewValue()); - } - - @Override - public GearUseFeaturesLonglineUI getUi() { - return (GearUseFeaturesLonglineUI) super.getUi(); - } - - @Override - public GearUseFeaturesLonglineUIModel getModel() { - return (GearUseFeaturesLonglineUIModel) super.getModel(); - } - - @Override - public void initUI() { - - super.initUI(); - - getModel().addPropertyChangeListener(GearUseFeaturesLonglineUIModel.PROPERTY_EDITABLE, evt -> { - Boolean newValue = (Boolean) evt.getNewValue(); - setTableModelEditable(newValue); - }); - - setTableModelEditable(getModel().isEditable()); - - getTableModel().setGearUseFeaturesLonglineUIHandler(this); - - } - - @Override - public void openUI() { - - if (log.isInfoEnabled()) { - log.info("OpenUI: " + getModel()); - } - - super.openUI(); - - // To be sure always remove listener (could prevent some leaks) - getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); - // listen messages to see if required to add - getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); - - SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); - computeTabValidState(errorTableModel); - - } - - @Override - public void startEditUI(String... binding) { - - getModel().getMeasurementsTableModel().setEditable(true); - - super.startEditUI(binding); - - } - - public void addMeasurement() { - - GearUseFeaturesMeasurementLonglinesTableModel tableModel = getUi().getMeasurementsTableModel(); - tableModel.addNewRow(); - - } - - public void deleteSelectedMeasurement() { - - GearUseFeaturesMeasurementLonglinesTableModel tableModel = getUi().getMeasurementsTableModel(); - - boolean selectionEmpty = tableModel.isSelectionEmpty(); - - if (!selectionEmpty) { - - GearUseFeaturesMeasurementLonglineDto data = tableModel.getSelectedRow(); - - if (log.isInfoEnabled()) { - log.info("Delete: " + data); - } - - ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); - int response = UIHelper.askUser(mainUI, - t("observe.title.delete"), - t("observe.content.measurement.delete.message"), - JOptionPane.WARNING_MESSAGE, - new Object[]{t("observe.choice.confirm.delete"), - t("observe.choice.cancel")}, - 1); - - if (response != 0) { - - // user cancel - return; - } - - tableModel.removeSelectedRow(); - - } - - } - - public List<GearUseFeaturesMeasurementLonglineDto> getDefaultGearUseFeaturesMeasurementLongline(String gearId) { - - ReferentialService referentialService = getDataSource().newReferentialService(); - - Form<GearDto> gearDtoForm = referentialService.loadForm(GearDto.class, gearId); - - GearDto gearDto = gearDtoForm.getObject(); - - List<GearUseFeaturesMeasurementLonglineDto> measurements = Lists.newArrayList( - Iterables.transform(gearDto.getGearCaracteristic(), - input -> { - GearUseFeaturesMeasurementLonglineDto measurementLonglineDto = new GearUseFeaturesMeasurementLonglineDto(); - measurementLonglineDto.setGearCaracteristic(input); - String gearCaracterisiticTypeId = (String) input.getPropertyValue(GearCaracteristicDto.PROPERTY_GEAR_CARACTERISTIC_TYPE); - if (GearCaracteristicTypeDtos.isBoolean(gearCaracterisiticTypeId)) { - measurementLonglineDto.setMeasurementValue(Boolean.FALSE.toString()); - } - return measurementLonglineDto; - })); - - return measurements; - } - - @Override - protected void onSelectedRowChanged(int editingRow, GearUseFeaturesLonglineDto bean, boolean create) { - - if (log.isInfoEnabled()) { - log.info("Selected row changed: " + editingRow + ", create? " + create); - } - - GearUseFeaturesLonglineUI ui = getUi(); - - UIHelper.stopEditing(ui.getMeasurementsTable()); - - GearUseFeaturesLonglineTableModel tableModel = getTableModel(); - GearUseFeaturesLonglineUIModel model = getModel(); - - boolean emptySelection = editingRow == -1; - - // load size measures - - GearUseFeaturesMeasurementLonglinesTableModel measurementsTableModel = model.getMeasurementsTableModel(); - List<GearUseFeaturesMeasurementLonglineDto> measurements = emptySelection ? Collections.emptyList() : measurementsTableModel.getCacheForRow(editingRow); - if (measurements == null) { - - if (log.isInfoEnabled()) { - log.info("init measurements for row " + editingRow); - } - - // first time coming on this row - - if (tableModel.isCreate()) { - - // create mode: just init with empty list - measurements = Collections.emptyList(); - - if (log.isInfoEnabled()) { - log.info("create mode, use an empty list"); - } - - } else { - - measurements = Lists.newArrayList(bean.getGearUseFeaturesMeasurement()); - - } - - // init measurements - measurementsTableModel.initCacheForRow(editingRow, measurements); - - } else { - - if (log.isInfoEnabled()) { - log.info("Using existing measurements for row " + editingRow + " : " + measurements.size()); - } - } - - measurementsTableModel.setData(measurements); - - measurementsTableModel.setModified(false); - measurementsTableModel.setEditable(tableModel.isEditable()); - - if (!tableModel.isEditable()) { - return; - } - - JComponent requestFocus; - - if (tableModel.isCreate()) { - - // go back to first pane - ui.getGearUseFeaturesTabPane().setSelectedIndex(0); - - requestFocus = ui.getGear(); - - } else { - - requestFocus = ui.getGear(); - - } - - requestFocus.requestFocus(); - - } - - @Override - protected void initTableUI(DefaultTableCellRenderer renderer) { - - { - JTable table = getUi().getTable(); - - UIHelper.setI18nTableHeaderRenderer(table, - n("observe.content.gearUseFeaturesLongline.table.gear"), - n("observe.content.gearUseFeaturesLongline.table.gear.tip"), - n("observe.content.gearUseFeaturesLongline.table.number"), - n("observe.content.gearUseFeaturesLongline.table.number.tip"), - n("observe.content.gearUseFeaturesLongline.table.usedInTrip"), - n("observe.content.gearUseFeaturesLongline.table.usedInTrip.tip"), - n("observe.content.gearUseFeaturesLongline.table.comment"), - n("observe.content.gearUseFeaturesLongline.table.comment.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, GearDto.class)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 2, UIHelper.newBooleanTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 3, UIHelper.newStringTableCellRenderer(renderer, 10, true)); - } - - { - // init measurements table - JTable table = getUi().getMeasurementsTable(); - - UIHelper.setI18nTableHeaderRenderer(table, - n("observe.content.gearUseFeaturesLongline.table.gearCaracteristic"), - n("observe.content.gearUseFeaturesLongline.table.gearCaracteristic.tip"), - n("observe.content.gearUseFeaturesLongline.table.value"), - n("observe.content.gearUseFeaturesLongline.table.value.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, GearCaracteristicDto.class)); - UIHelper.setTableColumnRenderer(table, 1, new GearUseFeatureMeasurementCellRenderer(0, renderer)); - - table.getTableHeader().setReorderingAllowed(false); - - ReferentialReferenceDecorator<GearCaracteristicDto> decorator = getReferentialReferenceDecorator(GearCaracteristicDto.class); - - List<ReferentialReference<GearCaracteristicDto>> caracteristics = Lists.newArrayList(getDataSource().getReferentialReferences(GearCaracteristicDto.class)); - - UIHelper.setTableColumnEditor(table, 0, ContentUIInitializer.newDataColumnEditor(caracteristics, decorator)); - UIHelper.setTableColumnEditor(table, 1, new GearUseFeatureMeasurementCellEditor(0)); - - initInlineTable(getUi().getMeasurementsScrollPane(), - table, - getModel().getMeasurementsTableModel(), - measurementsTableModelModified, - getUi().getMeasurementsTablePopup(), - getUi().getAddMeasurement(), - getUi().getDeleteSelectedMeasurement()); - - } - - // Adapt layout to let more place for the editor - - getUi().getShowForm().remove(1); - getUi().getShowForm().add(SwingUtil.boxComponentWithJxLayer(getUi().getEditor()), new GridBagConstraints(0, 1, 1, 1, 1.0, 0.3, 10, 1, new Insets(0, 0, 0, 0), 0, 0), 1); - getUi().getEditor().remove(0); - getUi().getEditor().add(SwingUtil.boxComponentWithJxLayer(getUi().getEditorPanel()), new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, 10, 1, new Insets(0, 0, 0, 0), 0, 0), 0); - - - } - - @Override - protected String getEditBeanIdToLoad() { - return getDataContext().getSelectedTripLonglineId(); - } - - @Override - protected void closeSafeUI() { - - if (log.isInfoEnabled()) { - log.info("CloseUI: " + getModel()); - } - super.closeSafeUI(); - - // remove listener - getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); - - } - - @Override - protected void resetEditBean() { - - UIHelper.stopEditing(getUi().getMeasurementsTable()); - - super.resetEditBean(); - - } - - @Override - public void resetEditUI() { - - getModel().getMeasurementsTableModel().clear(); - - super.resetEditUI(); - - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - // par defaut, on suppose qu'on peut afficher les données - getModel().setShowData(true); - - String selectedTripId = dataContext.getSelectedTripId(); - - if (getOpenDataManager().isOpenTripLongline(selectedTripId)) { - - // mode mise a jour - return ContentMode.UPDATE; - } - - // mode lecture - - if (dataContext.isSelectedTripLongline()) { - - addInfoMessage(t("observe.content.tripLongline.message.not.open")); - - } else { - - addInfoMessage(t("observe.content.tripLongline.message.not.open")); - - } - - return ContentMode.READ; - } - - @Override - protected GearUseFeaturesLonglineTableModel getTableModel() { - return (GearUseFeaturesLonglineTableModel) super.getTableModel(); - } - - protected void setTableModelEditable(Boolean newValue) { - - getModel().getMeasurementsTableModel().setEditable(newValue); - - } - - protected void onMeasurementsTableModelModified(Boolean newValue) { - - if (newValue) { - - // modify the validator, since this is the best way to prevent table edit form actions - // that something was modified on the form - getUi().getValidatorTable().setChanged(true); - - } - - // recompute table model valid state - getModel().getMeasurementsTableModel().validate(); - - } - - protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { - - Set<String> errorProperties = new HashSet<>(); - int rowCount = errorTableModel.getRowCount(); - for (int i = 0; i < rowCount; i++) { - - SwingValidatorMessage row = errorTableModel.getRow(i); - if (NuitonValidatorScope.ERROR.equals(row.getScope())) { - errorProperties.add(row.getField()); - } - } - - boolean generalTabValid = !errorProperties.removeAll(GearUseFeaturesLonglineUIModel.GENERAL_TAB_PROPERTIES); - - GearUseFeaturesLonglineUIModel model = getModel(); - - model.setGeneralTabValid(generalTabValid); - - } - - @Override - protected void doPersist(TripLonglineGearUseDto bean) { - - // On ne persiste pas les measurements qui sont vides - for (GearUseFeaturesLonglineDto gearUseFeatures : bean.getGearUseFeaturesLongline()) { - if (!gearUseFeatures.isGearUseFeaturesMeasurementEmpty()) { - Iterator<GearUseFeaturesMeasurementLonglineDto> iterator = gearUseFeatures.getGearUseFeaturesMeasurement().iterator(); - while (iterator.hasNext()) { - GearUseFeaturesMeasurementLonglineDto gearUseFeaturesMeasurement = iterator.next(); - if (gearUseFeaturesMeasurement.isEmpty()) { - iterator.remove(); - } - } - } - } - SaveResultDto saveResult = getTripLonglineGearUseService().save(bean); - saveResult.toDto(bean); - - } - - @Override - protected void loadEditBean(String beanId) { - Form<TripLonglineGearUseDto> form = getTripLonglineGearUseService().loadForm(beanId); - loadReferentialReferenceSetsInModel(form); - getModel().setForm(form); - TripLonglineGearUseDtos.copyTripLonglineGearUseDto(form.getObject(), getBean()); - } - - protected TripLonglineGearUseService getTripLonglineGearUseService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripLonglineGearUseService(); - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/GearUseFeaturesLonglineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/GearUseFeaturesLonglineUIModel.java deleted file mode 100644 index 8c7766f..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/GearUseFeaturesLonglineUIModel.java +++ /dev/null @@ -1,106 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; -import fr.ird.observe.services.dto.longline.GearUseFeaturesLonglineDto; -import fr.ird.observe.services.dto.longline.TripLonglineGearUseDto; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; - -import java.util.List; -import java.util.Set; - -/** - * Created on 3/24/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.16 - */ -public class GearUseFeaturesLonglineUIModel extends ContentTableUIModel<TripLonglineGearUseDto, GearUseFeaturesLonglineDto> { - - private static final long serialVersionUID = 1L; - - public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; - - public static final Set<String> GENERAL_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(GearUseFeaturesLonglineDto.PROPERTY_GEAR, - GearUseFeaturesLonglineDto.PROPERTY_NUMBER, - GearUseFeaturesLonglineDto.PROPERTY_USED_IN_TRIP, - GearUseFeaturesLonglineDto.PROPERTY_COMMENT).build(); - - protected boolean generalTabValid; - - private final GearUseFeaturesMeasurementLonglinesTableModel measurementsTableModel; - - public GearUseFeaturesLonglineUIModel(GearUseFeaturesLonglineUI ui) { - - super(TripLonglineGearUseDto.class, - GearUseFeaturesLonglineDto.class, - new String[]{ - TripLonglineGearUseDto.PROPERTY_ID, - TripLonglineGearUseDto.PROPERTY_GEAR_USE_FEATURES_LONGLINE, - TripLonglineGearUseDto.PROPERTY_LAST_UPDATE_DATE, - }, - new String[]{ - GearUseFeaturesLonglineDto.PROPERTY_ID, - GearUseFeaturesLonglineDto.PROPERTY_COMMENT, - GearUseFeaturesLonglineDto.PROPERTY_GEAR, - GearUseFeaturesLonglineDto.PROPERTY_NUMBER, - GearUseFeaturesLonglineDto.PROPERTY_USED_IN_TRIP}); - - this.measurementsTableModel = new GearUseFeaturesMeasurementLonglinesTableModel(); - - List<ContentTableMeta<GearUseFeaturesLonglineDto>> metas = Lists.newArrayList( - ContentTableModel.newTableMeta(GearUseFeaturesLonglineDto.class, GearUseFeaturesLonglineDto.PROPERTY_GEAR, false), - ContentTableModel.newTableMeta(GearUseFeaturesLonglineDto.class, GearUseFeaturesLonglineDto.PROPERTY_NUMBER, false), - ContentTableModel.newTableMeta(GearUseFeaturesLonglineDto.class, GearUseFeaturesLonglineDto.PROPERTY_USED_IN_TRIP, false), - ContentTableModel.newTableMeta(GearUseFeaturesLonglineDto.class, GearUseFeaturesLonglineDto.PROPERTY_COMMENT, false) - ); - - initModel(ui, metas); - - } - - @Override - protected GearUseFeaturesLonglineTableModel createTableModel(ObserveContentTableUI<TripLonglineGearUseDto, GearUseFeaturesLonglineDto> ui, List<ContentTableMeta<GearUseFeaturesLonglineDto>> contentTableMetas) { - return new GearUseFeaturesLonglineTableModel(ui, contentTableMetas); - } - - public GearUseFeaturesMeasurementLonglinesTableModel getMeasurementsTableModel() { - return measurementsTableModel; - } - - public boolean isGeneralTabValid() { - return generalTabValid; - } - - public void setGeneralTabValid(boolean generalTabValid) { - this.generalTabValid = generalTabValid; - firePropertyChange(PROPERTY_GENERAL_TAB_VALID, null, isGeneralTabValid()); - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/GearUseFeaturesMeasurementLonglinesTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/GearUseFeaturesMeasurementLonglinesTableModel.java deleted file mode 100644 index 66afdcc..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/GearUseFeaturesMeasurementLonglinesTableModel.java +++ /dev/null @@ -1,136 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.longline.GearUseFeaturesMeasurementLonglineDto; -import fr.ird.observe.services.dto.referential.GearCaracteristicDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.util.table.EditableTableWithCacheTableModelSupport; - -/** - * Created on 4/7/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.16 - */ -public class GearUseFeaturesMeasurementLonglinesTableModel extends EditableTableWithCacheTableModelSupport<GearUseFeaturesMeasurementLonglineDto> { - - private static final long serialVersionUID = 1L; - - public GearUseFeaturesMeasurementLonglinesTableModel() { - super(); - } - - @Override - public boolean isRowNotEmpty(GearUseFeaturesMeasurementLonglineDto valid) { - return !(valid.getGearCaracteristic() == null && valid.getMeasurementValue() == null); - } - - @Override - protected boolean isRowValid(GearUseFeaturesMeasurementLonglineDto valid) { - String size = valid.getMeasurementValue(); - return !(valid.getGearCaracteristic() == null || size == null) && !size.isEmpty(); - } - - @Override - public int getColumnCount() { - return 2; - } - - @Override - public Object getValueAt(int rowIndex, int columnIndex) { - - GearUseFeaturesMeasurementLonglineDto measure = data.get(rowIndex); - Object result; - switch (columnIndex) { - case 0: - result = measure.getGearCaracteristic(); - break; - case 1: - result = measure.getMeasurementValue(); - break; - default: - throw new IllegalStateException("Can't come here"); - } - return result; - } - - @Override - public boolean isCellEditable(int rowIndex, int columnIndex) { - - boolean result; - switch (columnIndex) { - case 0: - result = true; - break; - case 1: - GearUseFeaturesMeasurementLonglineDto measure = data.get(rowIndex); - result = measure != null && measure.getGearCaracteristic() != null; - break; - default: - throw new IllegalStateException("Can't come here"); - } - return result; - - } - - @Override - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - - GearUseFeaturesMeasurementLonglineDto measure = data.get(rowIndex); - switch (columnIndex) { - case 0: - - measure.setGearCaracteristic((ReferentialReference<GearCaracteristicDto>) aValue); - - break; - case 1: - - measure.setMeasurementValue(aValue == null ? null : String.valueOf(aValue)); - - break; - - default: - throw new IllegalStateException("Can't come here"); - } - - setModified(true); - - } - - @Override - public void removeSelectedRow() { - - super.removeSelectedRow(); - - // revalidate table model - validate(); - setModified(true); - - } - - @Override - protected GearUseFeaturesMeasurementLonglineDto createNewRow() { - return new GearUseFeaturesMeasurementLonglineDto(); - } -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/HooksCompositionUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/HooksCompositionUI.jaxx deleted file mode 100644 index 98ea7df..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/HooksCompositionUI.jaxx +++ /dev/null @@ -1,131 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.table.ContentTableUI - superGenericType='SetLonglineGlobalCompositionDto, HooksCompositionDto' - contentTitle='{n("observe.content.hooksComposition.title")}' - saveNewEntryText='{n("observe.content.hooksComposition.action.create")}' - saveNewEntryTip='{n("observe.content.hooksComposition.action.create.tip")}'> - - <style source="../../CommonTable.jcss"/> - - <import> - fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto - fr.ird.observe.services.dto.longline.HooksCompositionDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.longline.HookTypeDto - fr.ird.observe.services.dto.referential.longline.HookSizeDto - fr.ird.observe.ui.content.table.* - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <HooksCompositionUIHandler id='handler'/> - - <!-- model --> - <HooksCompositionUIModel id='model'/> - - <!-- edit bean --> - <SetLonglineGlobalCompositionDto id='bean'/> - - <!-- table edit bean --> - <HooksCompositionDto id='tableEditBean'/> - - <!-- table model --> - <ContentTableModel id='tableModel'/> - - <!-- le validateur de l'écran --> - <BeanValidator id='validator' autoField='true' context='ui-update-hooksComposition' - beanClass='fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto' - errorTableModel='{getErrorTableModel()}'> - <field name="hooksComposition" component="editorPanel"/> - </BeanValidator> - - <!-- le validateur d'une entrée de tableau --> - <BeanValidator id='validatorTable' autoField='true' context='ui-update' - beanClass='fr.ird.observe.services.dto.longline.HooksCompositionDto' - errorTableModel='{getErrorTableModel()}'/> - - <Table id='editorPanel' fill='both' insets='1'> - - <!-- HookType --> - <row> - <cell> - <JLabel id='hookTypeLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='hookType' constructorParams='this' genericType='ReferentialReference<HookTypeDto>' _entityClass='HookTypeDto.class'/> - </cell> - </row> - - <!-- HookSize --> - <row> - <cell> - <JLabel id='hookSizeLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='hookSize' constructorParams='this' genericType='ReferentialReference<HookSizeDto>' _entityClass='HookSizeDto.class'/> - </cell> - </row> - - - <!-- hookOffset --> - <row> - <cell> - <JLabel id='hookOffsetLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='hookOffset' constructorParams='this'/> - </cell> - </row> - - <!-- proportion --> - <row> - <cell> - <JLabel id='proportionLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='proportion' constructorParams='this'/> - </cell> - </row> - - </Table> - - <Table id='extraZone' fill='both'> - - <!-- proportion sum --> - <row> - <cell> - <JLabel id='hooksCompositionProportionSumLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <JLabel id='hooksCompositionProportionSum'/> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/HooksCompositionUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/HooksCompositionUI.jcss deleted file mode 100644 index adbd7e2..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/HooksCompositionUI.jcss +++ /dev/null @@ -1,79 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#hookTypeLabel { - text:"observe.content.hooksComposition.hookType"; - labelFor:{hookType}; -} - -#hookType { - property:{HooksCompositionDto.PROPERTY_HOOK_TYPE}; - selectedItem:{tableEditBean.getHookType()}; - _validatorLabel:{t("observe.content.hooksComposition.hookType")}; -} - -#hookSizeLabel { - text:"observe.content.hooksComposition.hookSize"; - labelFor:{hookSize}; -} - -#hookSize { - property:{HooksCompositionDto.PROPERTY_HOOK_SIZE}; - selectedItem:{tableEditBean.getHookSize()}; - _validatorLabel:{t("observe.content.hooksComposition.hookSize")}; -} - - -#hookOffsetLabel { - text:"observe.content.hooksComposition.hookOffset"; - labelFor:{hookOffset}; -} - -#hookOffset { - property:{HooksCompositionDto.PROPERTY_HOOK_OFFSET}; - model:{tableEditBean.getHookOffset()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.hooksComposition.hookOffset")}; -} - -#proportionLabel { - text:"observe.content.hooksComposition.proportion"; - labelFor:{proportion}; -} - -#proportion { - property:{HooksCompositionDto.PROPERTY_PROPORTION}; - model:{tableEditBean.getProportion()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; - _validatorLabel:{t("observe.content.hooksComposition.proportion")}; -} - -#hooksCompositionProportionSumLabel { - text:"observe.content.hooksComposition.proportionSum"; - labelFor:{hooksCompositionProportionSum}; -} - -#hooksCompositionProportionSum { - text:{getStringValue(bean.getHooksCompositionProportionSum())}; - _validatorLabel:{t("observe.content.hooksComposition.proportionSum")}; - font-weight:bold; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/HooksCompositionUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/HooksCompositionUIHandler.java deleted file mode 100644 index 3c914d0..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/HooksCompositionUIHandler.java +++ /dev/null @@ -1,120 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.longline.HooksCompositionDto; -import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto; -import fr.ird.observe.services.dto.referential.longline.HookSizeDto; -import fr.ird.observe.services.dto.referential.longline.HookTypeDto; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.table.ContentTableUIHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; - -import static org.nuiton.i18n.I18n.n; - -/** - * Created on 12/6/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.9 - */ -public class HooksCompositionUIHandler extends ContentTableUIHandler<SetLonglineGlobalCompositionDto, HooksCompositionDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(HooksCompositionUIHandler.class); - - public HooksCompositionUIHandler(HooksCompositionUI ui) { - super(ui, DataContextType.SetLongline); - } - - @Override - public HooksCompositionUI getUi() { - return (HooksCompositionUI) super.getUi(); - } - - @Override - protected void onSelectedRowChanged(int editingRow, HooksCompositionDto bean, boolean create) { - - if (getTableModel().isEditable()) { - if (log.isDebugEnabled()) { - log.debug("Row has changed to " + editingRow); - } - getUi().getHookType().requestFocus(); - } - - } - - @Override - protected void initTableUI(DefaultTableCellRenderer renderer) { - - JTable table = getUi().getTable(); - - UIHelper.setI18nTableHeaderRenderer( - table, - n("observe.content.hooksComposition.table.hookType"), - n("observe.content.hooksComposition.table.hookType.tip"), - n("observe.content.hooksComposition.table.hookSize"), - n("observe.content.hooksComposition.table.hookSize.tip"), - n("observe.content.hooksComposition.table.hookOffset"), - n("observe.content.hooksComposition.table.hookOffset.tip"), - n("observe.content.hooksComposition.table.proportion"), - n("observe.content.hooksComposition.table.proportion.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, HookTypeDto.class)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, HookSizeDto.class)); - UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - - // when model change in table, let's recompute the proportion sum - table.getModel().addTableModelListener(e -> { - int proportionSum = getBean().getHooksCompositionProportionSum(); - getBean().setHooksCompositionProportionSum(proportionSum); - }); - - } - - @Override - protected String getEditBeanIdToLoad() { - return getDataContext().getSelectedSetId(); - } - - @Override - public void afterSave(boolean refresh) { - super.afterSave(refresh); - } - - @Override - protected void doPersist(SetLonglineGlobalCompositionDto bean) { - // fait par le doSave de LonglineGlobalCompositionUIHandler - } - - @Override - protected void loadEditBean(String beanId) { - // fait par le loadEditBean de LonglineGlobalCompositionUIHandler - } -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/HooksCompositionUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/HooksCompositionUIModel.java deleted file mode 100644 index cc29463..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/HooksCompositionUIModel.java +++ /dev/null @@ -1,92 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import fr.ird.observe.services.dto.longline.HooksCompositionDto; -import fr.ird.observe.services.dto.longline.HooksCompositionDtos; -import fr.ird.observe.services.dto.longline.SetLonglineGlobalCompositionDto; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; - -import java.util.Collection; -import java.util.List; - -/** - * Created on 12/6/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.9 - */ -public class HooksCompositionUIModel extends ContentTableUIModel<SetLonglineGlobalCompositionDto, HooksCompositionDto> { - - private static final long serialVersionUID = 1L; - - public HooksCompositionUIModel(HooksCompositionUI ui) { - super(SetLonglineGlobalCompositionDto.class, - HooksCompositionDto.class, - new String[]{ - SetLonglineGlobalCompositionDto.PROPERTY_HOOKS_COMPOSITION - }, - new String[]{HooksCompositionDto.PROPERTY_HOOK_TYPE, - HooksCompositionDto.PROPERTY_HOOK_SIZE, - HooksCompositionDto.PROPERTY_HOOK_OFFSET, - HooksCompositionDto.PROPERTY_PROPORTION}); - - List<ContentTableMeta<HooksCompositionDto>> metas = Lists.newArrayList( - ContentTableModel.newTableMeta(HooksCompositionDto.class, HooksCompositionDto.PROPERTY_HOOK_TYPE, false), - ContentTableModel.newTableMeta(HooksCompositionDto.class, HooksCompositionDto.PROPERTY_HOOK_SIZE, false), - ContentTableModel.newTableMeta(HooksCompositionDto.class, HooksCompositionDto.PROPERTY_HOOK_OFFSET, false), - ContentTableModel.newTableMeta(HooksCompositionDto.class, HooksCompositionDto.PROPERTY_PROPORTION, false)); - - initModel(ui, metas); - - } - - - @Override - protected ContentTableModel<SetLonglineGlobalCompositionDto, HooksCompositionDto> createTableModel( - ObserveContentTableUI<SetLonglineGlobalCompositionDto, HooksCompositionDto> ui, - List<ContentTableMeta<HooksCompositionDto>> contentTableMetas) { - - return new ContentTableModel<SetLonglineGlobalCompositionDto, HooksCompositionDto>(ui, contentTableMetas) { - private static final long serialVersionUID = 1L; - @Override - protected Collection<HooksCompositionDto> getChilds(SetLonglineGlobalCompositionDto bean) { - return bean.getHooksComposition(); - } - - @Override - protected void load(HooksCompositionDto source, HooksCompositionDto target) { - HooksCompositionDtos.copyHooksCompositionDto(source, target); - } - - @Override - protected void setChilds(SetLonglineGlobalCompositionDto parent, List<HooksCompositionDto> childs) { - parent.setHooksComposition(childs); - } - }; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/LonglinePositionHelper.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/LonglinePositionHelper.java deleted file mode 100644 index 3f8ffc8..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/LonglinePositionHelper.java +++ /dev/null @@ -1,318 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.longline.BasketDto; -import fr.ird.observe.services.dto.longline.BranchlineDto; -import fr.ird.observe.services.dto.longline.CatchLonglineDto; -import fr.ird.observe.services.dto.longline.LonglinePositionAwareDto; -import fr.ird.observe.services.dto.longline.LonglinePositionSetDto; -import fr.ird.observe.services.dto.longline.SectionDto; -import jaxx.runtime.swing.editor.bean.BeanComboBox; - -import java.beans.PropertyChangeListener; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.stream.Collectors; - -/** - * Created on 1/6/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.11 - */ -public class LonglinePositionHelper<D extends LonglinePositionAwareDto> { - - protected final BeanComboBox<DataReference<SectionDto>> uiSection; - - protected final BeanComboBox<DataReference<BasketDto>> uiBasket; - - protected final BeanComboBox<DataReference<BranchlineDto>> uiBranchline; - - // To avoid any propagation when doing some works on locations - protected boolean locationIsAdjusting; - - protected Collection<DataReference<SectionDto>> sectionUniverse; - - protected Collection<DataReference<BasketDto>> basketUniverse; - - protected Collection<DataReference<BranchlineDto>> branchlineUniverse; - - public LonglinePositionHelper(BeanComboBox<DataReference<SectionDto>> uiSection, - BeanComboBox<DataReference<BasketDto>> uiBasket, - BeanComboBox<DataReference<BranchlineDto>> uiBranchline, - D tableEditBean) { - - this.uiSection = uiSection; - this.uiBasket = uiBasket; - this.uiBranchline = uiBranchline; - - PropertyChangeListener sectionChanged = evt -> onSectionChanged((DataReference<SectionDto>) evt.getNewValue(), (D) evt.getSource()); - tableEditBean.addPropertyChangeListener(CatchLonglineDto.PROPERTY_SECTION, sectionChanged); - - PropertyChangeListener basketChanged = evt -> onBasketChanged((DataReference<BasketDto>) evt.getNewValue(), (D) evt.getSource()); - tableEditBean.addPropertyChangeListener(CatchLonglineDto.PROPERTY_BASKET, basketChanged); - - } - - public void initSections(LonglinePositionSetDto positionSetDto, - Collection<D> dtos) { - - this.sectionUniverse = positionSetDto.getSections(); - this.basketUniverse = positionSetDto.getBaskets(); - this.branchlineUniverse = positionSetDto.getBranchlines(); - - for (D dto : dtos) { - - DataReference<BranchlineDto> branchline = dto.getBranchline(); - - if (branchline != null) { - - DataReference<BasketDto> basket = getBasket(branchline); - dto.setBasket(basket); - - } - - DataReference<BasketDto> basket = dto.getBasket(); - - if (basket != null) { - - DataReference<SectionDto> section = getSection(basket); - dto.setSection(section); - - } - } - } - - public void resetPosition(D dto) { - - DataReference<SectionDto> section = dto.getSection(); - DataReference<BasketDto> basket = dto.getBasket(); - DataReference<BranchlineDto> branchline = dto.getBranchline(); - - uiBranchline.setSelectedItem(null); - uiSection.setSelectedItem(null); - uiBasket.setSelectedItem(null); - - if (section != null) { - - // reload section (basket and branchlines universe will then changed) - uiSection.setSelectedItem(section); - - } - - if (basket != null) { - - // reload basket (branchlines universe will then changed) - uiBasket.setSelectedItem(basket); - - } - - if (branchline != null) { - - // reload branchline - uiBranchline.setSelectedItem(branchline); - - } - - } - - public void savePosition(List<D> dtos) { - - for (D dto : dtos) { - - if (dto.getBasket() != null) { - // remove section - dto.setSection(null); - } - - if (dto.getBranchline() != null) { - - // remove basket - dto.setBasket(null); - } - - } - - } - - public List<DataReference<SectionDto>> getSections() { - - List<DataReference<SectionDto>> sections = Lists.newArrayList(); - - if (sectionUniverse != null) { - - sections.addAll(sectionUniverse); - - } - - return sections; - } - - protected void onSectionChanged(DataReference<SectionDto> newValue, D dto) { - - locationIsAdjusting = true; - - try { - - DataReference<BasketDto> basket = dto.getBasket(); - DataReference<BranchlineDto> branchline = dto.getBranchline(); - - // on deselectionne le panier - dto.setBasket(null); - - // on deselectionne l'avançon - dto.setBranchline(null); - - // on vide l'ensemble des paniers - uiBasket.setData(Collections.emptyList()); - - // on vide l'ensemble des avançons - uiBranchline.setData(Collections.emptyList()); - - if (newValue != null) { - - // une section est sélectionnée - - // on remplit uniquement les paniers de cette section - List<DataReference<BasketDto>> baskets = getBaskets(newValue); - uiBasket.setData(Lists.newArrayList(baskets)); - - if (basket != null && baskets.contains(basket)) { - - // un panier est sélectionné - - // on repmlit uniquement les avançons du panier - List<DataReference<BranchlineDto>> branchlines = getBranchlines(basket); - uiBranchline.setData(Lists.newArrayList(branchlines)); - dto.setBasket(basket); - - if (branchline != null && branchlines.contains(branchline)) { - - // un avançon est sélectionné - dto.setBranchline(branchline); - - } - - } - - } - - } finally { - - locationIsAdjusting = false; - - } - - } - - protected void onBasketChanged(DataReference<BasketDto> newValue, D dto) { - - if (!locationIsAdjusting) { - - DataReference<BranchlineDto> branchline = dto.getBranchline(); - - // on deselectionne l'avançon - dto.setBranchline(null); - - // on vide l'ensemble des avançons - uiBranchline.setData(Collections.emptyList()); - - if (newValue != null) { - - // un panier est selectionne - - // on remplit uniquement les avançons des paniers - List<DataReference<BranchlineDto>> branchlines = getBranchlines(newValue); - uiBranchline.setData(branchlines); - - - if (branchline != null && branchlines.contains(branchline)) { - - // un avançon est sélectionné - dto.setBranchline(branchline); - - } - - } - - } - - } - - protected DataReference<SectionDto> getSection(DataReference<BasketDto> basket) { - - String sectionId = (String) basket.getPropertyValue(BasketDto.PROPERTY_SECTION); - - DataReference<SectionDto> section = sectionUniverse.stream() - // TODO sbavencoff 11/03/2016 utiliser le prédicat AbstractReference.newIdPredicate() - // A la migartion vers les prédicats JAVA8 - .filter(s -> sectionId.equals(s.getId())) - .findFirst() - .get(); - - return section; - - } - - protected DataReference<BasketDto> getBasket(DataReference<BranchlineDto> branchline) { - - String basketId = (String) branchline.getPropertyValue(BranchlineDto.PROPERTY_BASKET); - - DataReference<BasketDto> basket = basketUniverse.stream() - // TODO sbavencoff 11/03/2016 utiliser le prédicat DataReference.newLabelValuePredicate - // A la migartion vers les prédicats JAVA8 - .filter(b -> basketId.equals(b.getId())) - .findFirst() - .get(); - - return basket; - - } - - protected List<DataReference<BasketDto>> getBaskets(DataReference<SectionDto> section) { - - List<DataReference<BasketDto>> baskets = basketUniverse.stream() - // TODO sbavencoff 11/03/2016 utiliser le prédicat DataReference.newLabelValuePredicate - // A la migartion vers les prédicat JAVA8 - .filter(b -> section.getId().equals(b.getPropertyValue(BasketDto.PROPERTY_SECTION))) - .collect(Collectors.toList()); - - return baskets; - } - - protected List<DataReference<BranchlineDto>> getBranchlines(DataReference<BasketDto> basket) { - - List<DataReference<BranchlineDto>> branchlines = branchlineUniverse.stream() - // TODO sbavencoff 11/03/2016 utilise le prédicat DataReference.newLabelValuePredicate - // A la migartion vers les prédicat JAVA8 - .filter(b -> basket.getId().equals(b.getPropertyValue(BranchlineDto.PROPERTY_BASKET))) - .collect(Collectors.toList()); - - return branchlines; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/SensorUsedUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/SensorUsedUI.jaxx deleted file mode 100644 index ce77895..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/SensorUsedUI.jaxx +++ /dev/null @@ -1,163 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.table.ContentTableUI - superGenericType='ActivityLonglineSensorUsedDto, SensorUsedDto' - contentTitle='{n("observe.content.sensorUsed.title")}' - saveNewEntryText='{n("observe.content.sensorUsed.action.create")}' - saveNewEntryTip='{n("observe.content.sensorUsed.action.create.tip")}'> - - <style source="../../CommonTable.jcss"/> - - <import> - fr.ird.observe.services.dto.CommentableDto - fr.ird.observe.services.dto.longline.ActivityLonglineSensorUsedDto - fr.ird.observe.services.dto.longline.SensorUsedDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.longline.SensorTypeDto - fr.ird.observe.services.dto.referential.longline.SensorBrandDto - fr.ird.observe.services.dto.referential.longline.SensorDataFormatDto - fr.ird.observe.ui.content.table.* - - jaxx.runtime.swing.editor.bean.BeanComboBox - - java.awt.Dimension - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <SensorUsedUIHandler id='handler'/> - - <!-- model --> - <SensorUsedUIModel id='model'/> - - <!-- edit bean --> - <ActivityLonglineSensorUsedDto id='bean'/> - - <!-- table edit bean --> - <SensorUsedDto id='tableEditBean'/> - - <!-- table model --> - <ContentTableModel id='tableModel'/> - - <!-- le validateur de l'écran --> - <BeanValidator id='validator' autoField='true' context='ui-update' - beanClass='fr.ird.observe.services.dto.longline.ActivityLonglineSensorUsedDto' - errorTableModel='{getErrorTableModel()}'/> - - <!-- le validateur d'une entrée de tableau --> - <BeanValidator id='validatorTable' autoField='true' context='ui-update' - beanClass='fr.ird.observe.services.dto.longline.SensorUsedDto' - errorTableModel='{getErrorTableModel()}'/> - - <Table id='editorPanel' fill='both' insets='1'> - - <!-- sensorType --> - <row> - <cell> - <JLabel id='sensorTypeLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='sensorType' constructorParams='this' genericType='ReferentialReference<SensorTypeDto>' _entityClass='SensorTypeDto.class'/> - </cell> - </row> - - <!-- sensorDataFormat --> - <row> - <cell> - <JLabel id='sensorDataFormatLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='sensorDataFormat' constructorParams='this' genericType='ReferentialReference<SensorDataFormatDto>' _entityClass='SensorDataFormatDto.class'/> - </cell> - </row> - - <!-- sensorBrand --> - <row> - <cell> - <JLabel id='sensorBrandLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='sensorBrand' constructorParams='this' genericType='ReferentialReference<SensorBrandDto>' _entityClass='SensorBrandDto.class'/> - </cell> - </row> - - <!-- sensorSerialNo --> - <row> - <cell> - <JLabel id='sensorSerialNoLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <JPanel layout='{new BorderLayout()}'> - <JToolBar id='sensorSerialNoToolbar' constraints='BorderLayout.WEST'> - <JButton id='resetSensorSerialNo' styleClass='resetButton'/> - </JToolBar> - <JTextField id='sensorSerialNo' constraints='BorderLayout.CENTER'/> - </JPanel> - </cell> - </row> - - <!-- dataLocation --> - <row> - <cell> - <JLabel id='dataLocationLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <JPanel layout='{new BorderLayout()}'> - <JToolBar id='dataLocationToolbar' constraints='BorderLayout.WEST'> - <JButton id='resetDataLocation' styleClass='resetButton'/> - </JToolBar> - <JTextField id='dataLocation' constraints='BorderLayout.CENTER'/> - </JPanel> - </cell> - </row> - - <!-- data --> - <row> - <cell> - <JLabel id='dataLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <JPanel layout='{new GridLayout()}'> - <JButton id="importDataButton" onActionPerformed="getHandler().importData()"/> - <JButton id="exportDataButton" onActionPerformed="getHandler().exportData()"/> - <JButton id="deleteDataButton" onActionPerformed="getHandler().deleteData()"/> - </JPanel> - </cell> - </row> - </Table> - - <Table id='extraZone' fill='both' weightx='1' insets='1'> - <row> - <cell weighty='1'> - <JScrollPane id='comment' - onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2' - onKeyReleased='getBean().setComment(comment2.getText())'/> - </JScrollPane> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/SensorUsedUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/SensorUsedUIHandler.java deleted file mode 100644 index 28e1cd8..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/SensorUsedUIHandler.java +++ /dev/null @@ -1,220 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.ObserveSwingTechnicalException; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.DataFileDto; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.longline.ActivityLonglineSensorUsedDto; -import fr.ird.observe.services.dto.longline.ActivityLonglineSensorUsedDtos; -import fr.ird.observe.services.dto.longline.SensorUsedDto; -import fr.ird.observe.services.dto.referential.longline.SensorBrandDto; -import fr.ird.observe.services.dto.referential.longline.SensorDataFormatDto; -import fr.ird.observe.services.dto.referential.longline.SensorTypeDto; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.service.longline.ActivityLongLineSensorUsedService; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.table.ContentTableUIHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.jaxx.runtime.JaxxFileChooser; - -import javax.swing.JOptionPane; -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; -import java.awt.Component; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 8/31/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class SensorUsedUIHandler extends ContentTableUIHandler<ActivityLonglineSensorUsedDto, SensorUsedDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(SensorUsedUIHandler.class); - - public SensorUsedUIHandler(SensorUsedUI ui) { - super(ui, DataContextType.ActivityLongline); - } - - @Override - public SensorUsedUI getUi() { - return (SensorUsedUI) super.getUi(); - } - - @Override - protected void onSelectedRowChanged(int editingRow, SensorUsedDto bean, boolean create) { - if (getTableModel().isEditable()) { - if (log.isDebugEnabled()) { - log.debug("Row has changed to " + editingRow); - } - getUi().getSensorType().requestFocus(); - } - } - - @Override - protected void initTableUI(DefaultTableCellRenderer renderer) { - JTable table = getUi().getTable(); - - UIHelper.setI18nTableHeaderRenderer(table, - n("observe.content.sensorUsed.table.sensorType"), - n("observe.content.sensorUsed.table.sensorType.tip"), - n("observe.content.sensorUsed.table.sensorBrand"), - n("observe.content.sensorUsed.table.sensorBrand.tip"), - n("observe.content.sensorUsed.table.sensorDataFormat"), - n("observe.content.sensorUsed.table.sensorDataFormat.tip"), - n("observe.content.sensorUsed.table.sensorSerialNo"), - n("observe.content.sensorUsed.table.sensorSerialNo.tip"), - n("observe.content.sensorUsed.table.data"), - n("observe.content.sensorUsed.table.data.tip"), - n("observe.content.sensorUsed.table.dataLocation"), - n("observe.content.sensorUsed.table.dataLocation.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SensorTypeDto.class)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SensorBrandDto.class)); - UIHelper.setTableColumnRenderer(table, 2, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SensorDataFormatDto.class)); - UIHelper.setTableColumnRenderer(table, 3, UIHelper.newStringTableCellRenderer(renderer, 10, true)); - UIHelper.setTableColumnRenderer(table, 4, UIHelper.newBooleanTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 5, UIHelper.newStringTableCellRenderer(renderer, 10, true)); - } - - @Override - protected String getEditBeanIdToLoad() { - return getDataContext().getSelectedActivityId(); - } - - public void importData() { - - File file = UIHelper.chooseFile((Component) ui, - t("observe.content.choose.sensorUsed.title.importData"), - t("observe.action.choose.sensorUsed.importData"), - null); - - if (file != null) { - - if (log.isInfoEnabled()) { - log.info("Set data from file: " + file); - } - - DataFileDto dataFileDto = UIHelper.fileToDataFileDto(file); - getTableEditBean().setData(dataFileDto); - getTableEditBean().setHasData(true); - - } - - } - - public void deleteData() { - - int response = UIHelper.askUser((Component) ui, - t("observe.title.delete"), - t("observe.content.sensorUsed.delete.data.message"), - JOptionPane.WARNING_MESSAGE, - new Object[]{t("observe.choice.confirm.delete"), - t("observe.choice.cancel")}, - 1); - - boolean doDelete = response == 0; - - if (doDelete) { - - if (log.isInfoEnabled()) { - log.info("Delete sensorUsed data " + getTableEditBean().getData()); - } - getTableEditBean().setData(null); - getTableEditBean().setHasData(false); - - } - - } - - public void exportData() { - - DataFileDto dataFile = getTableEditBean().getData(); - - if (dataFile == null) { - dataFile = getActivityLonglineSensorUsedService().getDataFile(getTableEditBean().getId()); - } - - - File file = JaxxFileChooser - .forSaving() - .setParent(getUi()) - .setTitle(t("observe.content.choose.sensorUsed.title.exportData")) - .setApprovalText(t("observe.action.choose.sensorUsed.exportData")) - .setFilename(dataFile.getName()) - .setUseAcceptAllFileFilter(true) - .choose(); - - if (file != null && UIHelper.confirmOverwriteFileIfExist(getUi(), file)) { - - if (log.isInfoEnabled()) { - log.info("save sensorUsed data to " + file); - } - - try { - - Files.write(file.toPath(), dataFile.getContent()); - - ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); - mainUI.getStatus().setStatus(t("observe.content.sensorUsed.message.data.exported", file)); - } catch (IOException e) { - throw new ObserveSwingTechnicalException("Could not save binary data to " + file, e); - } - - } - - } - - @Override - protected void doPersist(ActivityLonglineSensorUsedDto bean) { - - SaveResultDto saveResult= getActivityLonglineSensorUsedService().save(bean); - saveResult.toDto(bean); - - } - - @Override - protected void loadEditBean(String beanId) { - Form<ActivityLonglineSensorUsedDto> form = getActivityLonglineSensorUsedService().loadForm(beanId); - loadReferentialReferenceSetsInModel(form); - getModel().setForm(form); - ActivityLonglineSensorUsedDtos.copyActivityLonglineSensorUsedDto(form.getObject(), getBean()); - } - - protected ActivityLongLineSensorUsedService getActivityLonglineSensorUsedService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivityLongLineSensorUsedService(); - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/SensorUsedUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/SensorUsedUIModel.java deleted file mode 100644 index ebcd761..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/SensorUsedUIModel.java +++ /dev/null @@ -1,96 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import fr.ird.observe.services.dto.longline.ActivityLonglineSensorUsedDto; -import fr.ird.observe.services.dto.longline.SensorUsedDto; -import fr.ird.observe.services.dto.longline.SensorUsedDtos; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; - -import java.util.Collection; -import java.util.List; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class SensorUsedUIModel extends ContentTableUIModel<ActivityLonglineSensorUsedDto, SensorUsedDto> { - - private static final long serialVersionUID = 1L; - - public SensorUsedUIModel(SensorUsedUI ui) { - - super(ActivityLonglineSensorUsedDto.class, - SensorUsedDto.class, - new String[]{ - ActivityLonglineSensorUsedDto.PROPERTY_SENSOR_USED, - ActivityLonglineSensorUsedDto.PROPERTY_COMMENT}, - new String[]{SensorUsedDto.PROPERTY_HAS_DATA, - SensorUsedDto.PROPERTY_DATA, - SensorUsedDto.PROPERTY_SENSOR_SERIAL_NO, - SensorUsedDto.PROPERTY_SENSOR_TYPE, - SensorUsedDto.PROPERTY_SENSOR_BRAND, - SensorUsedDto.PROPERTY_SENSOR_DATA_FORMAT}); - - List<ContentTableMeta<SensorUsedDto>> metas = Lists.newArrayList( - ContentTableModel.newTableMeta(SensorUsedDto.class, SensorUsedDto.PROPERTY_SENSOR_TYPE, false), - ContentTableModel.newTableMeta(SensorUsedDto.class, SensorUsedDto.PROPERTY_SENSOR_BRAND, false), - ContentTableModel.newTableMeta(SensorUsedDto.class, SensorUsedDto.PROPERTY_SENSOR_DATA_FORMAT, false), - ContentTableModel.newTableMeta(SensorUsedDto.class, SensorUsedDto.PROPERTY_SENSOR_SERIAL_NO, false), - ContentTableModel.newTableMeta(SensorUsedDto.class, SensorUsedDto.PROPERTY_HAS_DATA, false), - ContentTableModel.newTableMeta(SensorUsedDto.class, SensorUsedDto.PROPERTY_DATA_LOCATION, false)); - - initModel(ui, metas); - - } - - @Override - protected ContentTableModel<ActivityLonglineSensorUsedDto, SensorUsedDto> createTableModel( - ObserveContentTableUI<ActivityLonglineSensorUsedDto, SensorUsedDto> ui, - List<ContentTableMeta<SensorUsedDto>> contentTableMetas) { - - return new ContentTableModel<ActivityLonglineSensorUsedDto, SensorUsedDto>(ui, contentTableMetas) { - private static final long serialVersionUID = 1L; - @Override - protected Collection<SensorUsedDto> getChilds(ActivityLonglineSensorUsedDto bean) { - return bean.getSensorUsed(); - } - - @Override - protected void load(SensorUsedDto source, SensorUsedDto target) { - SensorUsedDtos.copySensorUsedDto(source, target); - } - - @Override - protected void setChilds(ActivityLonglineSensorUsedDto parent, List<SensorUsedDto> childs) { - parent.setSensorUsed(childs); - } - }; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/SizeMeasuresTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/SizeMeasuresTableModel.java deleted file mode 100644 index 5ece237..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/SizeMeasuresTableModel.java +++ /dev/null @@ -1,104 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.longline.SizeMeasureDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.longline.SizeMeasureTypeDto; -import fr.ird.observe.ui.util.table.EditableTableWithCacheTableModelSupport; - -/** - * Created on 12/3/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.8 - */ -public class SizeMeasuresTableModel extends EditableTableWithCacheTableModelSupport<SizeMeasureDto> { - - private static final long serialVersionUID = 1L; - - public SizeMeasuresTableModel() { - super(); - } - - @Override - public boolean isRowNotEmpty(SizeMeasureDto valid) { - return !(valid.getSizeMeasureType() == null && valid.getSize() == null); - } - - @Override - protected boolean isRowValid(SizeMeasureDto valid) { - Float size = valid.getSize(); - return !(valid.getSizeMeasureType() == null || size == null) && size > 0 && size < 1000; - } - - @Override - public int getColumnCount() { - return 2; - } - - @Override - public Object getValueAt(int rowIndex, int columnIndex) { - - SizeMeasureDto measure = data.get(rowIndex); - Object result; - switch (columnIndex) { - case 0: - result = measure.getSizeMeasureType(); - break; - case 1: - result = measure.getSize(); - break; - default: - throw new IllegalStateException("Can't come here"); - } - return result; - } - - @Override - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - - SizeMeasureDto measure = data.get(rowIndex); - switch (columnIndex) { - case 0: - measure.setSizeMeasureType((ReferentialReference<SizeMeasureTypeDto>) aValue); - break; - - case 1: - measure.setSize((Float) aValue); - break; - - default: - throw new IllegalStateException("Can't come here"); - } - - setModified(true); - - } - - @Override - protected SizeMeasureDto createNewRow() { - return new SizeMeasureDto(); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/TdrUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/TdrUI.jaxx deleted file mode 100644 index 4f8ba38..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/TdrUI.jaxx +++ /dev/null @@ -1,396 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2014 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.table.ContentTableUI superGenericType='SetLonglineTdrDto, TdrDto' - contentTitle='{n("observe.content.tdr.title")}' - saveNewEntryText='{n("observe.content.tdr.action.create")}' - saveNewEntryTip='{n("observe.content.tdr.action.create.tip")}'> - - <style source="../../CommonTable.jcss"/> - - <import> - fr.ird.observe.services.dto.DataReference - fr.ird.observe.services.dto.longline.BasketDto - fr.ird.observe.services.dto.longline.BranchlineDto - fr.ird.observe.services.dto.longline.TdrDto - fr.ird.observe.services.dto.longline.SectionDto - fr.ird.observe.services.dto.longline.SetLonglineTdrDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.SpeciesDto - fr.ird.observe.services.dto.referential.longline.ItemHorizontalPositionDto - fr.ird.observe.services.dto.referential.longline.ItemVerticalPositionDto - fr.ird.observe.services.dto.referential.longline.SensorBrandDto - fr.ird.observe.ui.content.table.* - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - org.nuiton.jaxx.widgets.select.FilterableDoubleList - - org.nuiton.jaxx.widgets.datetime.DateTimeEditor - - java.util.Collection - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <TdrUIHandler id='handler'/> - - <!-- model --> - <TdrUIModel id='model'/> - - <!-- edit bean --> - <SetLonglineTdrDto id='bean'/> - - <!-- table edit bean --> - <TdrDto id='tableEditBean'/> - - <!-- table model --> - <ContentTableModel id='tableModel'/> - - <!-- le validateur de l'écran --> - <BeanValidator id='validator' context='ui-update-tdr' - beanClass='fr.ird.observe.services.dto.longline.SetLonglineTdrDto' - errorTableModel='{getErrorTableModel()}'> - </BeanValidator> - - <!-- le validateur d'une entrée de tableau --> - <BeanValidator id='validatorTable' autoField='true' context='ui-update' - beanClass='fr.ird.observe.services.dto.longline.TdrDto' - errorTableModel='{getErrorTableModel()}' - parentValidator='{validator}'/> - - <Table id='editorPanel' fill='both' insets='0'> - <row> - <cell weightx="1" weighty="1"> - <JTabbedPane id='editTabPane'> - - <tab id='caracteristicsTab'> - - <JPanel layout='{new BorderLayout()}'> - <Table fill='both' constraints='BorderLayout.NORTH' insets="0"> - - <!-- homeId --> - <row> - <cell anchor='west'> - <JLabel id='homeIdLabel'/> - </cell> - <cell fill='both' weightx='1'> - <JPanel layout='{new BorderLayout()}'> - <JToolBar id='homeIdToolbar' constraints='BorderLayout.WEST'> - <JButton id='resetHomeId' styleClass='resetButton'/> - </JToolBar> - <JTextField id='homeId' constraints='BorderLayout.CENTER'/> - </JPanel> - </cell> - </row> - - <!-- serialNo --> - <row> - <cell anchor='west'> - <JLabel id='serialNoLabel'/> - </cell> - <cell fill='both' weightx='1'> - <JPanel layout='{new BorderLayout()}'> - <JToolBar id='serialNoToolbar' constraints='BorderLayout.WEST'> - <JButton id='resetSerialNo' styleClass='resetButton'/> - </JToolBar> - <JTextField id='serialNo' constraints='BorderLayout.CENTER'/> - </JPanel> - </cell> - </row> - - <!-- sensorBrand --> - <row> - <cell> - <JLabel id='sensorBrandLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='sensorBrand' constructorParams='this' genericType='ReferentialReference<SensorBrandDto>' _entityClass='SensorBrandDto.class'/> - </cell> - </row> - - <!-- dataLocation --> - <row> - <cell> - <JLabel id='dataLocationLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <JPanel layout='{new BorderLayout()}'> - <JToolBar id='dataLocationToolbar' constraints='BorderLayout.WEST'> - <JButton id='resetDataLocation' styleClass='resetButton'/> - </JToolBar> - <JTextField id='dataLocation' constraints='BorderLayout.CENTER'/> - </JPanel> - </cell> - </row> - - <!-- data --> - <row> - <cell> - <JLabel id='dataLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <JPanel layout='{new GridLayout()}'> - <JButton id="importDataButton" onActionPerformed="getHandler().importData()"/> - <JButton id="exportDataButton" onActionPerformed="getHandler().exportData()"/> - <JButton id="deleteDataButton" onActionPerformed="getHandler().deleteData()"/> - </JPanel> - </cell> - </row> - - </Table> - </JPanel> - - </tab> - - <tab id='localisationTab'> - - <JPanel layout='{new BorderLayout()}'> - <Table fill='both' constraints='BorderLayout.NORTH' insets="0"> - - <!-- location on longline --> - <row> - <cell columns="2"> - <Table id="locationOnLonglinePanel"> - <row> - <cell anchor="west"> - <JLabel id='sectionLabel'/> - </cell> - <cell fill="both" weightx="1"> - <BeanComboBox id='section' genericType='DataReference<SectionDto>' _entityClass='SectionDto.class' constructorParams='this'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='basketLabel'/> - </cell> - <cell fill="both" weightx="1"> - <BeanComboBox id='basket' genericType='DataReference<BasketDto>' _entityClass='BasketDto.class' constructorParams='this'/> - </cell> - </row> - <row> - <cell anchor="west"> - <JLabel id='branchlineLabel'/> - </cell> - <cell fill="both" weightx="1"> - <BeanComboBox id='branchline' genericType='DataReference<BranchlineDto>' _entityClass='BranchlineDto.class' constructorParams='this'/> - </cell> - </row> - </Table> - </cell> - </row> - - <!-- itemHorizontalPosition --> - <row> - <cell> - <JLabel id='itemHorizontalPositionLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='itemHorizontalPosition' constructorParams='this' - genericType='ReferentialReference<ItemHorizontalPositionDto>' _entityClass='ItemHorizontalPositionDto.class'/> - </cell> - </row> - - <!-- itemVerticalPosition --> - <row> - <cell> - <JLabel id='itemVerticalPositionLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='itemVerticalPosition' constructorParams='this' - genericType='ReferentialReference<ItemVerticalPositionDto>' _entityClass='ItemVerticalPositionDto.class'/> - </cell> - </row> - - <!-- floatline1Length --> - <row> - <cell> - <JLabel id='floatline1LengthLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='floatline1Length' constructorParams='this' styleClass='float'/> - </cell> - </row> - - <!-- floatline2Length --> - <row> - <cell> - <JLabel id='floatline2LengthLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='floatline2Length' constructorParams='this' styleClass='float'/> - </cell> - </row> - - </Table> - </JPanel> - - </tab> - - <tab id='timestampTab'> - - <JPanel layout='{new BorderLayout()}'> - <JPanel layout='{new BorderLayout()}' constraints='BorderLayout.NORTH'> - - <JCheckBox id='enableTimestamp' constraints='BorderLayout.NORTH' - onMouseClicked='getHandler().changeEnableTimestamp(enableTimestamp.isSelected())'/> - - <Table id='timestampPanel' fill='both' constraints='BorderLayout.CENTER' insets="0"> - - <!-- deployementStart --> - <row> - <cell weightx="1" fill="both"> - <DateTimeEditor id='deployementStart' constructorParams='this'/> - </cell> - </row> - <!-- fishingStart --> - <row> - <cell> - <DateTimeEditor id='fishingStart' constructorParams='this'/> - </cell> - </row> - <!-- fishingEnd --> - <row> - <cell> - <DateTimeEditor id='fishingEnd' constructorParams='this'/> - </cell> - </row> - <!-- deployementEnd --> - <row> - <cell> - <DateTimeEditor id='deployementEnd' constructorParams='this'/> - </cell> - </row> - </Table> - </JPanel> - - </JPanel> - </tab> - - <tab id='keyDataTab'> - - <JPanel layout='{new BorderLayout()}'> - <Table fill='both' constraints='BorderLayout.NORTH'> - - <!-- fishingStartDepth --> - <row> - <cell> - <JLabel id='fishingStartDepthLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='fishingStartDepth' constructorParams='this' styleClass='float2'/> - </cell> - </row> - <!-- fishingEndDepth --> - <row> - <cell> - <JLabel id='fishingEndDepthLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='fishingEndDepth' constructorParams='this' styleClass='float2'/> - </cell> - </row> - <!-- minFishingDepth --> - <row> - <cell> - <JLabel id='minFishingDepthLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='minFishingDepth' constructorParams='this' styleClass='float2'/> - </cell> - </row> - <!-- maxFishingDepth --> - <row> - <cell> - <JLabel id='maxFishingDepthLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='maxFishingDepth' constructorParams='this' styleClass='float2'/> - </cell> - </row> - <!-- meanFishingDepth --> - <row> - <cell> - <JLabel id='meanFishingDepthLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='meanFishingDepth' constructorParams='this' styleClass='float2'/> - </cell> - </row> - <!-- medianFishingDepth --> - <row> - <cell> - <JLabel id='medianFishingDepthLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='medianFishingDepth' constructorParams='this' styleClass='float2'/> - </cell> - </row> - <!-- meanDeployementDepth --> - <row> - <cell> - <JLabel id='meanDeployementDepthLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='meanDeployementDepth' constructorParams='this' styleClass='float2'/> - </cell> - </row> - <!-- medianDeployementDepth --> - <row> - <cell> - <JLabel id='medianDeployementDepthLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='medianDeployementDepth' constructorParams='this' styleClass='float2'/> - </cell> - </row> - </Table> - - </JPanel> - - </tab> - - <tab id='speciesTab'> - - <!-- species --> - <JPanel layout='{new BorderLayout()}'> - <Table fill='both' constraints='BorderLayout.NORTH'> - <row> - <cell weighty="1" weightx="1"> - <FilterableDoubleList id='species' - genericType='ReferentialReference<SpeciesDto>' - _entityClass='SpeciesDto.class'/> - </cell> - </row> - </Table> - </JPanel> - - </tab> - - </JTabbedPane> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/TdrUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/TdrUI.jcss deleted file mode 100644 index 25ce7cc..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/TdrUI.jcss +++ /dev/null @@ -1,370 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -/* ***************************************************************************** */ -/* CARACTERISTICS TAB ********************************************************* */ -/* ***************************************************************************** */ - -#caracteristicsTab { - title:{t("observe.content.tdr.tab.caracteristics")}; - icon:{handler.getErrorIconIfFalse(model.isCaracteristicsTabValid())}; -} - -#homeIdLabel { - text:"observe.content.tdr.homeId"; - labelFor:{homeId}; -} - -#homeId { - text: {getStringValue(tableEditBean.getHomeId())}; - _tablePropertyName: {TdrDto.PROPERTY_HOME_ID}; -} - -#resetHomeId { - toolTipText:"observe.content.tdr.action.reset.homeId.tip"; - _resetTablePropertyName: {TdrDto.PROPERTY_HOME_ID}; -} - -#serialNoLabel { - text:"observe.content.tdr.serialNo"; - labelFor:{serialNo}; -} - -#serialNo { - text: {getStringValue(tableEditBean.getSerialNo())}; - _tablePropertyName: {TdrDto.PROPERTY_SERIAL_NO}; -} - -#resetSerialNo { - toolTipText:"observe.content.tdr.action.reset.serialNo.tip"; - _resetTablePropertyName: {TdrDto.PROPERTY_SERIAL_NO}; -} - - -#sensorBrandLabel { - text:"observe.content.tdr.sensorBrand"; - labelFor:{sensorBrand}; -} - -#sensorBrand { - property:{TdrDto.PROPERTY_SENSOR_BRAND}; - selectedItem:{tableEditBean.getSensorBrand()}; -} - -#dataLocationLabel { - text:"observe.content.tdr.dataLocation"; - toolTipText:"observe.content.tdr.dataLocation.tip"; - labelFor:{dataLocation}; -} - -#dataLocation { - _tablePropertyName:{TdrDto.PROPERTY_DATA_LOCATION}; - text:{tableEditBean.getDataLocation()}; -} - -#resetDataLocation { - toolTipText:"observe.content.tdr.action.reset.dataLocation.tip"; - _resetTablePropertyName: {TdrDto.PROPERTY_DATA_LOCATION}; - focusable:false; -} - -#dataLabel { - text:"observe.content.tdr.data"; -} - -#importDataButton { - actionIcon:data-import; - text:"observe.content.tdr.importData"; - toolTipText:"observe.content.tdr.importData.tip"; - enabled:{! tableEditBean.isHasData()}; -} - -#exportDataButton { - actionIcon:data-export; - text:"observe.content.tdr.exportData"; - toolTipText:"observe.content.tdr.exportData.tip"; - enabled:{tableEditBean.isHasData()}; -} - -#deleteDataButton { - actionIcon:delete; - text:"observe.content.tdr.deleteData"; - toolTipText:"observe.content.tdr.deleteData.tip"; - enabled:{tableEditBean.isHasData()}; -} - -/* ***************************************************************************** */ -/* LOCALISATION TAB *********************************************************** */ -/* ***************************************************************************** */ - -#localisationTab { - title:{t("observe.content.tdr.tab.localisation")}; - icon:{handler.getErrorIconIfFalse(model.isLocalisationTabValid())}; -} - -#locationOnLonglinePanel { - border:{new TitledBorder(t("observe.content.tdr.locationOnLongline"))}; -} - -#sectionLabel { - text:"observe.content.tdr.section"; - labelFor:{section}; -} - -#section { - property:{TdrDto.PROPERTY_SECTION}; - selectedItem:{tableEditBean.getSection()}; - _listNoLoad:{true}; - _validatorLabel: {t("observe.content.tdr.section")}; -} - -#basketLabel { - text:"observe.content.tdr.basket"; - labelFor:{basket}; -} - -#basket { - property:{TdrDto.PROPERTY_BASKET}; - selectedItem:{tableEditBean.getBasket()}; - _listNoLoad:{true}; - _validatorLabel: {t("observe.content.tdr.basket")}; -} - -#branchlineLabel { - text:"observe.content.tdr.branchline"; - labelFor:{branchline}; -} - -#branchline { - property:{TdrDto.PROPERTY_BRANCHLINE}; - selectedItem:{tableEditBean.getBranchline()}; - _listNoLoad:{true}; - _validatorLabel: {t("observe.content.tdr.branchline")}; -} - -#itemHorizontalPositionLabel { - text:"observe.content.tdr.itemHorizontalPosition"; - labelFor:{itemHorizontalPosition}; -} - -#itemHorizontalPosition { - property:{TdrDto.PROPERTY_ITEM_HORIZONTAL_POSITION}; - selectedItem:{tableEditBean.getItemHorizontalPosition()}; - _validatorLabel: {t("observe.content.tdr.itemHorizontalPosition")}; -} - -#itemVerticalPositionLabel { - text:"observe.content.tdr.itemVerticalPosition"; - labelFor:{itemVerticalPosition}; -} - -#itemVerticalPosition { - property:{TdrDto.PROPERTY_ITEM_VERTICAL_POSITION}; - selectedItem:{tableEditBean.getItemVerticalPosition()}; - _validatorLabel: {t("observe.content.tdr.itemVerticalPosition")}; -} - -#floatline1LengthLabel { - text:"observe.content.tdr.floatline1Length"; - labelFor:{floatline1Length}; -} - -#floatline1Length { - property:{TdrDto.PROPERTY_FLOATLINE1_LENGTH}; - model:{tableEditBean.getFloatline1Length()}; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL3_PATTERN}; - _validatorLabel: {t("observe.content.tdr.floatline1Length")}; -} - -#floatline2LengthLabel { - text:"observe.content.tdr.floatline2Length"; - labelFor:{floatline2Length}; -} - -#floatline2Length { - property:{TdrDto.PROPERTY_FLOATLINE2_LENGTH}; - model:{tableEditBean.getFloatline2Length()}; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL3_PATTERN}; - _validatorLabel: {t("observe.content.tdr.floatline2Length")}; -} - - -/* ***************************************************************************** */ -/* TIMESTAMP TAB ************************************************************** */ -/* ***************************************************************************** */ - -#timestampTab { - title:{t("observe.content.tdr.tab.timestamp")}; - icon:{handler.getErrorIconIfFalse(model.isTimestampTabValid())}; -} - -#enableTimestamp { - text:"observe.content.tdr.enableTimestamp"; - toolTipText:"observe.content.tdr.enableTimestamp.tip"; -} - -#timestampPanel { - visible:{enableTimestamp.isSelected()}; -} - -#deployementStart { - label:{t("observe.content.tdr.deployementStart")}; - date:{tableEditBean.getDeployementStart()}; - propertyDate: {TdrDto.PROPERTY_DEPLOYEMENT_START}; - _validatorLabel: {t("observe.content.tdr.deployementStart")}; -} - -#deployementEnd { - label:{t("observe.content.tdr.deployementEnd")}; - date:{tableEditBean.getDeployementEnd()}; - propertyDate: {TdrDto.PROPERTY_DEPLOYEMENT_END}; - _validatorLabel: {t("observe.content.tdr.deployementEnd")}; -} - -#fishingStart { - label:{t("observe.content.tdr.fishingStart")}; - date:{tableEditBean.getFishingStart()}; - propertyDate: {TdrDto.PROPERTY_FISHING_START}; - _validatorLabel: {t("observe.content.tdr.fishingStart")}; -} - -#fishingEnd { - label:{t("observe.content.tdr.fishingEnd")}; - date:{tableEditBean.getFishingEnd()}; - propertyDate: {TdrDto.PROPERTY_FISHING_END}; - _validatorLabel: {t("observe.content.tdr.fishingEnd")}; -} - -/* ***************************************************************************** */ -/* KEY DATA TAB *************************************************************** */ -/* ***************************************************************************** */ - -#keyDataTab { - title:{t("observe.content.tdr.tab.keyData")}; - icon:{handler.getErrorIconIfFalse(model.isKeyDataTabValid())}; -} - -#fishingStartDepthLabel { - text:"observe.content.tdr.fishingStartDepth"; - labelFor:{fishingStartDepth}; -} - -#fishingStartDepth { - property:{TdrDto.PROPERTY_FISHING_START_DEPTH}; - model:{tableEditBean.getFishingStartDepth()}; - _validatorLabel: {t("observe.content.tdr.fishingStartDepth")}; -} - -#fishingEndDepthLabel { - text:"observe.content.tdr.fishingEndDepth"; - labelFor:{fishingEndDepth}; -} - -#fishingEndDepth { - property:{TdrDto.PROPERTY_FISHING_END_DEPTH}; - model:{tableEditBean.getFishingEndDepth()}; - _validatorLabel: {t("observe.content.tdr.fishingEndDepth")}; -} - -#meanDeployementDepthLabel { - text:"observe.content.tdr.meanDeployementDepth"; - labelFor:{meanDeployementDepth}; -} - -#meanDeployementDepth { - property:{TdrDto.PROPERTY_MEAN_DEPLOYEMENT_DEPTH}; - model:{tableEditBean.getMeanDeployementDepth()}; - _validatorLabel: {t("observe.content.tdr.meanDeployementDepth")}; -} - -#medianDeployementDepthLabel { - text:"observe.content.tdr.medianDeployementDepth"; - labelFor:{medianDeployementDepth}; -} - -#medianDeployementDepth { - property:{TdrDto.PROPERTY_MEDIAN_DEPLOYEMENT_DEPTH}; - model:{tableEditBean.getMedianDeployementDepth()}; - _validatorLabel: {t("observe.content.tdr.medianDeployementDepth")}; -} - -#minFishingDepthLabel { - text:"observe.content.tdr.minFishingDepth"; - labelFor:{minFishingDepth}; -} - -#minFishingDepth { - property:{TdrDto.PROPERTY_MIN_FISHING_DEPTH}; - model:{tableEditBean.getMinFishingDepth()}; - _validatorLabel: {t("observe.content.tdr.minFishingDepth")}; -} - -#maxFishingDepthLabel { - text:"observe.content.tdr.maxFishingDepth"; - labelFor:{maxFishingDepth}; -} - -#maxFishingDepth { - property:{TdrDto.PROPERTY_MAX_FISHING_DEPTH}; - model:{tableEditBean.getMaxFishingDepth()}; - _validatorLabel: {t("observe.content.tdr.maxFishingDepth")}; -} - -#meanFishingDepthLabel { - text:"observe.content.tdr.meanFishingDepth"; - labelFor:{meanFishingDepth}; -} - -#meanFishingDepth { - property:{TdrDto.PROPERTY_MEAN_FISHING_DEPTH}; - model:{tableEditBean.getMeanFishingDepth()}; - _validatorLabel: {t("observe.content.tdr.meanFishingDepth")}; -} - -#medianFishingDepthLabel { - text:"observe.content.tdr.medianFishingDepth"; - labelFor:{medianFishingDepth}; -} - -#medianFishingDepth { - property:{TdrDto.PROPERTY_MEDIAN_FISHING_DEPTH}; - model:{tableEditBean.getMedianFishingDepth()}; - _validatorLabel: {t("observe.content.tdr.medianFishingDepth")}; -} - -/* ***************************************************************************** */ -/* SPECIES TAB **************************************************************** */ -/* ***************************************************************************** */ - -#speciesTab { - title:{t("observe.content.tdr.tab.species")}; - icon:{handler.getErrorIconIfFalse(model.isSpeciesTabValid())}; -} - -#species { - property: {TdrDto.PROPERTY_SPECIES}; - selected:{(java.util.Collection)tableEditBean.getSpecies()}; - _validatorLabel: {t("observe.content.tdr.species")}; - showListLabel: true; - universeLabel:{t("observe.content.tdr.availableSpecies")}; - selectedLabel:{t("observe.content.tdr.selectedSpecies")}; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/TdrUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/TdrUIHandler.java deleted file mode 100644 index 00568c9..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/TdrUIHandler.java +++ /dev/null @@ -1,485 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.ObserveSwingTechnicalException; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.DataFileDto; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.longline.SetLonglineTdrDto; -import fr.ird.observe.services.dto.longline.SetLonglineTdrDtos; -import fr.ird.observe.services.dto.longline.TdrDto; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.ReferentialReferences; -import fr.ird.observe.services.dto.referential.longline.SensorBrandDto; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.service.longline.TdrService; -import fr.ird.observe.services.service.longline.TripLonglineService; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIHandler; -import fr.ird.observe.ui.content.table.ContentTableUIModel; -import jaxx.runtime.context.JAXXContextEntryDef; -import jaxx.runtime.swing.HidorButton; -import jaxx.runtime.validator.swing.SwingValidatorMessage; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.jaxx.runtime.JaxxFileChooser; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.JTable; -import javax.swing.event.TableModelListener; -import javax.swing.table.DefaultTableCellRenderer; -import java.awt.Component; -import java.beans.PropertyChangeListener; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.Collection; -import java.util.Date; -import java.util.HashSet; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 9/30/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class TdrUIHandler extends ContentTableUIHandler<SetLonglineTdrDto, TdrDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(TdrUIHandler.class); - - // Compute valid state of tab from the error table - protected final TableModelListener computeTabValidStateListener; - - // Change toogle target visible on all TimeEditors - protected final PropertyChangeListener onToogleTimeEditorSliderChangedListener; - - protected boolean toogleTimeEditorSliderIsChanging; - - private static final JAXXContextEntryDef<LonglinePositionHelper<TdrDto>> POSITION_HELPER_ENTRY = - UIHelper.newContextEntryDef("TdrUI-positionHelper", LonglinePositionHelper.class); - - public TdrUIHandler(TdrUI ui) { - super(ui, DataContextType.SetLongline); - computeTabValidStateListener = e -> { - - SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); - computeTabValidState(source); - - }; - onToogleTimeEditorSliderChangedListener = evt -> { - Boolean newValue = (Boolean) evt.getNewValue(); - onToogleTimeEditorSliderChanged(newValue); - }; - } - - @Override - public TdrUI getUi() { - return (TdrUI) super.getUi(); - } - - @Override - protected void onSelectedRowChanged(int editingRow, TdrDto bean, boolean create) { - - ContentTableModel<SetLonglineTdrDto, TdrDto> model = getTableModel(); - - TdrUI ui = getUi(); - - boolean withTimestamp = bean.getFishingStart() != null; - ui.getEnableTimestamp().setSelected(withTimestamp); - - if (!model.isEditable()) { - return; - } - - String homeId = bean.getHomeId(); - - if (log.isDebugEnabled()) { - log.debug("selected tdr " + homeId); - } - JComponent requestFocus = ui.getHomeId(); - - if (create) { - - // set date - time - - SetLonglineTdrDto setLongline = getBean(); - - Date settingStartTimeStamp = setLongline.getSettingStartTimeStamp(); - setTimestamp(bean, settingStartTimeStamp); - - // go back to first tab - ui.getEditTabPane().setSelectedIndex(0); - - // enable timestamps - ui.getEnableTimestamp().setSelected(true); - - } else if (!withTimestamp) { - - // clean timestamps - setTimestamp(bean, null); - - } - - LonglinePositionHelper<TdrDto> positionHelper = POSITION_HELPER_ENTRY.getContextValue(ui); - positionHelper.resetPosition(bean); - - requestFocus.requestFocus(); - - } - - @Override - protected void initTableUI(DefaultTableCellRenderer renderer) { - - JTable table = getUi().getTable(); - - UIHelper.setI18nTableHeaderRenderer(table, - n("observe.content.tdr.table.homeId"), - n("observe.content.tdr.table.homeId.tip"), - n("observe.content.tdr.table.serialNo"), - n("observe.content.tdr.table.serialNo.tip"), - n("observe.content.tdr.table.sensorBrand"), - n("observe.content.tdr.table.sensorBrand.tip"), - n("observe.content.tdr.table.data"), - n("observe.content.sensorUsed.table.data.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newStringTableCellRenderer(renderer, 10, true)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newStringTableCellRenderer(renderer, 10, true)); - UIHelper.setTableColumnRenderer(table, 2, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SensorBrandDto.class)); - UIHelper.setTableColumnRenderer(table, 3, UIHelper.newBooleanTableCellRenderer(renderer)); - - } - - @Override - protected String getEditBeanIdToLoad() { - return getDataContext().getSelectedSetId(); - } - - @Override - public void initUI() { - - super.initUI(); - - LonglinePositionHelper<TdrDto> positionHelper = new LonglinePositionHelper<>( - getUi().getSection(), - getUi().getBasket(), - getUi().getBranchline(), - getTableEditBean()); - - POSITION_HELPER_ENTRY.setContextValue(getUi(), positionHelper); - - getUi().getDeployementStart().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); - getUi().getDeployementEnd().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); - getUi().getFishingStart().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); - getUi().getFishingEnd().getSliderHidor().addPropertyChangeListener(HidorButton.PROPERTY_TARGET_VISIBLE, onToogleTimeEditorSliderChangedListener); - - } - - @Override - public void openUI() { - - if (log.isInfoEnabled()) { - log.info("OpenUI: " + getModel()); - } - super.openUI(); - - // Reset all sections - LonglinePositionHelper<TdrDto> positionHelper = POSITION_HELPER_ENTRY.getContextValue(getUi()); - getUi().getSection().setData(positionHelper.getSections()); - - // To be sure always remove listener (could prevent some leaks) - getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); - // listen messages to see if required to add - getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); - - SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); - computeTabValidState(errorTableModel); - - } - - @Override - protected void closeSafeUI() { - if (log.isInfoEnabled()) { - log.info("CloseUI: " + getModel()); - } - super.closeSafeUI(); - - // remove listener - getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); - - } - - @Override - protected void resetEditBean() { - - super.resetEditBean(); - TdrDto tableEditBean = getTableEditBean(); - - boolean withTimestamp = tableEditBean.getFishingStart() != null; - getUi().getEnableTimestamp().setSelected(withTimestamp); - - } - - public void changeEnableTimestamp(boolean enableTimestamp) { - - Date timeStamp; - - if (enableTimestamp) { - - SetLonglineTdrDto setLongline = getBean(); - timeStamp = setLongline.getSettingStartTimeStamp(); - - } else { - - timeStamp = null; - - } - - TdrDto bean = getTableEditBean(); - setTimestamp(bean, timeStamp); - - } - - public void importData() { - - File file = UIHelper.chooseFile((Component) ui, - t("observe.content.choose.tdr.title.importData"), - t("observe.action.choose.tdr.importData"), - null); - - if (file != null) { - - if (log.isInfoEnabled()) { - log.info("Set data from file: " + file); - } - - DataFileDto dataFileDto = UIHelper.fileToDataFileDto(file); - getTableEditBean().setData(dataFileDto); - getTableEditBean().setHasData(true); - - } - - } - - public void deleteData() { - - int response = UIHelper.askUser((Component) ui, - t("observe.title.delete"), - t("observe.content.tdr.delete.data.message"), - JOptionPane.WARNING_MESSAGE, - new Object[]{t("observe.choice.confirm.delete"), - t("observe.choice.cancel")}, - 1); - - boolean doDelete = response == 0; - - if (doDelete) { - - if (log.isInfoEnabled()) { - log.info("Delete tdr data " + getTableEditBean().getData()); - } - getTableEditBean().setData(null); - getTableEditBean().setHasData(false); - - } - - } - - public void exportData() { - - DataFileDto dataFile = getTableEditBean().getData(); - - if (dataFile == null) { - dataFile = getTdrService().getDataFile(getTableEditBean().getId()); - } - - File file = JaxxFileChooser - .forSaving() - .setParent(getUi()) - .setTitle(t("observe.content.choose.tdr.title.exportData")) - .setApprovalText(t("observe.action.choose.tdr.exportData")) - .setFilename(dataFile.getName()) - .setUseAcceptAllFileFilter(true) - .choose(); - - if (file != null && UIHelper.confirmOverwriteFileIfExist(getUi(), file)) { - - if (log.isInfoEnabled()) { - log.info("save tdr data to " + file); - } - - try { - - Files.write(file.toPath(), dataFile.getContent()); - - ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); - mainUI.getStatus().setStatus(t("observe.content.sensorUsed.message.data.exported", file)); - } catch (IOException e) { - throw new ObserveSwingTechnicalException("Could not save binary data to " + file, e); - } - - } - - } - - protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { - - Set<String> errorProperties = new HashSet<>(); - int rowCount = errorTableModel.getRowCount(); - for (int i = 0; i < rowCount; i++) { - - SwingValidatorMessage row = errorTableModel.getRow(i); - if (NuitonValidatorScope.ERROR.equals(row.getScope())) { - errorProperties.add(row.getField()); - } - } - - boolean caracteristicsTabValid = !errorProperties.removeAll(TdrUIModel.CARACTERISTIC_TAB_PROPERTIES); - boolean localisationTabValid = !errorProperties.removeAll(TdrUIModel.LOCALISATION_TAB_PROPERTIES); - boolean timestampTabValid = !errorProperties.removeAll(TdrUIModel.TIMESTAMP_TAB_PROPERTIES); - boolean keyDataTabValid = !errorProperties.removeAll(TdrUIModel.KEY_DATA_TAB_PROPERTIES); - boolean speciesTabValid = !errorProperties.removeAll(TdrUIModel.SPECIES_TAB_PROPERTIES); - - TdrUIModel model = (TdrUIModel) getModel(); - model.setCaracteristicsTabValid(caracteristicsTabValid); - model.setLocalisationTabValid(localisationTabValid); - model.setTimestampTabValid(timestampTabValid); - model.setKeyDataTabValid(keyDataTabValid); - model.setSpeciesTabValid(speciesTabValid); - - } - - protected void onToogleTimeEditorSliderChanged(boolean newValue) { - - if (!toogleTimeEditorSliderIsChanging) { - - toogleTimeEditorSliderIsChanging = true; - - try { - - boolean selected = !newValue; - - getUi().getDeployementStart().getSliderHidor().setSelected(selected); - getUi().getDeployementStart().getSliderHidor().setTargetVisible(newValue); - - getUi().getFishingStart().getSliderHidor().setSelected(selected); - getUi().getFishingStart().getSliderHidor().setTargetVisible(newValue); - - getUi().getFishingEnd().getSliderHidor().setSelected(selected); - getUi().getFishingEnd().getSliderHidor().setTargetVisible(newValue); - - getUi().getDeployementEnd().getSliderHidor().setSelected(selected); - getUi().getDeployementEnd().getSliderHidor().setTargetVisible(newValue); - - } finally { - - toogleTimeEditorSliderIsChanging = false; - - } - - } - - } - - protected void setTimestamp(TdrDto bean, Date timestamp) { - - bean.setDeployementStart(timestamp); - bean.setDeployementEnd(timestamp); - bean.setFishingStart(timestamp); - bean.setFishingEnd(timestamp); - - } - - @Override - protected void doPersist(SetLonglineTdrDto bean) { - - SaveResultDto saveResult = getTdrService().save(bean); - saveResult.toDto(bean); - - } - - @Override - protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { - - Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); - - switch (propertyName) { - - case TdrDto.PROPERTY_SPECIES: { - String speciesListId = ObserveSwingApplicationContext.get().getConfig().getSpeciesListLonglineCatchId(); - - String tripLonglineId = getDataContext().getSelectedTripLonglineId(); - - TripLonglineService tripLonglineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripLonglineService(); - result = (List) tripLonglineService.getSpeciesByListAndTrip(tripLonglineId, speciesListId); - - result = ReferentialReferences.filterEnabled(result); - - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - - break; - } - - } - - return result; - - } - - @Override - protected void loadEditBean(String beanId) { - - Form<SetLonglineTdrDto> form = getTdrService().loadForm(beanId); - - ContentTableUIModel<SetLonglineTdrDto, TdrDto> model = getModel(); - loadReferentialReferenceSetsInModel(form); - model.setForm(form); - - LonglinePositionHelper<TdrDto> positionHelper = POSITION_HELPER_ENTRY.getContextValue(getUi()); - positionHelper.initSections(form.getObject(), - form.getObject().getTdr()); - - SetLonglineTdrDtos.copySetLonglineTdrDto(form.getObject(), getBean()); - - } - - protected TdrService getTdrService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTdrService(); - } -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/TdrUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/TdrUIModel.java deleted file mode 100644 index fdc86e5..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/TdrUIModel.java +++ /dev/null @@ -1,227 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; -import fr.ird.observe.services.dto.longline.SetLonglineTdrDto; -import fr.ird.observe.services.dto.longline.TdrDto; -import fr.ird.observe.services.dto.longline.TdrDtos; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; - -import java.util.Collection; -import java.util.List; -import java.util.Set; - -/** - * Created on 9/30/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class TdrUIModel extends ContentTableUIModel<SetLonglineTdrDto, TdrDto> { - - public static final Set<String> CARACTERISTIC_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(TdrDto.PROPERTY_HOME_ID, - TdrDto.PROPERTY_SERIAL_NO, - TdrDto.PROPERTY_SENSOR_BRAND, - TdrDto.PROPERTY_HAS_DATA, - TdrDto.PROPERTY_DATA).build(); - - public static final Set<String> LOCALISATION_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(TdrDto.PROPERTY_SECTION, - TdrDto.PROPERTY_BASKET, - TdrDto.PROPERTY_BRANCHLINE, - TdrDto.PROPERTY_ITEM_HORIZONTAL_POSITION, - TdrDto.PROPERTY_ITEM_VERTICAL_POSITION, - TdrDto.PROPERTY_FLOATLINE1_LENGTH, - TdrDto.PROPERTY_FLOATLINE2_LENGTH).build(); - - - public static final Set<String> TIMESTAMP_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(TdrDto.PROPERTY_DEPLOYEMENT_START, - TdrDto.PROPERTY_DEPLOYEMENT_END, - TdrDto.PROPERTY_FISHING_START, - TdrDto.PROPERTY_FISHING_END - ).build(); - - public static final Set<String> KEY_DATA_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(TdrDto.PROPERTY_FISHING_START_DEPTH, - TdrDto.PROPERTY_FISHING_END_DEPTH, - TdrDto.PROPERTY_MEAN_DEPLOYEMENT_DEPTH, - TdrDto.PROPERTY_MEDIAN_DEPLOYEMENT_DEPTH, - TdrDto.PROPERTY_MEAN_FISHING_DEPTH, - TdrDto.PROPERTY_MEDIAN_FISHING_DEPTH, - TdrDto.PROPERTY_MIN_FISHING_DEPTH, - TdrDto.PROPERTY_MAX_FISHING_DEPTH).build(); - - public static final Set<String> SPECIES_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(TdrDto.PROPERTY_SPECIES).build(); - - public static final String PROPERTY_CARACTERISTICS_TAB_VALID = "caracteristicsTabValid"; - - public static final String PROPERTY_LOCALISATION_TAB_VALID = "localisationTabValid"; - - public static final String PROPERTY_TIMESTAMP_TAB_VALID = "timestampTabValid"; - - public static final String PROPERTY_KEY_DATA_TAB_VALID = "keyDataTabValid"; - - public static final String PROPERTY_SPECIES_TAB_VALID = "speciesTabValid"; - - private static final long serialVersionUID = 1L; - - protected boolean caracteristicsTabValid; - - protected boolean localisationTabValid; - - protected boolean timestampTabValid; - - protected boolean keyDataTabValid; - - protected boolean speciesTabValid; - - public TdrUIModel(TdrUI ui) { - super(SetLonglineTdrDto.class, - TdrDto.class, - new String[]{ - SetLonglineTdrDto.PROPERTY_TDR, - SetLonglineTdrDto.PROPERTY_SETTING_START_TIME_STAMP - }, - new String[]{ - - // caracteristics tab - TdrDto.PROPERTY_HOME_ID, - TdrDto.PROPERTY_SERIAL_NO, - TdrDto.PROPERTY_SENSOR_BRAND, - TdrDto.PROPERTY_HAS_DATA, - TdrDto.PROPERTY_DATA, - - // localisation tab - TdrDto.PROPERTY_SECTION, - TdrDto.PROPERTY_BASKET, - TdrDto.PROPERTY_BRANCHLINE, - TdrDto.PROPERTY_ITEM_HORIZONTAL_POSITION, - TdrDto.PROPERTY_ITEM_VERTICAL_POSITION, - TdrDto.PROPERTY_FLOATLINE1_LENGTH, - TdrDto.PROPERTY_FLOATLINE2_LENGTH, - - // timestamp tab - TdrDto.PROPERTY_DEPLOYEMENT_START, - TdrDto.PROPERTY_DEPLOYEMENT_END, - TdrDto.PROPERTY_FISHING_START, - TdrDto.PROPERTY_FISHING_END, - - // key data tab - TdrDto.PROPERTY_FISHING_START_DEPTH, - TdrDto.PROPERTY_FISHING_END_DEPTH, - TdrDto.PROPERTY_MEAN_DEPLOYEMENT_DEPTH, - TdrDto.PROPERTY_MEDIAN_DEPLOYEMENT_DEPTH, - TdrDto.PROPERTY_MEAN_FISHING_DEPTH, - TdrDto.PROPERTY_MEDIAN_FISHING_DEPTH, - TdrDto.PROPERTY_MIN_FISHING_DEPTH, - TdrDto.PROPERTY_MAX_FISHING_DEPTH, - - // species tab - TdrDto.PROPERTY_SPECIES}); - - List<ContentTableMeta<TdrDto>> metas = Lists.newArrayList( - ContentTableModel.newTableMeta(TdrDto.class, TdrDto.PROPERTY_HOME_ID, false), - ContentTableModel.newTableMeta(TdrDto.class, TdrDto.PROPERTY_SERIAL_NO, false), - ContentTableModel.newTableMeta(TdrDto.class, TdrDto.PROPERTY_SENSOR_BRAND, false), - ContentTableModel.newTableMeta(TdrDto.class, TdrDto.PROPERTY_HAS_DATA, false)); - - initModel(ui, metas); - - } - - @Override - protected ContentTableModel<SetLonglineTdrDto, TdrDto> createTableModel( - ObserveContentTableUI<SetLonglineTdrDto, TdrDto> ui, - List<ContentTableMeta<TdrDto>> contentTableMetas) { - return new ContentTableModel<SetLonglineTdrDto, TdrDto>(ui, contentTableMetas) { - private static final long serialVersionUID = 1L; - @Override - protected Collection<TdrDto> getChilds(SetLonglineTdrDto bean) { - return bean.getTdr(); - } - - @Override - protected void load(TdrDto source, TdrDto target) { - TdrDtos.copyTdrDto(source, target); - } - - @Override - protected void setChilds(SetLonglineTdrDto parent, List<TdrDto> childs) { - parent.setTdr(childs); - } - }; - } - - public boolean isCaracteristicsTabValid() { - return caracteristicsTabValid; - } - - public void setCaracteristicsTabValid(boolean caracteristicsTabValid) { - this.caracteristicsTabValid = caracteristicsTabValid; - firePropertyChange(PROPERTY_CARACTERISTICS_TAB_VALID, null, caracteristicsTabValid); - } - - public boolean isLocalisationTabValid() { - return localisationTabValid; - } - - public void setLocalisationTabValid(boolean localisationTabValid) { - this.localisationTabValid = localisationTabValid; - firePropertyChange(PROPERTY_LOCALISATION_TAB_VALID, null, localisationTabValid); - } - - public boolean isKeyDataTabValid() { - return keyDataTabValid; - } - - public void setKeyDataTabValid(boolean keyDataTabValid) { - this.keyDataTabValid = keyDataTabValid; - firePropertyChange(PROPERTY_KEY_DATA_TAB_VALID, null, keyDataTabValid); - } - - public boolean isSpeciesTabValid() { - return speciesTabValid; - } - - public void setSpeciesTabValid(boolean speciesTabValid) { - this.speciesTabValid = speciesTabValid; - firePropertyChange(PROPERTY_SPECIES_TAB_VALID, null, speciesTabValid); - } - - public boolean isTimestampTabValid() { - return timestampTabValid; - } - - public void setTimestampTabValid(boolean timestampTabValid) { - this.timestampTabValid = timestampTabValid; - firePropertyChange(PROPERTY_TIMESTAMP_TAB_VALID, null, timestampTabValid); - } -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/WeightMeasuresTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/WeightMeasuresTableModel.java deleted file mode 100644 index 7af7e5d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/longline/WeightMeasuresTableModel.java +++ /dev/null @@ -1,105 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.longline.WeightMeasureDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.longline.WeightMeasureTypeDto; -import fr.ird.observe.ui.util.table.EditableTableWithCacheTableModelSupport; - -/** - * Created on 12/3/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.8 - */ -public class WeightMeasuresTableModel extends EditableTableWithCacheTableModelSupport<WeightMeasureDto> { - - private static final long serialVersionUID = 1L; - - public WeightMeasuresTableModel() { - super(); - } - - @Override - public boolean isRowNotEmpty(WeightMeasureDto valid) { - return !(valid.getWeightMeasureType() == null && valid.getWeight() == null); - } - - @Override - public boolean isRowValid(WeightMeasureDto valid) { - Float weight = valid.getWeight(); - return !(valid.getWeightMeasureType() == null || weight == null) && weight > 0 && weight < 1000; - } - - @Override - protected WeightMeasureDto createNewRow() { - return new WeightMeasureDto(); - } - - @Override - public int getColumnCount() { - return 2; - } - - @Override - public Object getValueAt(int rowIndex, int columnIndex) { - - WeightMeasureDto measure = data.get(rowIndex); - Object result; - switch (columnIndex) { - case 0: - result = measure.getWeightMeasureType(); - break; - case 1: - result = measure.getWeight(); - break; - default: - throw new IllegalStateException("Can't come here"); - } - return result; - } - - @Override - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - - WeightMeasureDto measure = data.get(rowIndex); - switch (columnIndex) { - case 0: - - measure.setWeightMeasureType((ReferentialReference<WeightMeasureTypeDto>) aValue); - break; - case 1: - - measure.setWeight((Float) aValue); - break; - - default: - throw new IllegalStateException("Can't come here"); - } - - setModified(true); - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/AbstractSampleUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/AbstractSampleUI.jcss deleted file mode 100644 index 8a7a337..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/AbstractSampleUI.jcss +++ /dev/null @@ -1,90 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -NumberEditor { - bean:{tableEditBean}; - autoPopup:{config.isAutoPopupNumberEditor()}; - showPopupButton:{config.isShowNumberEditorButton()}; - showReset:true; -} - -JToolBar { - borderPainted:false; - floatable:false; - opaque:false; -} - -#speciesLabel { - labelFor:{species}; -} - -#species { - property:"species"; - bean:{tableEditBean}; - showReset:true; - selectedItem:{tableEditBean.getSpecies()}; -} - -#lengthLabel { - labelFor:{length}; -} - -#length { - property:"length"; - model:{tableEditBean.getLength()}; - useFloat:true; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL1_PATTERN}; -} - -#lengthSourceInformation { - disabledIcon: {iconDataObserve}; - icon: {iconDataCalcule}; - enabled: {tableEditBean.isLengthSource()}; - toolTipText:{getLengthDataTip(tableEditBean.isLengthSource())}; -} - -#weightLabel { - text:"observe.common.weight.ind"; - labelFor:{weight}; -} - -#weight { - property:"weight"; - model:{tableEditBean.getWeight()}; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL2_PATTERN}; - _validatorLabel:{"observe.common.weight.ind"}; -} - -#weightSourceInformation { - disabledIcon: {iconDataObserve}; - icon: {iconDataCalcule}; - enabled: {tableEditBean.isWeightSource()}; - toolTipText:{getWeightDataTip(tableEditBean.isWeightSource())}; -} - -#comment { - minimumSize:{new Dimension(10,80)}; -} - -#comment2 { - text:{getStringValue(bean.getComment())}; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/CodeMesureEnum.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/CodeMesureEnum.java deleted file mode 100644 index cf5a3d3..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/CodeMesureEnum.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.table.impl.seine; - -import static org.nuiton.i18n.I18n.n; - -/** - * Définition des codes mesures utilisés pour saisir et afficher les - * échantillons thon. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.9.1 - */ -public enum CodeMesureEnum implements Comparable<CodeMesureEnum> { - - /** inconnue */ - unknown, - - /** mesure LD1 */ - ld1, - - /** mesure LF */ - lf; - - static { - - n("observe.codeMesureEnum.unknown"); - n("observe.codeMesureEnum.ld1"); - n("observe.codeMesureEnum.lf"); - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeatureMeasurementCellEditor.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeatureMeasurementCellEditor.java deleted file mode 100644 index 94d73b8..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeatureMeasurementCellEditor.java +++ /dev/null @@ -1,173 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.GearCaracteristicDto; -import fr.ird.observe.services.dto.referential.GearCaracteristicTypeDtos; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import jaxx.runtime.swing.JAXXWidgetUtil; -import jaxx.runtime.swing.editor.cell.NumberCellEditor; - -import javax.swing.JTable; -import javax.swing.border.LineBorder; -import javax.swing.event.CellEditorListener; -import javax.swing.table.TableCellEditor; -import java.awt.Color; -import java.awt.Component; -import java.util.EventObject; -import java.util.Map; -import java.util.TreeMap; - -/** - * Created on 4/7/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.16 - */ -public class GearUseFeatureMeasurementCellEditor implements TableCellEditor { - - protected final int caracteristicColumn; - - protected TableCellEditor editor; - - protected Map<String, TableCellEditor> editorsByGearCaracteristicId; - - - public GearUseFeatureMeasurementCellEditor(int caracteristicColumn) { - super(); - this.caracteristicColumn = caracteristicColumn; - - } - - @Override - public Object getCellEditorValue() { - return editor.getCellEditorValue(); - } - - @Override - public boolean isCellEditable(EventObject anEvent) { - return true; - } - - @Override - public boolean shouldSelectCell(EventObject anEvent) { - return editor.shouldSelectCell(anEvent); - } - - @Override - public boolean stopCellEditing() { - return editor.stopCellEditing(); - } - - @Override - public void cancelCellEditing() { - editor.cancelCellEditing(); - } - - @Override - public void addCellEditorListener(CellEditorListener l) { - editor.addCellEditorListener(l); - } - - @Override - public void removeCellEditorListener(CellEditorListener l) { - editor.removeCellEditorListener(l); - } - - public Map<String, TableCellEditor> getEditorsByGearCaracteristicId(JTable table) { - if (editorsByGearCaracteristicId == null) { - editorsByGearCaracteristicId = new TreeMap<>(); - - { - // texte - TableCellEditor editor = table.getDefaultEditor(Object.class); - editorsByGearCaracteristicId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.1", editor); - } - { - // boolean - TableCellEditor editor = table.getDefaultEditor(Boolean.class); - editorsByGearCaracteristicId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.2", editor); - } - { - // entier signé - NumberCellEditor<Integer> editor = JAXXWidgetUtil.newNumberTableCellEditor(Integer.class, true); - editor.getNumberEditor().setSelectAllTextOnError(true); - editor.getNumberEditor().setNumberPattern("\\d{0,6}?"); - editor.getNumberEditor().getTextField().setBorder(new LineBorder(Color.GRAY, 2)); - editorsByGearCaracteristicId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.3", editor); - } - { - // décimal signé - NumberCellEditor<Float> editor = JAXXWidgetUtil.newNumberTableCellEditor(Float.class, true); - editor.getNumberEditor().setSelectAllTextOnError(true); - editor.getNumberEditor().setNumberPattern("\\d{0,6}(\\.\\d{0,4})?"); - editor.getNumberEditor().getTextField().setBorder(new LineBorder(Color.GRAY, 2)); - editorsByGearCaracteristicId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.4", editor); - } - { - // entier non signé - NumberCellEditor<Integer> editor = JAXXWidgetUtil.newNumberTableCellEditor(Integer.class, false); - editor.getNumberEditor().setSelectAllTextOnError(true); - editor.getNumberEditor().setNumberPattern("\\d{0,6}?"); - editor.getNumberEditor().getTextField().setBorder(new LineBorder(Color.GRAY, 2)); - editorsByGearCaracteristicId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.5", editor); - } - { - // décimal non signé - NumberCellEditor<Float> editor = JAXXWidgetUtil.newNumberTableCellEditor(Float.class, false); - editor.getNumberEditor().setSelectAllTextOnError(true); - editor.getNumberEditor().setNumberPattern("\\d{0,6}(\\.\\d{0,4})?"); - editor.getNumberEditor().getTextField().setBorder(new LineBorder(Color.GRAY, 2)); - editorsByGearCaracteristicId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.6", editor); - } - - } - return editorsByGearCaracteristicId; - } - - @Override - public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { - - ReferentialReference<GearCaracteristicDto> caracteristicRef = (ReferentialReference<GearCaracteristicDto>) table.getModel().getValueAt(row, caracteristicColumn); - if (caracteristicRef == null) { - - // can't edit a null value ? - editor = table.getDefaultEditor(Object.class); - - } else { - - String gearCaracteristicTypeId = (String) caracteristicRef.getPropertyValue(GearCaracteristicDto.PROPERTY_GEAR_CARACTERISTIC_TYPE); - - Map<String, TableCellEditor> editors = getEditorsByGearCaracteristicId(table); - editor = editors.get(gearCaracteristicTypeId); - - value = GearCaracteristicTypeDtos.getTypeValue(gearCaracteristicTypeId, value); - - } - - Component result = editor.getTableCellEditorComponent(table, value, isSelected, row, column); - return result; - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeatureMeasurementCellRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeatureMeasurementCellRenderer.java deleted file mode 100644 index e00a1a1..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeatureMeasurementCellRenderer.java +++ /dev/null @@ -1,111 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.GearCaracteristicDto; -import fr.ird.observe.services.dto.referential.GearCaracteristicTypeDtos; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.UIHelper; - -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; -import javax.swing.table.TableCellRenderer; -import java.awt.Component; -import java.util.Map; -import java.util.TreeMap; - -/** - * Created on 4/7/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.16 - */ -public class GearUseFeatureMeasurementCellRenderer implements TableCellRenderer { - - protected final int caracteristicColumn; - - protected final Map<String, TableCellRenderer> renderersByCaracteristicTypeId; - - - public GearUseFeatureMeasurementCellRenderer(int caracteristicColumn, DefaultTableCellRenderer renderer) { - - this.caracteristicColumn = caracteristicColumn; - renderersByCaracteristicTypeId = new TreeMap<>(); - - { - // texte - TableCellRenderer editor = UIHelper.newStringTableCellRenderer(renderer, 10, true); - renderersByCaracteristicTypeId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.1", editor); - } - { - // boolean - TableCellRenderer editor = UIHelper.newBooleanTableCellRenderer(renderer); - renderersByCaracteristicTypeId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.2", editor); - } - { - // entier signé - TableCellRenderer editor = UIHelper.newEmptyNumberTableCellRenderer(renderer); - renderersByCaracteristicTypeId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.3", editor); - } - { - // décimal signé - TableCellRenderer editor = UIHelper.newEmptyNumberTableCellRenderer(renderer); - renderersByCaracteristicTypeId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.4", editor); - } - { - // entier non signé - TableCellRenderer editor = UIHelper.newEmptyNumberTableCellRenderer(renderer); - renderersByCaracteristicTypeId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.5", editor); - } - { - // décimal non signé - TableCellRenderer editor = UIHelper.newEmptyNumberTableCellRenderer(renderer); - renderersByCaracteristicTypeId.put("fr.ird.observe.entities.referentiel.GearCaracteristicType#1239832686123#0.6", editor); - } - } - - @Override - public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { - - TableCellRenderer tableCellRenderer; - - ReferentialReference<GearCaracteristicDto> caracteristicRef = (ReferentialReference<GearCaracteristicDto>) table.getModel().getValueAt(row, caracteristicColumn); - if (caracteristicRef == null) { - - tableCellRenderer = table.getDefaultRenderer(Object.class); - - } else { - String gearCaracteristicTypeId = (String) caracteristicRef.getPropertyValue(GearCaracteristicDto.PROPERTY_GEAR_CARACTERISTIC_TYPE); - - tableCellRenderer = renderersByCaracteristicTypeId.get(gearCaracteristicTypeId); - - value = GearCaracteristicTypeDtos.getTypeValue(gearCaracteristicTypeId, value); - - } - - Component result = tableCellRenderer.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - return result; - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeaturesMeasurementSeinesTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeaturesMeasurementSeinesTableModel.java deleted file mode 100644 index 5438c90..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeaturesMeasurementSeinesTableModel.java +++ /dev/null @@ -1,133 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.GearCaracteristicDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.seine.GearUseFeaturesMeasurementSeineDto; -import fr.ird.observe.ui.util.table.EditableTableWithCacheTableModelSupport; - -/** - * Created on 4/7/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.16 - */ -public class GearUseFeaturesMeasurementSeinesTableModel extends EditableTableWithCacheTableModelSupport<GearUseFeaturesMeasurementSeineDto> { - - private static final long serialVersionUID = 1L; - - public GearUseFeaturesMeasurementSeinesTableModel() { - super(); - } - - @Override - public boolean isRowNotEmpty(GearUseFeaturesMeasurementSeineDto valid) { - return !(valid.getGearCaracteristic() == null && valid.getMeasurementValue() == null); - } - - @Override - protected boolean isRowValid(GearUseFeaturesMeasurementSeineDto valid) { - String size = valid.getMeasurementValue(); - return !(valid.getGearCaracteristic() == null || size == null) && !size.isEmpty(); - } - - @Override - public int getColumnCount() { - return 2; - } - - @Override - public Object getValueAt(int rowIndex, int columnIndex) { - - GearUseFeaturesMeasurementSeineDto measure = data.get(rowIndex); - Object result; - switch (columnIndex) { - case 0: - result = measure.getGearCaracteristic(); - break; - case 1: - result = measure.getMeasurementValue(); - break; - default: - throw new IllegalStateException("Can't come here"); - } - return result; - } - - @Override - public boolean isCellEditable(int rowIndex, int columnIndex) { - - boolean result; - switch (columnIndex) { - case 0: - result = true; - break; - case 1: - GearUseFeaturesMeasurementSeineDto measure = data.get(rowIndex); - result = measure != null && measure.getGearCaracteristic() != null; - break; - default: - throw new IllegalStateException("Can't come here"); - } - return result; - - } - - @Override - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - - GearUseFeaturesMeasurementSeineDto measure = data.get(rowIndex); - switch (columnIndex) { - case 0: - measure.setGearCaracteristic((ReferentialReference<GearCaracteristicDto>) aValue); - break; - case 1: - - measure.setMeasurementValue(aValue == null ? null : String.valueOf(aValue)); - break; - - default: - throw new IllegalStateException("Can't come here"); - } - - setModified(true); - - } - - @Override - public void removeSelectedRow() { - - super.removeSelectedRow(); - - // revalidate table model - validate(); - setModified(true); - - } - - @Override - protected GearUseFeaturesMeasurementSeineDto createNewRow() { - return new GearUseFeaturesMeasurementSeineDto(); - } -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeaturesSeineTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeaturesSeineTableModel.java deleted file mode 100644 index 7bcfb7c..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeaturesSeineTableModel.java +++ /dev/null @@ -1,177 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Sets; -import fr.ird.observe.services.dto.referential.GearDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.seine.GearUseFeaturesMeasurementSeineDto; -import fr.ird.observe.services.dto.seine.GearUseFeaturesSeineDto; -import fr.ird.observe.services.dto.seine.GearUseFeaturesSeineDtos; -import fr.ird.observe.services.dto.seine.TripSeineGearUseDto; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.Collection; -import java.util.List; - -/** - * Created on 4/7/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.16 - */ -public class GearUseFeaturesSeineTableModel extends ContentTableModel<TripSeineGearUseDto, GearUseFeaturesSeineDto> { - - /** Logger. */ - private static final Log log = LogFactory.getLog(GearUseFeaturesSeineTableModel.class); - - private static final long serialVersionUID = 1L; - - private transient GearUseFeaturesSeineUIHandler gearUseFeaturesSeineUIHandler; - - public GearUseFeaturesSeineTableModel(ObserveContentTableUI<TripSeineGearUseDto, GearUseFeaturesSeineDto> context, - List<ContentTableMeta<GearUseFeaturesSeineDto>> contentTableMetas) { - super(context, contentTableMetas); - } - - public void setGearUseFeaturesSeineUIHandler(GearUseFeaturesSeineUIHandler gearUseFeaturesSeineUIHandler) { - this.gearUseFeaturesSeineUIHandler = gearUseFeaturesSeineUIHandler; - } - - @Override - public void addNewEntry() { - - int editingRow = getSelectedRow(); - - if (editingRow > -1) { - - // store sizes and weights for the selected row - // before creating a new one ? - GearUseFeaturesSeineUIModel model = getModel(); - model.getMeasurementsTableModel().storeInCacheForRow(editingRow); - - } - - super.addNewEntry(); - } - - @Override - public void updateRowFromEditBean() { - - GearUseFeaturesSeineUIModel model = getModel(); - - int editingRow = getSelectedRow(); - GearUseFeaturesSeineDto rowBean = getRowBean(); - GearUseFeaturesMeasurementSeinesTableModel measurementsTableModel = model.getMeasurementsTableModel(); - - List<GearUseFeaturesMeasurementSeineDto> measurements; - - if (rowBean.getId() == null && CollectionUtils.isEmpty(measurementsTableModel.getCacheForRow(editingRow))) { - - // new gear usage, add default measurements - - ReferentialReference<GearDto> gear = rowBean.getGear(); - measurements = gearUseFeaturesSeineUIHandler.getDefaultGearUseFeaturesMeasurementSeine(gear.getId()); - if (log.isInfoEnabled()) { - log.info("Create mode, use default measurements: " + measurements.size()); - } - measurementsTableModel.removeCacheForRow(editingRow); - measurementsTableModel.initCacheForRow(editingRow, measurements); - - measurementsTableModel.setData(measurements); - measurementsTableModel.setModified(false); - - } else { - - // store current measurements for the selected row - measurementsTableModel.storeInCacheForRow(editingRow); - - measurements = measurementsTableModel.getData(); - } - - rowBean.setGearUseFeaturesMeasurement(Sets.newLinkedHashSet(measurements)); - - super.updateRowFromEditBean(); - - - } - - @Override - protected void removeRow(int row) { - super.removeRow(row); - - // remove sizes and weights for the deleted row - // also update rows to row - 1 (when after the deleted row) - GearUseFeaturesSeineUIModel model = getModel(); - model.getMeasurementsTableModel().removeCacheForRow(row); - - } - - @Override - protected void setChilds(TripSeineGearUseDto parent, List<GearUseFeaturesSeineDto> childs) { - parent.getGearUseFeaturesSeine().clear(); - parent.addAllGearUseFeaturesSeine(childs); - } - - @Override - public void resetEditBean() { - - int row = getSelectedRow(); - if (log.isInfoEnabled()) { - log.info("Reset edit bean at row: " + row); - } - GearUseFeaturesSeineUIModel model = getModel(); - model.getMeasurementsTableModel().resetCacheForRow(row); - - super.resetEditBean(); - - } - - @Override - protected Collection<GearUseFeaturesSeineDto> getChilds(TripSeineGearUseDto bean) { - return bean.getGearUseFeaturesSeine(); - } - - @Override - protected void load(GearUseFeaturesSeineDto source, GearUseFeaturesSeineDto target) { - GearUseFeaturesSeineDtos.copyGearUseFeaturesSeineDto(source, target); - } - - @Override - protected void resetRow(int row) { - super.resetRow(row); - - GearUseFeaturesSeineUIModel model = getModel(); - model.getMeasurementsTableModel().resetCacheForRow(row); - } - - @Override - protected GearUseFeaturesSeineUIModel getModel() { - return (GearUseFeaturesSeineUIModel) super.getModel(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeaturesSeineUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeaturesSeineUI.jaxx deleted file mode 100644 index cdfccd6..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeaturesSeineUI.jaxx +++ /dev/null @@ -1,155 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.table.ContentTableUI - superGenericType='TripSeineGearUseDto, GearUseFeaturesSeineDto' - contentTitle='{n("observe.content.gearUseFeaturesSeine.title")}' - saveNewEntryText='{n("observe.content.action.create.gearUseFeaturesSeine")}' - saveNewEntryTip='{n("observe.content.action.create.gearUseFeaturesSeine.tip")}'> - - <style source="../../CommonTable.jcss"/> - - <import> - fr.ird.observe.services.dto.CommentableDto - fr.ird.observe.services.dto.seine.TripSeineGearUseDto - fr.ird.observe.services.dto.seine.GearUseFeaturesSeineDto - fr.ird.observe.services.dto.seine.GearUseFeaturesMeasurementSeineDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.GearDto - fr.ird.observe.ui.content.table.* - fr.ird.observe.ui.util.BooleanEditor - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - java.awt.Dimension - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <GearUseFeaturesSeineUIHandler id='handler' constructorParams='this'/> - - <!-- model --> - <GearUseFeaturesSeineUIModel id='model' constructorParams='this'/> - - <GearUseFeaturesMeasurementSeinesTableModel id='measurementsTableModel' - initializer="getModel().getMeasurementsTableModel()"/> - - <!-- edit bean --> - <TripSeineGearUseDto id='bean'/> - - <!-- table edit bean --> - <GearUseFeaturesSeineDto id='tableEditBean'/> - - <!-- table model --> - <ContentTableModel id='tableModel'/> - - <!-- le validateur de l'écran --> - <BeanValidator id='validator' - beanClass='fr.ird.observe.services.dto.seine.TripSeineGearUseDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update'/> - - <!-- le validateur d'une entrée de tableau --> - <BeanValidator id='validatorTable' - autoField='true' - beanClass='fr.ird.observe.services.dto.seine.GearUseFeaturesSeineDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update'/> - - <JPopupMenu id='measurementsTablePopup'> - <JMenuItem id='addMeasurement' onActionPerformed='getHandler().addMeasurement()'/> - <JMenuItem id='deleteSelectedMeasurement' onActionPerformed='getHandler().deleteSelectedMeasurement()'/> - </JPopupMenu> - - <Table id='editorPanel' fill='both' insets='0' weighty="1"> - <row> - <cell weightx="1" weighty="0.9"> - - <JTabbedPane id='gearUseFeaturesTabPane'> - - <tab id='generalTab'> - - <JPanel layout='{new BorderLayout()}'> - - <Table id='editForm' fill='both' insets='1' constraints="BorderLayout.NORTH"> - - <!-- gear --> - <row> - <cell> - <JLabel id='gearLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='gear' constructorParams='this' genericType='ReferentialReference<GearDto>' _entityClass='GearDto.class'/> - </cell> - </row> - - <!-- number --> - <row> - <cell> - <JLabel id='numberLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='number' constructorParams='this'/> - </cell> - </row> - - <!-- usedInTrip --> - <row> - <cell> - <JLabel id='usedInTripLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BooleanEditor id='usedInTrip'/> - </cell> - </row> - - </Table> - - </JPanel> - - - </tab> - - <tab id='measurementsFormTab'> - - <JScrollPane id='measurementsScrollPane'> - <JTable id='measurementsTable'/> - </JScrollPane> - - </tab> - </JTabbedPane> - - </cell> - </row> - <row> - <cell weighty='0.1'> - <JScrollPane id='comment' onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2'/> - </JScrollPane> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeaturesSeineUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeaturesSeineUI.jcss deleted file mode 100644 index 52961c3..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeaturesSeineUI.jcss +++ /dev/null @@ -1,103 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#model { - valid:{validator.isValid() && validatorTable.isValid() && getMeasurementsTableModel().isValid()}; - canSaveRow:{validatorTable.isChanged() && validatorTable.isValid() && getMeasurementsTableModel().isValid()}; - canResetRow:{validatorTable.isChanged()}; -} - -/* ***************************************************************************** */ -/* GENERAL TAB **************************************************************** */ -/* ***************************************************************************** */ - -#generalTab { - title:{t("observe.content.gearUseFeaturesSeine.tab.general")}; - icon:{handler.getErrorIconIfFalse(model.isGeneralTabValid())}; -} - -#gearLabel { - text:"observe.content.gearUseFeaturesSeine.gear"; - labelFor:{gear}; -} - -#gear { - property:{GearUseFeaturesSeineDto.PROPERTY_GEAR}; - selectedItem:{tableEditBean.getGear()}; -} - -#numberLabel { - text:"observe.content.gearUseFeaturesSeine.number"; - labelFor:{number}; -} - -#number { - property:{GearUseFeaturesSeineDto.PROPERTY_NUMBER}; - model:{tableEditBean.getNumber()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; -} - -#usedInTripLabel { - text:"observe.content.gearUseFeaturesSeine.usedInTrip"; - labelFor:{usedInTrip}; -} - -#usedInTrip { - booleanValue:{tableEditBean.getUsedInTrip()}; - _tablePropertyName:{GearUseFeaturesSeineDto.PROPERTY_USED_IN_TRIP}; -} - -/* ***************************************************************************** */ -/* MEASUREMENTS TAB *********************************************************** */ -/* ***************************************************************************** */ - -#measurementsFormTab { - title:{t("observe.content.gearUseFeaturesSeine.tab.measurements")}; - icon:{handler.getErrorIconIfFalse(measurementsTableModel.isValid())}; - enabled:{!tableModel.isCreate()}; -} - -#measurementsTable { - model: {measurementsTableModel}; -} - -#comment { - columnHeaderView:{new JLabel(t("observe.content.gearUseFeaturesSeine.comment"))}; - minimumSize:{new Dimension(10,80)}; -} - -#comment2 { - _tablePropertyName: {GearUseFeaturesSeineDto.PROPERTY_COMMENT}; - text:{getStringValue(tableEditBean.getComment())}; -} - -#addMeasurement { - text: "observe.content.gearUseFeaturesSeine.action.addMeasurement"; - toolTipText: "observe.content.gearUseFeaturesSeine.action.addMeasurement.tip"; - actionIcon: add; -} - -#deleteSelectedMeasurement { - text: "observe.content.gearUseFeaturesSeine.action.deleteSelectedMeasurement"; - toolTipText: "observe.content.gearUseFeaturesSeine.action.deleteSelectedMeasurement.tip"; - actionIcon: delete; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeaturesSeineUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeaturesSeineUIHandler.java deleted file mode 100644 index 02d5880..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeaturesSeineUIHandler.java +++ /dev/null @@ -1,506 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.referential.GearCaracteristicDto; -import fr.ird.observe.services.dto.referential.GearCaracteristicTypeDtos; -import fr.ird.observe.services.dto.referential.GearDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.dto.seine.GearUseFeaturesMeasurementSeineDto; -import fr.ird.observe.services.dto.seine.GearUseFeaturesSeineDto; -import fr.ird.observe.services.dto.seine.TripSeineGearUseDto; -import fr.ird.observe.services.dto.seine.TripSeineGearUseDtos; -import fr.ird.observe.services.service.ReferentialService; -import fr.ird.observe.services.service.seine.TripSeineGearUseService; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.ContentUIInitializer; -import fr.ird.observe.ui.content.table.ContentTableUIHandler; -import jaxx.runtime.SwingUtil; -import jaxx.runtime.validator.swing.SwingValidatorMessage; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.JTable; -import javax.swing.event.TableModelListener; -import javax.swing.table.DefaultTableCellRenderer; -import java.awt.GridBagConstraints; -import java.awt.Insets; -import java.beans.PropertyChangeListener; -import java.util.Collections; -import java.util.HashSet; -import java.util.Iterator; -import java.util.List; -import java.util.Set; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 3/24/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.16 - */ -public class GearUseFeaturesSeineUIHandler extends ContentTableUIHandler<TripSeineGearUseDto, GearUseFeaturesSeineDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(GearUseFeaturesSeineUIHandler.class); - - // Compute valid state of tab from the error table - protected final TableModelListener computeTabValidStateListener; - - private final PropertyChangeListener measurementsTableModelModified; - - public GearUseFeaturesSeineUIHandler(GearUseFeaturesSeineUI ui) { - super(ui, DataContextType.TripSeine); - computeTabValidStateListener = e -> { - - SwingValidatorMessageTableModel source = (SwingValidatorMessageTableModel) e.getSource(); - computeTabValidState(source); - - }; - measurementsTableModelModified = evt -> onMeasurementsTableModelModified((Boolean) evt.getNewValue()); - } - - @Override - public GearUseFeaturesSeineUI getUi() { - return (GearUseFeaturesSeineUI) super.getUi(); - } - - @Override - public GearUseFeaturesSeineUIModel getModel() { - return (GearUseFeaturesSeineUIModel) super.getModel(); - } - - @Override - public void initUI() { - - super.initUI(); - - getModel().addPropertyChangeListener(GearUseFeaturesSeineUIModel.PROPERTY_EDITABLE, evt -> { - Boolean newValue = (Boolean) evt.getNewValue(); - setTableModelEditable(newValue); - }); - - setTableModelEditable(getModel().isEditable()); - - getTableModel().setGearUseFeaturesSeineUIHandler(this); - - } - - @Override - public void openUI() { - - if (log.isInfoEnabled()) { - log.info("OpenUI: " + getModel()); - } - - super.openUI(); - - // To be sure always remove listener (could prevent some leaks) - getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); - // listen messages to see if required to add - getUi().getErrorTableModel().addTableModelListener(computeTabValidStateListener); - - SwingValidatorMessageTableModel errorTableModel = getUi().getErrorTableModel(); - computeTabValidState(errorTableModel); - - } - - @Override - public void startEditUI(String... binding) { - - getModel().getMeasurementsTableModel().setEditable(true); - - super.startEditUI(binding); - - } - - public void addMeasurement() { - - GearUseFeaturesMeasurementSeinesTableModel tableModel = getUi().getMeasurementsTableModel(); - tableModel.addNewRow(); - - } - - public void deleteSelectedMeasurement() { - - GearUseFeaturesMeasurementSeinesTableModel tableModel = getUi().getMeasurementsTableModel(); - - boolean selectionEmpty = tableModel.isSelectionEmpty(); - - if (!selectionEmpty) { - - GearUseFeaturesMeasurementSeineDto data = tableModel.getSelectedRow(); - - if (log.isInfoEnabled()) { - log.info("Delete: " + data); - } - - ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); - int response = UIHelper.askUser(mainUI, - t("observe.title.delete"), - t("observe.content.measurement.delete.message"), - JOptionPane.WARNING_MESSAGE, - new Object[]{t("observe.choice.confirm.delete"), - t("observe.choice.cancel")}, - 1); - - if (response != 0) { - - // user cancel - return; - } - - tableModel.removeSelectedRow(); - - } - - } - - public List<GearUseFeaturesMeasurementSeineDto> getDefaultGearUseFeaturesMeasurementSeine(String gearId) { - - ReferentialService referentialService = getDataSource().newReferentialService(); - - Form<GearDto> gearDtoForm = referentialService.loadForm(GearDto.class, gearId); - - GearDto gearDto = gearDtoForm.getObject(); - - List<GearUseFeaturesMeasurementSeineDto> measurements = Lists.newArrayList( - Iterables.transform(gearDto.getGearCaracteristic(), - input -> { - GearUseFeaturesMeasurementSeineDto measurementSeineDto = new GearUseFeaturesMeasurementSeineDto(); - String gearCaracterisiticTypeId = (String) input.getPropertyValue(GearCaracteristicDto.PROPERTY_GEAR_CARACTERISTIC_TYPE); - if (GearCaracteristicTypeDtos.isBoolean(gearCaracterisiticTypeId)) { - measurementSeineDto.setMeasurementValue(Boolean.FALSE.toString()); - } - measurementSeineDto.setGearCaracteristic(input); - return measurementSeineDto; - })); - - return measurements; - - } - - @Override - protected void onSelectedRowChanged(int editingRow, GearUseFeaturesSeineDto bean, boolean create) { - - if (log.isInfoEnabled()) { - log.info("Selected row changed: " + editingRow + ", create? " + create); - } - - GearUseFeaturesSeineUI ui = getUi(); - - UIHelper.stopEditing(ui.getMeasurementsTable()); - - GearUseFeaturesSeineTableModel tableModel = getTableModel(); - GearUseFeaturesSeineUIModel model = getModel(); - - boolean emptySelection = editingRow == -1; - - // load size measures - - GearUseFeaturesMeasurementSeinesTableModel measurementsTableModel = model.getMeasurementsTableModel(); - List<GearUseFeaturesMeasurementSeineDto> measurements = emptySelection ? Collections.emptyList() : measurementsTableModel.getCacheForRow(editingRow); - if (measurements == null) { - - if (log.isInfoEnabled()) { - log.info("init measurements for row " + editingRow); - } - - // first time coming on this row - - if (tableModel.isCreate()) { - - // create mode: just init with empty list - measurements = Collections.emptyList(); - - if (log.isInfoEnabled()) { - log.info("create mode, use an empty list"); - } - - } else { - measurements = Lists.newArrayList(bean.getGearUseFeaturesMeasurement()); - } - - // init measurements - measurementsTableModel.initCacheForRow(editingRow, measurements); - - } else { - - if (log.isInfoEnabled()) { - log.info("Using existing measurements for row " + editingRow + " : " + measurements.size()); - } - } - - measurementsTableModel.setData(measurements); - - measurementsTableModel.setModified(false); - measurementsTableModel.setEditable(tableModel.isEditable()); - - if (!tableModel.isEditable()) { - return; - } - - JComponent requestFocus; - - if (tableModel.isCreate()) { - - // go back to first pane - ui.getGearUseFeaturesTabPane().setSelectedIndex(0); - - requestFocus = ui.getGear(); - - } else { - - requestFocus = ui.getGear(); - - } - - requestFocus.requestFocus(); - - } - - @Override - protected void initTableUI(DefaultTableCellRenderer renderer) { - - { - JTable table = getUi().getTable(); - - UIHelper.setI18nTableHeaderRenderer(table, - n("observe.content.gearUseFeaturesSeine.table.gear"), - n("observe.content.gearUseFeaturesSeine.table.gear.tip"), - n("observe.content.gearUseFeaturesSeine.table.number"), - n("observe.content.gearUseFeaturesSeine.table.number.tip"), - n("observe.content.gearUseFeaturesSeine.table.usedInTrip"), - n("observe.content.gearUseFeaturesSeine.table.usedInTrip.tip"), - n("observe.content.gearUseFeaturesSeine.table.comment"), - n("observe.content.gearUseFeaturesSeine.table.comment.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, GearDto.class)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 2, UIHelper.newBooleanTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 3, UIHelper.newStringTableCellRenderer(renderer, 10, true)); - } - - { - // init measurements table - JTable table = getUi().getMeasurementsTable(); - - UIHelper.setI18nTableHeaderRenderer(table, - n("observe.content.gearUseFeaturesSeine.table.gearCaracteristic"), - n("observe.content.gearUseFeaturesSeine.table.gearCaracteristic.tip"), - n("observe.content.gearUseFeaturesSeine.table.value"), - n("observe.content.gearUseFeaturesSeine.table.value.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, GearCaracteristicDto.class)); - UIHelper.setTableColumnRenderer(table, 1, new GearUseFeatureMeasurementCellRenderer(0, renderer)); - - table.getTableHeader().setReorderingAllowed(false); - - ReferentialReferenceDecorator<GearCaracteristicDto> decorator = getReferentialReferenceDecorator(GearCaracteristicDto.class); - - List<ReferentialReference<GearCaracteristicDto>> caracteristics = Lists.newArrayList(getDataSource().getReferentialReferences(GearCaracteristicDto.class)); - - UIHelper.setTableColumnEditor(table, 0, ContentUIInitializer.newDataColumnEditor(caracteristics, decorator)); - UIHelper.setTableColumnEditor(table, 1, new GearUseFeatureMeasurementCellEditor(0)); - - initInlineTable(getUi().getMeasurementsScrollPane(), - table, - getModel().getMeasurementsTableModel(), - measurementsTableModelModified, - getUi().getMeasurementsTablePopup(), - getUi().getAddMeasurement(), - getUi().getDeleteSelectedMeasurement()); - - } - - // Adapt layout to let more place for the editor - - getUi().getShowForm().remove(1); - getUi().getShowForm().add(SwingUtil.boxComponentWithJxLayer(getUi().getEditor()), new GridBagConstraints(0, 1, 1, 1, 1.0, 0.3, 10, 1, new Insets(0, 0, 0, 0), 0, 0), 1); - getUi().getEditor().remove(0); - getUi().getEditor().add(SwingUtil.boxComponentWithJxLayer(getUi().getEditorPanel()), new GridBagConstraints(0, 0, 1, 1, 1.0, 1.0, 10, 1, new Insets(0, 0, 0, 0), 0, 0), 0); - - - } - - @Override - protected String getEditBeanIdToLoad() { - return getDataContext().getSelectedTripSeineId(); - } - - @Override - protected void closeSafeUI() { - - if (log.isInfoEnabled()) { - log.info("CloseUI: " + getModel()); - } - super.closeSafeUI(); - - // remove listener - getUi().getErrorTableModel().removeTableModelListener(computeTabValidStateListener); - - } - - @Override - protected void resetEditBean() { - - UIHelper.stopEditing(getUi().getMeasurementsTable()); - - super.resetEditBean(); - - } - - @Override - public void resetEditUI() { - - getModel().getMeasurementsTableModel().clear(); - - super.resetEditUI(); - - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - - // par defaut, on suppose qu'on peut afficher les données - getModel().setShowData(true); - - String selectedTripId = dataContext.getSelectedTripId(); - - if (getOpenDataManager().isOpenTripSeine(selectedTripId)) { - - // mode mise a jour - return ContentMode.UPDATE; - } - - // mode lecture - - if (dataContext.isSelectedTripLongline()) { - - addInfoMessage(t("observe.content.tripLongline.message.not.open")); - - } else { - - addInfoMessage(t("observe.content.tripSeine.message.not.open")); - - } - - return ContentMode.READ; - } - - @Override - protected GearUseFeaturesSeineTableModel getTableModel() { - return (GearUseFeaturesSeineTableModel) super.getTableModel(); - } - - protected void setTableModelEditable(Boolean newValue) { - - getModel().getMeasurementsTableModel().setEditable(newValue); - - } - - protected void onMeasurementsTableModelModified(Boolean newValue) { - - if (newValue) { - - // modify the validator, since this is the best way to prevent table edit form actions - // that something was modified on the form - getUi().getValidatorTable().setChanged(true); - - } - - // recompute table model valid state - getModel().getMeasurementsTableModel().validate(); - - } - - protected void computeTabValidState(SwingValidatorMessageTableModel errorTableModel) { - - Set<String> errorProperties = new HashSet<>(); - int rowCount = errorTableModel.getRowCount(); - for (int i = 0; i < rowCount; i++) { - - SwingValidatorMessage row = errorTableModel.getRow(i); - if (NuitonValidatorScope.ERROR.equals(row.getScope())) { - errorProperties.add(row.getField()); - } - } - - boolean generalTabValid = !errorProperties.removeAll(GearUseFeaturesSeineUIModel.GENERAL_TAB_PROPERTIES); - - GearUseFeaturesSeineUIModel model = getModel(); - - model.setGeneralTabValid(generalTabValid); - - } - - @Override - protected void doPersist(TripSeineGearUseDto bean) { - - // On ne persiste pas les measurements qui sont vides - for (GearUseFeaturesSeineDto gearUseFeatures : bean.getGearUseFeaturesSeine()) { - if (!gearUseFeatures.isGearUseFeaturesMeasurementEmpty()) { - Iterator<GearUseFeaturesMeasurementSeineDto> iterator = gearUseFeatures.getGearUseFeaturesMeasurement().iterator(); - while (iterator.hasNext()) { - GearUseFeaturesMeasurementSeineDto gearUseFeaturesMeasurement = iterator.next(); - if (gearUseFeaturesMeasurement.isEmpty()) { - iterator.remove(); - } - } - } - } - - SaveResultDto saveResult = getTripSeineGearUseService().save(bean); - saveResult.toDto(bean); - - } - - @Override - protected void loadEditBean(String beanId) { - Form<TripSeineGearUseDto> form = getTripSeineGearUseService().loadForm(beanId); - loadReferentialReferenceSetsInModel(form); - getModel().setForm(form); - TripSeineGearUseDtos.copyTripSeineGearUseDto(form.getObject(), getBean()); - } - - protected TripSeineGearUseService getTripSeineGearUseService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripSeineGearUseService(); - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeaturesSeineUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeaturesSeineUIModel.java deleted file mode 100644 index c76af87..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/GearUseFeaturesSeineUIModel.java +++ /dev/null @@ -1,109 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; -import fr.ird.observe.services.dto.seine.GearUseFeaturesSeineDto; -import fr.ird.observe.services.dto.seine.TripSeineGearUseDto; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; - -import java.util.List; -import java.util.Set; - -/** - * Created on 3/24/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.16 - */ -public class GearUseFeaturesSeineUIModel extends ContentTableUIModel<TripSeineGearUseDto, GearUseFeaturesSeineDto> { - - private static final long serialVersionUID = 1L; - - public static final String PROPERTY_GENERAL_TAB_VALID = "generalTabValid"; - - public static final Set<String> GENERAL_TAB_PROPERTIES = - ImmutableSet.<String>builder().add(GearUseFeaturesSeineDto.PROPERTY_GEAR, - GearUseFeaturesSeineDto.PROPERTY_NUMBER, - GearUseFeaturesSeineDto.PROPERTY_USED_IN_TRIP, - GearUseFeaturesSeineDto.PROPERTY_COMMENT).build(); - - protected boolean generalTabValid; - - private final GearUseFeaturesMeasurementSeinesTableModel measurementsTableModel; - - public GearUseFeaturesSeineUIModel(GearUseFeaturesSeineUI ui) { - - super(TripSeineGearUseDto.class, - GearUseFeaturesSeineDto.class, - new String[]{ - TripSeineGearUseDto.PROPERTY_ID, - TripSeineGearUseDto.PROPERTY_GEAR_USE_FEATURES_SEINE, - TripSeineGearUseDto.PROPERTY_LAST_UPDATE_DATE, - }, - new String[]{ - GearUseFeaturesSeineDto.PROPERTY_ID, - GearUseFeaturesSeineDto.PROPERTY_NUMBER, - GearUseFeaturesSeineDto.PROPERTY_USED_IN_TRIP, - GearUseFeaturesSeineDto.PROPERTY_GEAR_USE_FEATURES_MEASUREMENT, - GearUseFeaturesSeineDto.PROPERTY_COMMENT - } - ); - - this.measurementsTableModel = new GearUseFeaturesMeasurementSeinesTableModel(); - - List<ContentTableMeta<GearUseFeaturesSeineDto>> metas = Lists.newArrayList( - ContentTableModel.newTableMeta(GearUseFeaturesSeineDto.class, GearUseFeaturesSeineDto.PROPERTY_GEAR, false), - ContentTableModel.newTableMeta(GearUseFeaturesSeineDto.class, GearUseFeaturesSeineDto.PROPERTY_NUMBER, false), - ContentTableModel.newTableMeta(GearUseFeaturesSeineDto.class, GearUseFeaturesSeineDto.PROPERTY_USED_IN_TRIP, false), - ContentTableModel.newTableMeta(GearUseFeaturesSeineDto.class, GearUseFeaturesSeineDto.PROPERTY_COMMENT, false)); - - initModel(ui, metas); - - } - - @Override - protected GearUseFeaturesSeineTableModel createTableModel( - ObserveContentTableUI<TripSeineGearUseDto, GearUseFeaturesSeineDto> ui, - List<ContentTableMeta<GearUseFeaturesSeineDto>> contentTableMetas) { - return new GearUseFeaturesSeineTableModel(ui, contentTableMetas); - } - - public GearUseFeaturesMeasurementSeinesTableModel getMeasurementsTableModel() { - return measurementsTableModel; - } - - public boolean isGeneralTabValid() { - return generalTabValid; - } - - public void setGeneralTabValid(boolean generalTabValid) { - this.generalTabValid = generalTabValid; - firePropertyChange(PROPERTY_GENERAL_TAB_VALID, null, isGeneralTabValid()); - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ModeSaisieEchantillonEnum.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ModeSaisieEchantillonEnum.java deleted file mode 100644 index 3239ca3..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ModeSaisieEchantillonEnum.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.table.impl.seine; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Pour définir le mode saisie d'un échantillon. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.8 - */ -public enum ModeSaisieEchantillonEnum { - /** - * Le mode de saisie par défaut. - * - * L'observateur entre un effectif et une classe de taille, il ne peut pas - * saisir le poids (celui sera déduit par calcul). - */ - byEffectif(n("observe.modeSaisieEchantillonEnum.byEffectif")), - - /** - * Le mode de saisie par individu. - * - * L'observateur saisie les poids individuel, il ne peut pas saisir - * d'effectif, l'effectif est de 1. - */ - byIndividu(n("observe.modeSaisieEchantillonEnum.byIndividu")); - - private final String i18nKey; - - ModeSaisieEchantillonEnum(String i18nKey) { - this.i18nKey = i18nKey; - } - - public static ModeSaisieEchantillonEnum valueOf(int ordinal) - throws IllegalArgumentException { - for (ModeSaisieEchantillonEnum o : values()) { - if (o.ordinal() == ordinal) { - return o; - } - } - throw new IllegalArgumentException( - "could not find a " + ModeSaisieEchantillonEnum.class.getSimpleName() + - " value for ordinal " + ordinal); - } - - public String getI18nKey() { - return i18nKey; - } - - @Override - public String toString() { - return t(i18nKey); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetCatchUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetCatchUI.jaxx deleted file mode 100644 index 8b83137..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetCatchUI.jaxx +++ /dev/null @@ -1,195 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - - -<fr.ird.observe.ui.content.table.ContentTableUI - superGenericType='SetSeineNonTargetCatchDto, NonTargetCatchDto' - contentTitle='{n("observe.common.nonTargetCatch")}' - saveNewEntryText='{n("observe.content.action.create.nonTargetCatch")}' - saveNewEntryTip='{n("observe.content.action.create.nonTargetCatch.tip")}'> - - <style source="../../CommonTable.jcss"/> - - <import> - fr.ird.observe.services.dto.CommentableDto - fr.ird.observe.services.dto.seine.SetSeineNonTargetCatchDto - fr.ird.observe.services.dto.seine.NonTargetCatchDto - fr.ird.observe.services.dto.referential.seine.SpeciesFateDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.SpeciesDto - fr.ird.observe.services.dto.referential.seine.ReasonForDiscardDto - fr.ird.observe.ui.content.table.* - fr.ird.observe.validation.ObserveSwingValidator - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - java.awt.Dimension - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <NonTargetCatchUIHandler id='handler' constructorParams='this'/> - - <!-- model --> - <NonTargetCatchUIModel id='model' constructorParams='this'/> - - <!-- edit bean --> - <SetSeineNonTargetCatchDto id='bean'/> - - <!-- table edit bean --> - <NonTargetCatchDto id='tableEditBean'/> - - <!-- table model --> - <ContentTableModel id='tableModel'/> - - <!-- le validateur de l'écran --> - - <BeanValidator id='validator' - beanClass='fr.ird.observe.services.dto.seine.SetSeineNonTargetCatchDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update'> - <!-- clef unique --> - <field name="nonTargetCatch" component="editorPanel"/> - </BeanValidator> - - <!-- le validateur d'une entrée de tableau --> - <BeanValidator id='validatorTable' - autoField='true' - beanClass='fr.ird.observe.services.dto.seine.NonTargetCatchDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update'/> - - <Table id='editorPanel' fill='both' insets='1' - onFocusGained='species.requestFocus()'> - - <!-- species faune --> - <row> - <cell> - <JLabel id='speciesLabel'/> - </cell> - <cell weightx='1' anchor='east' columns="2"> - <BeanComboBox id='species' constructorParams='this' genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class'/> - </cell> - </row> - - <!-- objectFate faune --> - <row> - <cell> - <JLabel id='speciesFateLabel'/> - </cell> - <cell weightx='1' anchor='east' columns="2"> - <BeanComboBox id='speciesFate' constructorParams='this' genericType='ReferentialReference<SpeciesFateDto>' _entityClass='SpeciesFateDto.class'/> - </cell> - </row> - - <!-- raison rejet --> - <row> - <cell> - <JLabel id='reasonForDiscardLabel'/> - </cell> - <cell weightx='1' anchor='east' columns="2"> - <BeanComboBox id='reasonForDiscard' constructorParams='this' genericType='ReferentialReference<ReasonForDiscardDto>' _entityClass='ReasonForDiscardDto.class'/> - </cell> - </row> - - <!-- weight estime --> - <row> - <cell> - <JLabel id='catchWeightLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='catchWeight' constructorParams='this'/> - </cell> - <cell anchor='east'> - <JToolBar id='catchWeightComputedAction'> - <JButton id='catchWeightComputedInformation' - onActionPerformed='getHandler().resetCatchWeightComputed()'/> - </JToolBar> - </cell> - </row> - - <!-- count estime --> - <row> - <cell> - <JLabel id='totalCountLabel'/> - </cell> - <cell weightx='1'> - <NumberEditor id='totalCount' constructorParams='this'/> - - </cell> - <cell anchor='east'> - <JToolBar id='totalCountComputedAction'> - <JButton id='totalCountComputedInformation' - onActionPerformed='getHandler().resetTotalCountComputed()'/> - </JToolBar> - </cell> - </row> - - <!-- weight moyen --> - <row> - <cell> - <JLabel id='meanWeightLabel'/> - </cell> - <cell weightx='1'> - <NumberEditor id='meanWeight' constructorParams='this'/> - </cell> - <cell anchor='east'> - <JToolBar id='meanWeightComputedAction'> - <JButton id='meanWeightComputedInformation' - onActionPerformed='getHandler().resetMeanWeightComputed()'/> - </JToolBar> - </cell> - </row> - - <!-- taille moyenne --> - <row> - <cell> - <JLabel id='meanLengthLabel'/> - </cell> - <cell weightx='1'> - <NumberEditor id='meanLength' constructorParams='this'/> - </cell> - <cell anchor='east'> - <JToolBar id='meanLengthComputedAction'> - <JButton id='meanLengthComputedInformation' - onActionPerformed='getHandler().resetMeanLengthComputed()'/> - </JToolBar> - </cell> - </row> - - <!-- comment --> - <row> - <cell columns='3' weighty='1'> - <JScrollPane id='comment' - onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2' - onKeyReleased='getTableEditBean().setComment(((JTextArea) event.getSource()).getText())'/> - </JScrollPane> - </cell> - </row> - - </Table> - -</fr.ird.observe.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetCatchUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetCatchUI.jcss deleted file mode 100644 index 60d169c..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetCatchUI.jcss +++ /dev/null @@ -1,139 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#tableModel{ - deleteExtraMessage:{t("observe.content.nonTargetCatch.table.deleteExtraMessage")}; -} - -#speciesLabel { - text:"observe.common.speciesFaune"; - labelFor:{species}; -} - -#species { - property:{NonTargetCatchDto.PROPERTY_SPECIES}; - selectedItem:{tableEditBean.getSpecies()}; -} - -#speciesFateLabel { - text:"observe.common.speciesFate"; - labelFor:{speciesFate}; -} - -#speciesFate { - property:{NonTargetCatchDto.PROPERTY_SPECIES_FATE}; - selectedItem:{tableEditBean.getSpeciesFate()}; -} - -#reasonForDiscardLabel { - text:"observe.common.reasonForDiscard"; - labelFor:{reasonForDiscard}; -} - -#reasonForDiscard { - property:{NonTargetCatchDto.PROPERTY_REASON_FOR_DISCARD}; - selectedItem:{tableEditBean.getReasonForDiscard()}; -} - -#catchWeightLabel { - text:"observe.common.catchWeight"; - labelFor:{catchWeight}; -} - -#catchWeight { - property:{NonTargetCatchDto.PROPERTY_CATCH_WEIGHT}; - useFloat:true; - model:{tableEditBean.getCatchWeight()}; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL3_PATTERN}; -} - -#catchWeightComputedInformation { - disabledIcon: {iconDataObserve}; - icon: {iconDataCalcule}; - enabled: {tableEditBean.getCatchWeightComputedSource() != null}; - toolTipText:{getHandler().getCatchWeightDataTip(tableEditBean.getCatchWeightComputedSource())}; -} - -#totalCountLabel { - text:"observe.common.totalCount"; - labelFor:{totalCount}; -} - -#totalCount { - property:{NonTargetCatchDto.PROPERTY_TOTAL_COUNT}; - model:{tableEditBean.getTotalCount()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; -} - -#totalCountComputedInformation { - disabledIcon: {iconDataObserve}; - icon: {iconDataCalcule}; - enabled: {tableEditBean.getTotalCountComputedSource() != null}; - toolTipText:{getHandler().getTotalCountDataTip(tableEditBean.getTotalCountComputedSource())}; -} - -#meanWeightLabel { - text:"observe.common.meanWeight"; - labelFor:{meanWeight}; -} - -#meanWeight { - property:{NonTargetCatchDto.PROPERTY_MEAN_WEIGHT}; - model:{tableEditBean.getMeanWeight()}; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL2_PATTERN}; -} - -#meanWeightComputedInformation { - disabledIcon: {iconDataObserve}; - icon: {iconDataCalcule}; - enabled: {tableEditBean.getMeanWeightComputedSource() != null}; - toolTipText:{getHandler().getMeanWeightDataTip(tableEditBean.getMeanWeightComputedSource())}; -} - -#meanLengthLabel { - text:"observe.common.meanLength"; - labelFor:{meanLength}; -} - -#meanLength { - property:{NonTargetCatchDto.PROPERTY_MEAN_LENGTH}; - model:{tableEditBean.getMeanLength()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; -} - -#meanLengthComputedInformation { - disabledIcon: {iconDataObserve}; - icon: {iconDataCalcule}; - enabled: {tableEditBean.getMeanLengthComputedSource() != null}; - /*icon:{getDataIcon(tableEditBean.getMeanLengthComputedSource() != null)};*/ - toolTipText:{getHandler().getMeanLengthDataTip(tableEditBean.getMeanLengthComputedSource())}; -} - -#comment { - columnHeaderView:{new JLabel(t("observe.common.comment.nonTargetCatch"))}; - minimumSize:{new Dimension(10,80)}; -} - -#comment2 { - text:{getStringValue(tableEditBean.getComment())}; -} - diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetCatchUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetCatchUIHandler.java deleted file mode 100644 index f74641e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetCatchUIHandler.java +++ /dev/null @@ -1,403 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.table.impl.seine; - -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.constants.seine.NonTargetCatchComputedValueSource; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.ReferentialReferences; -import fr.ird.observe.services.dto.referential.SpeciesDto; -import fr.ird.observe.services.dto.referential.seine.ReasonForDiscardDto; -import fr.ird.observe.services.dto.referential.seine.SpeciesFateDto; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.dto.seine.NonTargetCatchDto; -import fr.ird.observe.services.dto.seine.NonTargetCatchDtos; -import fr.ird.observe.services.dto.seine.SetSeineNonTargetCatchDto; -import fr.ird.observe.services.dto.seine.SetSeineNonTargetCatchDtos; -import fr.ird.observe.services.service.seine.NonTargetCatchService; -import fr.ird.observe.services.service.seine.TripSeineService; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; -import java.beans.PropertyChangeListener; -import java.util.ArrayList; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class NonTargetCatchUIHandler extends ContentTableUIHandler<SetSeineNonTargetCatchDto, NonTargetCatchDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(NonTargetCatchUIHandler.class); - - /** - * Ecoute les modifications de la propriété {@link NonTargetCatchDto#getTotalCount()}, - * et repasser alors le flag {@link NonTargetCatchDto#getTotalCountComputedSource()} à - * {@code null}. - * - * @since 3.0 - */ - protected final PropertyChangeListener totalCountChanged; - - /** - * Ecoute les modifications de la propriété {@link NonTargetCatchDto#getCatchWeight()}, - * et repasser alors le flag {@link NonTargetCatchDto#getCatchWeightComputedSource()} à - * {@code null}. - * - * @since 3.0 - */ - protected final PropertyChangeListener catchWeightChanged; - - /** - * Ecoute les modifications de la propriété {@link NonTargetCatchDto#getMeanWeight()}, - * et repasser alors le flag {@link NonTargetCatchDto#getMeanWeightComputedSource()} à - * {@code null}. - * - * @since 3.0 - */ - protected final PropertyChangeListener meanWeightChanged; - - /** - * Ecoute les modifications de la propriété {@link NonTargetCatchDto#getMeanLength()}, - * et repasser alors le flag {@link NonTargetCatchDto#getMeanLengthComputedSource()} à - * {@code null}. - * - * @since 3.0 - */ - protected final PropertyChangeListener meanLengthChanged; - - public NonTargetCatchUIHandler(NonTargetCatchUI ui) { - super(ui, DataContextType.SetSeine); - totalCountChanged = evt -> { - NonTargetCatchDto source = (NonTargetCatchDto) evt.getSource(); - source.setTotalCountComputedSource(null); - }; - catchWeightChanged = evt -> { - NonTargetCatchDto source = (NonTargetCatchDto) evt.getSource(); - source.setCatchWeightComputedSource(null); - }; - meanWeightChanged = evt -> { - NonTargetCatchDto source = (NonTargetCatchDto) evt.getSource(); - source.setMeanWeightComputedSource(null); - }; - meanLengthChanged = evt -> { - NonTargetCatchDto source = (NonTargetCatchDto) evt.getSource(); - source.setMeanLengthComputedSource(null); - }; - } - - @Override - public NonTargetCatchUI getUi() { - return (NonTargetCatchUI) super.getUi(); - } - - public String getCatchWeightDataTip(NonTargetCatchComputedValueSource computed) { - String result; - - if (computed == null) { - result = t("observe.common.catchWeightComputed.observed.tip"); - } else { - result = t("observe.common.catchWeightComputed.computed.tip", computed.toString()); - } - return result; - } - - public String getTotalCountDataTip(NonTargetCatchComputedValueSource computed) { - String result; - - if (computed == null) { - result = t("observe.common.totalCountComputed.observed.tip"); - } else { - result = t("observe.common.totalCountComputed.computed.tip", computed.toString()); - - } - return result; - } - - public String getMeanWeightDataTip(NonTargetCatchComputedValueSource computed) { - String result; - - if (computed == null) { - result = t("observe.common.meanWeightComputed.observed.tip"); - } else { - result = t("observe.common.meanWeightComputed.computed.tip", computed.toString()); - } - return result; - } - - public String getMeanLengthDataTip(NonTargetCatchComputedValueSource computed) { - String result; - - if (computed == null) { - result = t("observe.common.meanLengthComputed.observed.tip"); - } else { - result = t("observe.common.meanLengthComputed.computed.tip", computed.toString()); - } - return result; - } - - public void resetCatchWeightComputed() { - getTableEditBean().setCatchWeightComputedSource(null); - getUi().getCatchWeight().grabFocus(); - } - - public void resetTotalCountComputed() { - getTableEditBean().setTotalCountComputedSource(null); - getUi().getTotalCount().grabFocus(); - } - - public void resetMeanWeightComputed() { - getTableEditBean().setMeanWeightComputedSource(null); - getUi().getMeanWeight().grabFocus(); - } - - public void resetMeanLengthComputed() { - getTableEditBean().setMeanLengthComputedSource(null); - getUi().getMeanLength().grabFocus(); - } - - @Override - protected String getEditBeanIdToLoad() { - return getDataContext().getSelectedSetId(); - } - - @Override - protected void onSelectedRowChanged(int editingRow, NonTargetCatchDto bean, boolean create) { - NonTargetCatchUI ui = getUi(); - - ContentTableModel<SetSeineNonTargetCatchDto, NonTargetCatchDto> model = getTableModel(); - - if (!model.isEditable()) { - - // rien a faire - return; - } - - List<ReferentialReference<SpeciesDto>> availableEspeces; - JComponent requestFocus; - - if (create) { - Set<ReferentialReference<SpeciesDto>> speciesSet = getModel().getReferentialReferences(NonTargetCatchDto.PROPERTY_SPECIES); - availableEspeces = Lists.newArrayList(speciesSet); - - requestFocus = ui.getSpecies(); - } else { - ReferentialReference<SpeciesDto> species = bean.getSpecies(); - availableEspeces = new ArrayList<>(); - availableEspeces.add(species); - requestFocus = ui.getTable(); - } - - ui.getSpecies().setData(availableEspeces); - requestFocus.requestFocus(); - - NonTargetCatchDto tableEditBean = getTableEditBean(); - tableEditBean.removePropertyChangeListener(NonTargetCatchDto.PROPERTY_TOTAL_COUNT, totalCountChanged); - tableEditBean.addPropertyChangeListener(NonTargetCatchDto.PROPERTY_TOTAL_COUNT, totalCountChanged); - - tableEditBean.removePropertyChangeListener(NonTargetCatchDto.PROPERTY_CATCH_WEIGHT, catchWeightChanged); - tableEditBean.addPropertyChangeListener(NonTargetCatchDto.PROPERTY_CATCH_WEIGHT, catchWeightChanged); - - tableEditBean.removePropertyChangeListener(NonTargetCatchDto.PROPERTY_MEAN_WEIGHT, meanWeightChanged); - tableEditBean.addPropertyChangeListener(NonTargetCatchDto.PROPERTY_MEAN_WEIGHT, meanWeightChanged); - - tableEditBean.removePropertyChangeListener(NonTargetCatchDto.PROPERTY_MEAN_LENGTH, meanLengthChanged); - tableEditBean.addPropertyChangeListener(NonTargetCatchDto.PROPERTY_MEAN_LENGTH, meanLengthChanged); - } - - @Override - protected void initTableUI(DefaultTableCellRenderer renderer) { - - JTable table = getUi().getTable(); - - UIHelper.fixTableColumnWidth(table, 3, 55); - UIHelper.fixTableColumnWidth(table, 4, 65); - UIHelper.fixTableColumnWidth(table, 5, 75); - UIHelper.fixTableColumnWidth(table, 6, 55); - UIHelper.fixTableColumnWidth(table, 7, 50); - - UIHelper.setI18nTableHeaderRenderer( - table, - n("observe.content.nonTargetCatch.table.speciesFaune"), - n("observe.content.nonTargetCatch.table.speciesFaune.tip"), - n("observe.content.nonTargetCatch.table.speciesFate"), - n("observe.content.nonTargetCatch.table.speciesFate.tip"), - n("observe.content.nonTargetCatch.table.reasonForDiscard"), - n("observe.content.nonTargetCatch.table.reasonForDiscard.tip"), - n("observe.content.nonTargetCatch.table.catchWeight"), - n("observe.content.nonTargetCatch.table.catchWeight.tip"), - n("observe.content.nonTargetCatch.table.totalCount"), - n("observe.content.nonTargetCatch.table.totalCount.tip"), - n("observe.content.nonTargetCatch.table.meanWeight"), - n("observe.content.nonTargetCatch.table.meanWeight.tip"), - n("observe.content.nonTargetCatch.table.meanLength"), - n("observe.content.nonTargetCatch.table.meanLength.tip"), - n("observe.content.nonTargetCatch.table.comment"), - n("observe.content.nonTargetCatch.table.comment.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesDto.class)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesFateDto.class)); - UIHelper.setTableColumnRenderer(table, 2, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, ReasonForDiscardDto.class)); - UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 4, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 5, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 6, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 7, UIHelper.newStringTableCellRenderer(renderer, 10, true)); - } - - @SuppressWarnings("Duplicates") - @Override - protected boolean prepareSave(SetSeineNonTargetCatchDto editBean, List<NonTargetCatchDto> objets) throws Exception { - super.prepareSave(editBean, objets); - - //on cherche si parmis les captures supprimer certaines ont des échantillon - SetSeineNonTargetCatchDto originalSetSeineNonTargetCatchDto = getModel().getForm().getObject(); - - Set<ReferentialReference<SpeciesDto>> speciesToDelete = Sets.newHashSet(); - - for (NonTargetCatchDto nonTargetCatchDto : originalSetSeineNonTargetCatchDto.getNonTargetCatch()) { - - if (nonTargetCatchDto.isHasSample()) { - - ReferentialReference<SpeciesDto> species = nonTargetCatchDto.getSpecies(); - - Iterable<NonTargetCatchDto> currentTargetCatchSpecies = NonTargetCatchDtos.filterBySpecies(objets, species); - - if (Iterables.isEmpty(currentTargetCatchSpecies)) { - - speciesToDelete.add(species); - - } - } - - } - - if (!speciesToDelete.isEmpty()) { - - // il existe des echantillon faune a supprimer on demande une - // confirmation - StringBuilder sb = new StringBuilder(512); - ReferentialReferenceDecorator<SpeciesDto> decorator = - getDecoratorService().getReferentialReferenceDecorator(SpeciesDto.class); - - for (ReferentialReference<SpeciesDto> species : speciesToDelete) { - sb.append(" - ").append(decorator.toString(species)).append('\n'); - } - int reponse = UIHelper.askUser( - t("observe.title.need.confirm"), - t("observe.content.nonTargetCatch.message.table.will.delete.nonTargetSample", sb.toString()), - JOptionPane.ERROR_MESSAGE, - new Object[]{ - t("observe.choice.continue"), - t("observe.choice.cancel")}, - 0); - if (log.isDebugEnabled()) { - log.debug("response : " + reponse); - } - boolean canContinue = false; - switch (reponse) { - case 0: - // wil reset ui - canContinue = true; - break; - } - if (!canContinue) { - // l'utilisateur a choisi de ne pas continuer - return false; - } - } - - return true; - } - - @Override - protected void doPersist(SetSeineNonTargetCatchDto bean) { - - SaveResultDto saveResult = getNonTargetCatchService().save(bean); - saveResult.toDto(bean); - - } - - @Override - protected void loadEditBean(String beanId) { - Form<SetSeineNonTargetCatchDto> form = getNonTargetCatchService().loadForm(beanId); - loadReferentialReferenceSetsInModel(form); - getModel().setForm(form); - SetSeineNonTargetCatchDtos.copySetSeineNonTargetCatchDto(form.getObject(), getBean()); - } - - @Override - protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { - - Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); - - switch (propertyName) { - - case NonTargetCatchDto.PROPERTY_SPECIES: { - - String speciesListId = ObserveSwingApplicationContext.get().getConfig().getSpeciesListSeineNonTargetCatchId(); - String tripSeineId = getDataContext().getSelectedTripSeineId(); - - TripSeineService tripSeineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripSeineService(); - result = (List) tripSeineService.getSpeciesByListAndTrip(tripSeineId, speciesListId); - - result = ReferentialReferences.filterEnabled(result); - - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - } - - break; - - } - - return result; - - } - - protected NonTargetCatchService getNonTargetCatchService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newNonTargetCatchService(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetCatchUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetCatchUIModel.java deleted file mode 100644 index d02baf1..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetCatchUIModel.java +++ /dev/null @@ -1,105 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import fr.ird.observe.services.dto.seine.NonTargetCatchDto; -import fr.ird.observe.services.dto.seine.NonTargetCatchDtos; -import fr.ird.observe.services.dto.seine.SetSeineNonTargetCatchDto; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; - -import java.util.Collection; -import java.util.List; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class NonTargetCatchUIModel extends ContentTableUIModel<SetSeineNonTargetCatchDto, NonTargetCatchDto> { - - private static final long serialVersionUID = 1L; - - public NonTargetCatchUIModel(NonTargetCatchUI ui) { - super(SetSeineNonTargetCatchDto.class, - NonTargetCatchDto.class, - new String[]{ - SetSeineNonTargetCatchDto.PROPERTY_NON_TARGET_CATCH}, - new String[]{ - NonTargetCatchDto.PROPERTY_SPECIES, - NonTargetCatchDto.PROPERTY_CATCH_WEIGHT, - NonTargetCatchDto.PROPERTY_TOTAL_COUNT, - NonTargetCatchDto.PROPERTY_MEAN_WEIGHT, - NonTargetCatchDto.PROPERTY_MEAN_LENGTH, - NonTargetCatchDto.PROPERTY_REASON_FOR_DISCARD, - NonTargetCatchDto.PROPERTY_SPECIES_FATE, - NonTargetCatchDto.PROPERTY_TOTAL_COUNT_COMPUTED_SOURCE, - NonTargetCatchDto.PROPERTY_MEAN_WEIGHT_COMPUTED_SOURCE, - NonTargetCatchDto.PROPERTY_CATCH_WEIGHT_COMPUTED_SOURCE, - NonTargetCatchDto.PROPERTY_MEAN_LENGTH_COMPUTED_SOURCE, - NonTargetCatchDto.PROPERTY_COMMENT - }); - - List<ContentTableMeta<NonTargetCatchDto>> metas = Lists.newArrayList( - ContentTableModel.newTableMeta(NonTargetCatchDto.class, NonTargetCatchDto.PROPERTY_SPECIES, false), - ContentTableModel.newTableMeta(NonTargetCatchDto.class, NonTargetCatchDto.PROPERTY_SPECIES_FATE, false), - ContentTableModel.newTableMeta(NonTargetCatchDto.class, NonTargetCatchDto.PROPERTY_REASON_FOR_DISCARD, false), - ContentTableModel.newTableMeta(NonTargetCatchDto.class, NonTargetCatchDto.PROPERTY_CATCH_WEIGHT, false), - ContentTableModel.newTableMeta(NonTargetCatchDto.class, NonTargetCatchDto.PROPERTY_TOTAL_COUNT, false), - ContentTableModel.newTableMeta(NonTargetCatchDto.class, NonTargetCatchDto.PROPERTY_MEAN_WEIGHT, false), - ContentTableModel.newTableMeta(NonTargetCatchDto.class, NonTargetCatchDto.PROPERTY_MEAN_LENGTH, false), - ContentTableModel.newTableMeta(NonTargetCatchDto.class, NonTargetCatchDto.PROPERTY_COMMENT, false)); - - initModel(ui, metas); - - } - - @Override - protected ContentTableModel<SetSeineNonTargetCatchDto, NonTargetCatchDto> createTableModel( - ObserveContentTableUI<SetSeineNonTargetCatchDto, NonTargetCatchDto> ui, - List<ContentTableMeta<NonTargetCatchDto>> contentTableMetas) { - - return new ContentTableModel<SetSeineNonTargetCatchDto, NonTargetCatchDto>(ui, contentTableMetas) { - private static final long serialVersionUID = 1L; - - @Override - protected Collection<NonTargetCatchDto> getChilds(SetSeineNonTargetCatchDto bean) { - return bean.getNonTargetCatch(); - } - - @Override - protected void load(NonTargetCatchDto source, NonTargetCatchDto target) { - NonTargetCatchDtos.copyNonTargetCatchDto(source, target); - } - - @Override - protected void setChilds(SetSeineNonTargetCatchDto parent, List<NonTargetCatchDto> childs) { - bean.setNonTargetCatch(childs); - } - }; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetSampleUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetSampleUI.jaxx deleted file mode 100644 index f0f404a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetSampleUI.jaxx +++ /dev/null @@ -1,221 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.table.ContentTableUI - superGenericType='NonTargetSampleDto, NonTargetLengthDto' - contentTitle='{n("observe.common.nonTargetSample")}' - saveNewEntryText='{n("observe.content.action.create.nonTargetSample")}' - saveNewEntryTip='{n("observe.content.action.create.nonTargetSample.tip")}'> - - <style source="../../CommonTable.jcss"/> - <style source="AbstractSampleUI.jcss"/> - - <import> - fr.ird.observe.services.dto.CommentableDto - fr.ird.observe.services.dto.referential.SexDto - fr.ird.observe.services.dto.referential.SpeciesDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.seine.NonTargetLengthDto - fr.ird.observe.services.dto.seine.NonTargetSampleDto - fr.ird.observe.ui.content.table.impl.seine.ModeSaisieEchantillonEnum - fr.ird.observe.ui.content.table.* - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - java.awt.Dimension - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <NonTargetSampleUIHandler id='handler' constructorParams='this'/> - - <!-- model --> - <NonTargetSampleUIModel id='model' constructorParams='this'/> - - <!-- edit bean --> - <NonTargetSampleDto id='bean'/> - - <!-- table edit bean --> - <NonTargetLengthDto id='tableEditBean'/> - - <!-- table model --> - <ContentTableModel id='tableModel'/> - - <!-- le validateur de l'écran --> - <BeanValidator id='validator' - beanClass='fr.ird.observe.services.dto.seine.NonTargetSampleDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update'> - <field name='comment'/> - </BeanValidator> - - <!-- le validateur d'une entrée de tableau --> - <BeanValidator id='validatorTable' - autoField='true' - beanClass='fr.ird.observe.services.dto.seine.NonTargetLengthDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update'> - </BeanValidator> - - <ButtonGroup id='acquisitionModeGroup' - onStateChanged='getHandler().updateModeSaisie((ModeSaisieEchantillonEnum) acquisitionModeGroup.getSelectedValue())'/> - - <script><![CDATA[ - -public static final String POIDS_COMPUTED_TIP = n("observe.common.weight.computed.tip"); -public static final String POIDS_OBSERVED_TIP = n("observe.common.weight.observed.tip"); -public static final String LONGUEUR_COMPUTED_TIP = n("observe.common.length.computed.tip"); -public static final String LONGUEUR_OBSERVED_TIP = n("observe.common.length.observed.tip"); - -public String getWeightDataTip(boolean computed) { - return computed ? t(POIDS_COMPUTED_TIP) : t(POIDS_OBSERVED_TIP); -} - -public String getLengthDataTip(boolean computed) { - return computed ? t(LONGUEUR_COMPUTED_TIP) : t(LONGUEUR_OBSERVED_TIP); -} - -public String getSpeciesFauneTypeTaille(ReferentialReference<SpeciesDto> species) { - return species == null ? t("observe.message.no.species.selected") : (String) species.getPropertyValue(SpeciesDto.PROPERTY_LENGTH_MEASURE_TYPE); -} -]]> - </script> - - <JLabel id='hideFormInformation'/> - - <Table id='editorPanel' fill='both' insets='1'> - - <!-- mode de saisie --> - <row> - <cell columns="2"> - <JPanel id='acquisitionModePanel'> - <JRadioButton id='acquisitionModeEffectif'/> - <JRadioButton id='acquisitionModeIndividu'/> - </JPanel> - </cell> - </row> - - <!-- species faune --> - <row> - <cell> - <JLabel id='speciesLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='species' constructorParams='this' genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class'/> - </cell> - </row> - - <!-- species faune (type taille) --> - <row> - <cell> - <JLabel id='speciesTypeTailleLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <JLabel id='speciesTypeTaille'/> - </cell> - </row> - - <!-- length --> - <row> - <cell> - <JLabel id='lengthLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='length' constructorParams='this'/> - </cell> - <cell anchor='east'> - <JToolBar id='lengthSourceAction'> - <JButton id='lengthSourceInformation' - onActionPerformed='getHandler().resetLengthSource()'/> - </JToolBar> - </cell> - </row> - - <!-- weight individuel --> - <row> - <cell> - <JLabel id='weightLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='weight' constructorParams='this'/> - </cell> - <cell anchor='east'> - <JToolBar id='weightSourceAction'> - <JButton id='weightSourceInformation' - onActionPerformed='getHandler().resetWeightSource()'/> - </JToolBar> - </cell> - </row> - - <!-- count --> - <row> - <cell> - <JLabel id='countLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='count' constructorParams='this'/> - </cell> - </row> - - <!-- sex --> - <row> - <cell> - <JLabel id='sexLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='sex' genericType='ReferentialReference<SexDto>' _entityClass='SexDto.class' constructorParams='this'/> - </cell> - </row> - - <!-- reference pĥoto --> - <row> - <cell> - <JLabel id='picturesReferencesLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <JPanel layout='{new BorderLayout()}'> - <JToolBar id='picturesReferencesToolbar' constraints='BorderLayout.WEST'> - <JButton id='resetPicturesReferences' styleClass='resetButton'/> - </JToolBar> - <JTextField id='picturesReferences' constraints='BorderLayout.CENTER'/> - </JPanel> - </cell> - </row> - - </Table> - - <Table id='extraZone' fill='both' weightx='1' insets='0'> - <row> - <cell weighty='1'> - <JScrollPane id='comment' - onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2' - onKeyReleased='getBean().setComment(comment2.getText())'/> - </JScrollPane> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetSampleUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetSampleUI.jcss deleted file mode 100644 index 73c39f4..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetSampleUI.jcss +++ /dev/null @@ -1,113 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#speciesLabel { - text:"observe.common.speciesFaune"; -} - -#acquisitionModeGroup { - selectedValue:{ModeSaisieEchantillonEnum.valueOf(tableEditBean.getAcquisitionMode())}; -} - -#acquisitionModePanel { - border:{new TitledBorder(t("observe.common.acquisitionMode"))}; - layout:{new GridLayout(1,0)}; -} - -#acquisitionModeEffectif { - buttonGroup:"acquisitionModeGroup"; - value:{ModeSaisieEchantillonEnum.byEffectif}; - text:{ModeSaisieEchantillonEnum.byEffectif.getI18nKey()}; - selected:{tableEditBean.getAcquisitionMode() == 0}; - enabled:{!tableModel.isEditable() || tableModel.isCreate()}; -} - -#acquisitionModeIndividu { - buttonGroup:"acquisitionModeGroup"; - value:{ModeSaisieEchantillonEnum.byIndividu}; - text:{ModeSaisieEchantillonEnum.byIndividu.getI18nKey()}; - selected:{tableEditBean.getAcquisitionMode() == 1}; - enabled:{!tableModel.isEditable() || tableModel.isCreate()}; -} - -#lengthLabel { - text:"observe.common.taille"; -} - -#length { - _validatorLabel:{"observe.common.taille"}; -} - -#countLabel { - text:"observe.common.count"; - labelFor:{count}; -} - -#count { - property:{NonTargetLengthDto.PROPERTY_COUNT}; - model:{tableEditBean.getCount()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; -} - -#sexLabel { - text:"observe.common.sex"; - labelFor:{sex}; -} - -#sex { - property:{NonTargetLengthDto.PROPERTY_SEX}; - selectedItem:{tableEditBean.getSex()}; -} - -#picturesReferencesLabel { - text:"observe.common.picturesReferences"; - labelFor:{picturesReferences}; -} - -#picturesReferences { - text:{getStringValue(tableEditBean.getPicturesReferences())}; - _tablePropertyName:{NonTargetLengthDto.PROPERTY_PICTURES_REFERENCES}; -} - -#resetPicturesReferences{ - toolTipText:"observe.content.action.reset.picturesReferences.tip"; - _resetTablePropertyName:{NonTargetLengthDto.PROPERTY_PICTURES_REFERENCES}; -} - -#speciesTypeTailleLabel{ - actionIcon:"information"; - text:"observe.common.lengthMeasureType"; - labelFor:{speciesTypeTaille}; -} - -#speciesTypeTaille { - font-weight:"bold"; - text:{getSpeciesFauneTypeTaille(tableEditBean.getSpecies())}; -} - -#comment { - columnHeaderView:{new JLabel(t("observe.common.comment.nonTargetSample"))}; -} - -#hideFormInformation { - text:"observe.message.cant.add.nonTargetSample"; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetSampleUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetSampleUIHandler.java deleted file mode 100644 index 14e6920..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetSampleUIHandler.java +++ /dev/null @@ -1,336 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.table.impl.seine; - -import com.google.common.collect.Lists; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.SexDto; -import fr.ird.observe.services.dto.referential.SpeciesDto; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.dto.seine.NonTargetLengthDto; -import fr.ird.observe.services.dto.seine.NonTargetSampleDto; -import fr.ird.observe.services.dto.seine.NonTargetSampleDtos; -import fr.ird.observe.services.dto.seine.SetSeineDto; -import fr.ird.observe.services.service.seine.NonTargetSampleService; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.JComponent; -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; -import java.beans.PropertyChangeListener; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class NonTargetSampleUIHandler extends ContentTableUIHandler<NonTargetSampleDto, NonTargetLengthDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(NonTargetSampleUIHandler.class); - - /** - * Ecoute les modifications de la propriété {@link NonTargetLengthDto#getWeight()}, - * et repasser alors le flag {@link NonTargetLengthDto#isWeightSource()} à - * {@code false}. - * - * @since 3.0 - */ - protected final PropertyChangeListener weightChanged; - - /** - * Ecoute les modifications de la propriété {@link NonTargetLengthDto#getLength()}, - * et repasser alors le flag {@link NonTargetLengthDto#isLengthSource()} à - * {@code false}. - * - * @since 3.0 - */ - protected final PropertyChangeListener lengthChanged; - - public NonTargetSampleUIHandler(NonTargetSampleUI ui) { - super(ui, DataContextType.SetSeine); - weightChanged = evt -> { - NonTargetLengthDto source = (NonTargetLengthDto) evt.getSource(); - source.setWeightSource(false); - }; - lengthChanged = evt -> { - NonTargetLengthDto source = (NonTargetLengthDto) evt.getSource(); - source.setLengthSource(false); - }; - } - - @Override - public NonTargetSampleUI getUi() { - return (NonTargetSampleUI) super.getUi(); - } - - public void resetWeightSource() { - getTableEditBean().setWeightSource(false); - getUi().getWeight().grabFocus(); - } - - public void resetLengthSource() { - getTableEditBean().setLengthSource(false); - getUi().getLength().grabFocus(); - } - - @Override - protected String getEditBeanIdToLoad() { - String id = getDataContext().getSelectedSetId(); - return id; - } - - @SuppressWarnings("unchecked") - @Override - protected void onSelectedRowChanged(int editingRow, - NonTargetLengthDto bean, - boolean create) { - ContentTableModel<NonTargetSampleDto, NonTargetLengthDto> model = getTableModel(); - - if (!model.isEditable()) { - return; - } - - ReferentialReference<SpeciesDto> species = bean.getSpecies(); - NonTargetSampleUI ui = getUi(); - if (log.isDebugEnabled()) { - log.debug("selected species " + species); - } - List<ReferentialReference<SpeciesDto>> availableEspeces; - JComponent requestFocus; - - if (create) { - - if (model.isCreate()) { - - // on passe le mode de saisie en count - ui.getAcquisitionModeGroup().setSelectedValue(null); - ui.getAcquisitionModeGroup().setSelectedValue(ModeSaisieEchantillonEnum.byEffectif); - } - - Set<ReferentialReference<SpeciesDto>> speciesReferences = getModel().getReferentialReferences(NonTargetLengthDto.PROPERTY_SPECIES); - - availableEspeces = Lists.newArrayList(speciesReferences); - requestFocus = ui.getSpecies(); - } else { - - requestFocus = ui.getCount(); - - // on passe le mode de saisie - int acquisitionMode = bean.getAcquisitionMode(); - ModeSaisieEchantillonEnum enumValue = - ModeSaisieEchantillonEnum.valueOf(acquisitionMode); - ui.getAcquisitionModeGroup().setSelectedValue(null); - ui.getAcquisitionModeGroup().setSelectedValue(enumValue); - - availableEspeces = Lists.newArrayList(species); - } - ui.getSpecies().setData(availableEspeces); - requestFocus.requestFocus(); - - NonTargetLengthDto tableEditBean = getTableEditBean(); - tableEditBean.removePropertyChangeListener(NonTargetLengthDto.PROPERTY_WEIGHT, weightChanged); - tableEditBean.addPropertyChangeListener(NonTargetLengthDto.PROPERTY_WEIGHT, weightChanged); - - tableEditBean.removePropertyChangeListener(NonTargetLengthDto.PROPERTY_LENGTH, lengthChanged); - tableEditBean.addPropertyChangeListener(NonTargetLengthDto.PROPERTY_LENGTH, lengthChanged); - } - - @Override - protected void initTableUI(DefaultTableCellRenderer renderer) { - JTable table = getUi().getTable(); - - UIHelper.fixTableColumnWidth(table, 1, 100); - UIHelper.fixTableColumnWidth(table, 2, 100); - - UIHelper.setI18nTableHeaderRenderer( - table, - n("observe.content.nonTargetSample.table.speciesFaune"), - n("observe.content.nonTargetSample.table.speciesFaune.tip"), - n("observe.content.nonTargetSample.table.length"), - n("observe.content.nonTargetSample.table.length.tip"), - n("observe.content.nonTargetSample.table.meanWeight"), - n("observe.content.nonTargetSample.table.meanWeight.tip"), - n("observe.content.nonTargetSample.table.count"), - n("observe.content.nonTargetSample.table.count.tip"), - n("observe.content.nonTargetSample.table.gender"), - n("observe.content.nonTargetSample.table.gender.tip"), - n("observe.content.nonTargetSample.table.picturesReferences"), - n("observe.content.nonTargetSample.table.picturesReferences.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesDto.class)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 4, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SexDto.class)); - UIHelper.setTableColumnRenderer(table, 5, renderer); - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - ContentMode mode = super.getContentMode(dataContext); - - String setId = getDataContext().getSelectedSetId(); - - boolean showData = getNonTargetSampleService().canUseNonTargetSample(setId); - - getUi().getModel().setShowData(showData); - - if (mode == ContentMode.UPDATE && !showData) { - - // on repasse en mode resteint car on ne peut pas éditer l'écran - mode = ContentMode.READ; - - addMessage(getUi(), - NuitonValidatorScope.INFO, - getEntityLabel(SetSeineDto.class), - t("observe.content.setSeine.message.no.nonTargetDiscarded")); - } - return mode; - } - - /** - * Le mode de saisie a été mis à jour. - * - * @param newMode le nouveau de mode de saisie à utiliser - * @since 3.0 - */ - public void updateModeSaisie(ModeSaisieEchantillonEnum newMode) { - - if (log.isDebugEnabled()) { - log.debug("Change mode saisie to " + newMode); - } - if (newMode == null) { - - // mode null (cela peut arriver avec les bindings) - return; - } - - NonTargetSampleUI ui = getUi(); - - boolean createMode = ui.getTableModel().isCreate(); - - NonTargetLengthDto editBean = ui.getTableEditBean(); - switch (newMode) { - - case byEffectif: - - // le weight n'est pas modifiable - ui.getWeight().setEnabled(false); - - // l'count est modifiable - ui.getCount().setEnabled(true); - - if (createMode) { - - // on supprime le weight (si il a été saisie) - editBean.setWeight(null); - // on supprime aussi l'count (pour forcer la saisie) - editBean.setCount(null); - } - break; - - case byIndividu: - - // le weight est pas modifiable - ui.getWeight().setEnabled(true); - - // l'count n'est pas modifiable et est toujours de 1 - ui.getCount().setEnabled(false); - - - if (createMode) { - - // on positionne l'count à 1 (seule valeur possible) - editBean.setCount(1); - } - break; - } - - if (createMode) { - - // on propage le mode de saisie dans le bean - editBean.setAcquisitionMode(newMode.ordinal()); - } - } - - @Override - protected void doPersist(NonTargetSampleDto bean) { - - SaveResultDto saveResult = getNonTargetSampleService().save(getSelectedParentId(), bean); - saveResult.toDto(bean); - - } - - @Override - protected void loadEditBean(String beanId) { - Form<NonTargetSampleDto> form = getNonTargetSampleService().loadForm(beanId); - loadReferentialReferenceSetsInModel(form); - getModel().setForm(form); - NonTargetSampleDtos.copyNonTargetSampleDto(form.getObject(), getBean()); - } - - @Override - protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { - - Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); - - switch (propertyName) { - - case NonTargetLengthDto.PROPERTY_SPECIES: { - - result = (Collection) getNonTargetSampleService().getSampleSpecies(getSelectedParentId()); - - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - } - - break; - - } - - return result; - - } - - protected NonTargetSampleService getNonTargetSampleService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newNonTargetSampleService(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetSampleUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetSampleUIModel.java deleted file mode 100644 index 9aa7bd6..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/NonTargetSampleUIModel.java +++ /dev/null @@ -1,106 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import fr.ird.observe.services.dto.seine.NonTargetLengthDto; -import fr.ird.observe.services.dto.seine.NonTargetLengthDtos; -import fr.ird.observe.services.dto.seine.NonTargetSampleDto; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; - -import java.util.Collection; -import java.util.List; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class NonTargetSampleUIModel extends ContentTableUIModel<NonTargetSampleDto, NonTargetLengthDto> { - - private static final long serialVersionUID = 1L; - - public NonTargetSampleUIModel(NonTargetSampleUI ui) { - - super(NonTargetSampleDto.class, - NonTargetLengthDto.class, - new String[]{ - NonTargetSampleDto.PROPERTY_NON_TARGET_LENGTH, - NonTargetSampleDto.PROPERTY_COMMENT}, - new String[]{NonTargetLengthDto.PROPERTY_SPECIES, - NonTargetLengthDto.PROPERTY_LENGTH, - NonTargetLengthDto.PROPERTY_LENGTH_SOURCE, - NonTargetLengthDto.PROPERTY_WEIGHT, - NonTargetLengthDto.PROPERTY_WEIGHT_SOURCE, - NonTargetLengthDto.PROPERTY_SEX, - NonTargetLengthDto.PROPERTY_COUNT, - NonTargetLengthDto.PROPERTY_ACQUISITION_MODE, - NonTargetLengthDto.PROPERTY_PICTURES_REFERENCES - }); - - List<ContentTableMeta<NonTargetLengthDto>> metas = Lists.newArrayList( - ContentTableModel.newTableMeta(NonTargetLengthDto.class, NonTargetLengthDto.PROPERTY_SPECIES, false), - ContentTableModel.newTableMeta(NonTargetLengthDto.class, NonTargetLengthDto.PROPERTY_LENGTH, false), - ContentTableModel.newTableMeta(NonTargetLengthDto.class, NonTargetLengthDto.PROPERTY_WEIGHT, false), - ContentTableModel.newTableMeta(NonTargetLengthDto.class, NonTargetLengthDto.PROPERTY_COUNT, false), - new ContentTableMeta<NonTargetLengthDto>(NonTargetLengthDto.class, NonTargetLengthDto.PROPERTY_SEX, false) { - - private static final long serialVersionUID = 1L; - - @Override - public boolean isNullValue(ContentTableModel<?, ?> m, NonTargetLengthDto bean, int row) { - return bean.getSex() != null; - } - }, - ContentTableModel.newTableMeta(NonTargetLengthDto.class, NonTargetLengthDto.PROPERTY_PICTURES_REFERENCES, false)); - - initModel(ui, metas); - - } - - @Override - protected ContentTableModel<NonTargetSampleDto, NonTargetLengthDto> createTableModel(ObserveContentTableUI<NonTargetSampleDto, NonTargetLengthDto> ui, List<ContentTableMeta<NonTargetLengthDto>> contentTableMetas) { - return new ContentTableModel<NonTargetSampleDto, NonTargetLengthDto>(ui, contentTableMetas) { - private static final long serialVersionUID = 1L; - @Override - protected Collection<NonTargetLengthDto> getChilds(NonTargetSampleDto bean) { - return bean.getNonTargetLength(); - } - - @Override - protected void load(NonTargetLengthDto source, NonTargetLengthDto target) { - NonTargetLengthDtos.copyNonTargetLengthDto(source, target); - } - - @Override - protected void setChilds(NonTargetSampleDto parent, List<NonTargetLengthDto> childs) { - parent.setNonTargetLength(Sets.newLinkedHashSet(childs)); - } - }; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectObservedSpeciesUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectObservedSpeciesUI.jaxx deleted file mode 100644 index c82527f..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectObservedSpeciesUI.jaxx +++ /dev/null @@ -1,125 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.table.ContentTableUI - superGenericType='FloatingObjectObservedSpeciesDto, ObjectObservedSpeciesDto' - contentTitle='{n("observe.common.objectObservedSpecies")}' - saveNewEntryText='{n("observe.content.action.create.objectObservedSpecies")}' - saveNewEntryTip='{n("observe.content.action.create.objectObservedSpecies.tip")}'> - - <style source="../../CommonTable.jcss"/> - - <import> - fr.ird.observe.services.dto.CommentableDto - fr.ird.observe.services.dto.seine.FloatingObjectObservedSpeciesDto - fr.ird.observe.services.dto.seine.ObjectObservedSpeciesDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.SpeciesDto - fr.ird.observe.services.dto.referential.seine.SpeciesStatusDto - fr.ird.observe.ui.content.table.* - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - java.awt.Dimension - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <ObjectObservedSpeciesUIHandler id='handler' constructorParams='this'/> - - <!-- model --> - <ObjectObservedSpeciesUIModel id='model' constructorParams='this'/> - - <!-- edit bean --> - <FloatingObjectObservedSpeciesDto id='bean'/> - - <!-- table edit bean --> - <ObjectObservedSpeciesDto id='tableEditBean'/> - - <!-- table model --> - <ContentTableModel id='tableModel'/> - - <!-- le validateur de l'écran --> - <BeanValidator id='validator' - autoField='true' - beanClass='fr.ird.observe.services.dto.seine.FloatingObjectObservedSpeciesDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update'/> - - <!-- le validateur d'une entrée de tableau --> - <BeanValidator id='validatorTable' - autoField='true' - beanClass='fr.ird.observe.services.dto.seine.ObjectObservedSpeciesDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update'/> - - <Table id='editorPanel' fill='both' insets='1'> - - <!-- species faune --> - <row> - <cell> - <JLabel id='speciesLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='species' constructorParams='this' - genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class'/> - </cell> - </row> - - <!-- statut species --> - <row> - <cell> - <JLabel id='speciesStatusLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='speciesStatus' constructorParams='this' - genericType='ReferentialReference<SpeciesStatusDto>' _entityClass='SpeciesStatusDto.class'/> - </cell> - </row> - - <!-- count --> - <row> - <cell> - <JLabel id='countLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='count' constructorParams='this'/> - </cell> - </row> - </Table> - - <Table id='extraZone' fill='both' weightx='1' insets='0'> - <row> - <cell weighty='1'> - <JScrollPane id='comment' - onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2' - onKeyReleased='getBean().setComment(comment2.getText())'/> - </JScrollPane> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectObservedSpeciesUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectObservedSpeciesUI.jcss deleted file mode 100644 index 3227180..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectObservedSpeciesUI.jcss +++ /dev/null @@ -1,61 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#speciesLabel { - text:"observe.common.speciesFaune"; - labelFor:{species}; -} - -#species { - property:{ObjectObservedSpeciesDto.PROPERTY_SPECIES}; - selectedItem:{tableEditBean.getSpecies()}; -} - -#speciesStatusLabel { - text:"observe.common.speciesStatus"; - labelFor:{speciesStatus}; -} - -#speciesStatus { - property:{ObjectObservedSpeciesDto.PROPERTY_SPECIES_STATUS}; - selectedItem:{tableEditBean.getSpeciesStatus()}; -} - -#countLabel { - text:"observe.common.count"; - labelFor:{count}; -} - -#count { - property:{ObjectObservedSpeciesDto.PROPERTY_COUNT}; - model:{tableEditBean.getCount()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; -} - -#comment { - columnHeaderView:{new JLabel(t("observe.common.comment.floatingObject"))}; - minimumSize:{new Dimension(10,80)}; -} - -#comment2 { - text:{getStringValue(bean.getComment())}; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectObservedSpeciesUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectObservedSpeciesUIHandler.java deleted file mode 100644 index b105219..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectObservedSpeciesUIHandler.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.table.impl.seine; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.ReferentialReferences; -import fr.ird.observe.services.dto.referential.SpeciesDto; -import fr.ird.observe.services.dto.referential.SpeciesListDto; -import fr.ird.observe.services.dto.referential.seine.SpeciesStatusDto; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.dto.seine.FloatingObjectObservedSpeciesDto; -import fr.ird.observe.services.dto.seine.FloatingObjectObservedSpeciesDtos; -import fr.ird.observe.services.dto.seine.ObjectObservedSpeciesDto; -import fr.ird.observe.services.dto.seine.ObjectSchoolEstimateDto; -import fr.ird.observe.services.service.ReferentialService; -import fr.ird.observe.services.service.seine.ObjectObservedSpeciesService; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.table.ContentTableUIHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; -import java.util.Collection; -import java.util.LinkedList; -import java.util.Set; - -import static org.nuiton.i18n.I18n.n; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class ObjectObservedSpeciesUIHandler extends ContentTableUIHandler<FloatingObjectObservedSpeciesDto, ObjectObservedSpeciesDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(ObjectObservedSpeciesUIHandler.class); - - public ObjectObservedSpeciesUIHandler(ObjectObservedSpeciesUI ui) { - super(ui, DataContextType.SetSeine); - } - - @Override - public ObjectObservedSpeciesUI getUi() { - return (ObjectObservedSpeciesUI) super.getUi(); - } - - @Override - protected String getEditBeanIdToLoad() { - return getDataContext().getSelectedFloatingObjectId(); - } - - @Override - protected void onSelectedRowChanged(int editingRow, ObjectObservedSpeciesDto bean, boolean create) { - if (log.isDebugEnabled()) { - log.debug("Row has changed to " + editingRow); - } - if (getTableModel().isEditable()) { - getUi().getSpecies().requestFocus(); - } - } - - @Override - protected void initTableUI(DefaultTableCellRenderer renderer) { - JTable table = getUi().getTable(); - - UIHelper.setI18nTableHeaderRenderer(table, - n("observe.content.objectObservedSpecies.table.speciesFaune"), - n("observe.content.objectObservedSpecies.table.speciesFaune.tip"), - n("observe.content.objectObservedSpecies.table.speciesStatus"), - n("observe.content.objectObservedSpecies.table.speciesStatus.tip"), - n("observe.content.objectObservedSpecies.table.count"), - n("observe.content.objectObservedSpecies.table.count.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesDto.class)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesStatusDto.class)); - UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - } - - @Override - protected void doPersist(FloatingObjectObservedSpeciesDto bean) { - - SaveResultDto saveResult = getObjectObservedSpeciesService().save(bean); - saveResult.toDto(bean); - - } - - @Override - protected void loadEditBean(String beanId) { - Form<FloatingObjectObservedSpeciesDto> form = getObjectObservedSpeciesService().loadForm(beanId); - loadReferentialReferenceSetsInModel(form); - getModel().setForm(form); - FloatingObjectObservedSpeciesDtos.copyFloatingObjectObservedSpeciesDto(form.getObject(), getBean()); - } - - @Override - protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { - - Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); - - switch (propertyName) { - - case ObjectSchoolEstimateDto.PROPERTY_SPECIES: { - String speciesListId = ObserveSwingApplicationContext.get().getConfig().getSpeciesListSeineObjectObservedSpeciesId(); - - ReferentialService referentialService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newReferentialService(); - Form<SpeciesListDto> speciesListDtoForm = referentialService.loadForm(SpeciesListDto.class, speciesListId); - SpeciesListDto speciesListDto = speciesListDtoForm.getObject(); - - Set<String> speciesIds = speciesListDto.getSpeciesIds(); - - result = ReferentialReferences.filterContains(result, speciesIds); - - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - } - - break; - - } - - return result; - - } - - protected ObjectObservedSpeciesService getObjectObservedSpeciesService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newObjectObservedSpeciesService(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectObservedSpeciesUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectObservedSpeciesUIModel.java deleted file mode 100644 index 7e802f3..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectObservedSpeciesUIModel.java +++ /dev/null @@ -1,92 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import fr.ird.observe.services.dto.seine.FloatingObjectObservedSpeciesDto; -import fr.ird.observe.services.dto.seine.ObjectObservedSpeciesDto; -import fr.ird.observe.services.dto.seine.ObjectObservedSpeciesDtos; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; - -import java.util.Collection; -import java.util.List; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ObjectObservedSpeciesUIModel extends ContentTableUIModel<FloatingObjectObservedSpeciesDto, ObjectObservedSpeciesDto> { - - private static final long serialVersionUID = 1L; - - public ObjectObservedSpeciesUIModel(ObjectObservedSpeciesUI ui) { - - super(FloatingObjectObservedSpeciesDto.class, - ObjectObservedSpeciesDto.class, - new String[]{ - FloatingObjectObservedSpeciesDto.PROPERTY_OBJECT_OBSERVED_SPECIES, - FloatingObjectObservedSpeciesDto.PROPERTY_COMMENT}, - new String[]{ - ObjectObservedSpeciesDto.PROPERTY_SPECIES, - ObjectObservedSpeciesDto.PROPERTY_SPECIES_STATUS, - ObjectObservedSpeciesDto.PROPERTY_COUNT} - ); - - List<ContentTableMeta<ObjectObservedSpeciesDto>> metas = Lists.newArrayList( - ContentTableModel.newTableMeta(ObjectObservedSpeciesDto.class, ObjectObservedSpeciesDto.PROPERTY_SPECIES, false), - ContentTableModel.newTableMeta(ObjectObservedSpeciesDto.class, ObjectObservedSpeciesDto.PROPERTY_SPECIES_STATUS, false), - ContentTableModel.newTableMeta(ObjectObservedSpeciesDto.class, ObjectObservedSpeciesDto.PROPERTY_COUNT, false)); - - initModel(ui, metas); - - } - - @Override - protected ContentTableModel<FloatingObjectObservedSpeciesDto, ObjectObservedSpeciesDto> createTableModel( - ObserveContentTableUI<FloatingObjectObservedSpeciesDto, ObjectObservedSpeciesDto> ui, - List<ContentTableMeta<ObjectObservedSpeciesDto>> contentTableMetas) { - - return new ContentTableModel<FloatingObjectObservedSpeciesDto, ObjectObservedSpeciesDto>(ui, contentTableMetas) { - private static final long serialVersionUID = 1L; - @Override - protected Collection<ObjectObservedSpeciesDto> getChilds(FloatingObjectObservedSpeciesDto bean) { - return bean.getObjectObservedSpecies(); - } - - @Override - protected void load(ObjectObservedSpeciesDto source, ObjectObservedSpeciesDto target) { - ObjectObservedSpeciesDtos.copyObjectObservedSpeciesDto(source, target); - } - - @Override - protected void setChilds(FloatingObjectObservedSpeciesDto parent, List<ObjectObservedSpeciesDto> childs) { - bean.setObjectObservedSpecies(childs); - } - }; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectSchoolEstimateUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectSchoolEstimateUI.jaxx deleted file mode 100644 index 55f0fc6..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectSchoolEstimateUI.jaxx +++ /dev/null @@ -1,113 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.table.ContentTableUI - superGenericType='FloatingObjectSchoolEstimateDto, ObjectSchoolEstimateDto' - contentTitle='{n("observe.common.schoolEstimate")}' - saveNewEntryText='{n("observe.content.action.create.schoolEstimate")}' - saveNewEntryTip='{n("observe.content.action.create.schoolEstimate.tip")}'> - - <style source="../../CommonTable.jcss"/> - - <import> - fr.ird.observe.services.dto.CommentableDto - fr.ird.observe.services.dto.seine.FloatingObjectSchoolEstimateDto - fr.ird.observe.services.dto.seine.ObjectSchoolEstimateDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.SpeciesDto - fr.ird.observe.ui.content.table.* - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - java.awt.Dimension - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <ObjectSchoolEstimateUIHandler id='handler' constructorParams='this'/> - - <!-- model --> - <ObjectSchoolEstimateUIModel id='model' constructorParams='this'/> - - <!-- edit bean --> - <FloatingObjectSchoolEstimateDto id='bean'/> - - <!-- table edit bean --> - <ObjectSchoolEstimateDto id='tableEditBean'/> - - <!-- table model --> - <ContentTableModel id='tableModel'/> - - <!-- le validateur de l'écran --> - <BeanValidator id='validator' - autoField='true' - beanClass='fr.ird.observe.services.dto.seine.FloatingObjectSchoolEstimateDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update'/> - - <!-- le validateur d'une entrée de tableau --> - <BeanValidator id='validatorTable' - autoField='true' - beanClass='fr.ird.observe.services.dto.seine.ObjectSchoolEstimateDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update'/> - - <Table id='editorPanel' fill='both' insets='1'> - - <!-- species --> - <row> - <cell> - <JLabel id='speciesLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='species' constructorParams='this' - genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class'/> - </cell> - </row> - - <!-- weight --> - <row> - <cell> - <JLabel id='totalWeightLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='totalWeight' constructorParams='this'/> - </cell> - </row> - </Table> - - <Table id='extraZone' fill='both' weightx='1' insets='1'> - <row> - <cell weighty='1'> - <JScrollPane id='comment' - onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2' - onKeyReleased='getBean().setComment(comment2.getText())'/> - </JScrollPane> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectSchoolEstimateUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectSchoolEstimateUI.jcss deleted file mode 100644 index 15d53f7..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectSchoolEstimateUI.jcss +++ /dev/null @@ -1,51 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#speciesLabel { - text:"observe.common.speciesThon"; - labelFor:{species}; -} - -#species { - property:{ObjectSchoolEstimateDto.PROPERTY_SPECIES}; - selectedItem:{tableEditBean.getSpecies()}; -} - -#totalWeightLabel { - text:"observe.common.totalWeight"; - labelFor:{totalWeight}; -} - -#totalWeight { - property:{ObjectSchoolEstimateDto.PROPERTY_TOTAL_WEIGHT}; - model:{tableEditBean.getTotalWeight()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; -} - -#comment { - columnHeaderView:{new JLabel(t("observe.common.comment.floatingObject"))}; - minimumSize:{new Dimension(10,80)}; -} - -#comment2 { - text:{getStringValue(bean.getComment())}; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectSchoolEstimateUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectSchoolEstimateUIHandler.java deleted file mode 100644 index a5bc97d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectSchoolEstimateUIHandler.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.table.impl.seine; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.ReferentialReferences; -import fr.ird.observe.services.dto.referential.SpeciesDto; -import fr.ird.observe.services.dto.referential.SpeciesListDto; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.dto.seine.FloatingObjectSchoolEstimateDto; -import fr.ird.observe.services.dto.seine.FloatingObjectSchoolEstimateDtos; -import fr.ird.observe.services.dto.seine.ObjectSchoolEstimateDto; -import fr.ird.observe.services.service.ReferentialService; -import fr.ird.observe.services.service.seine.ObjectSchoolEstimateService; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.table.ContentTableUIHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; -import java.util.Collection; -import java.util.LinkedList; -import java.util.Set; - -import static org.nuiton.i18n.I18n.n; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class ObjectSchoolEstimateUIHandler extends ContentTableUIHandler<FloatingObjectSchoolEstimateDto, ObjectSchoolEstimateDto> { - - - /** Logger */ - private static final Log log = LogFactory.getLog(ObjectSchoolEstimateUIHandler.class); - - public ObjectSchoolEstimateUIHandler(ObjectSchoolEstimateUI ui) { - super(ui, DataContextType.SetSeine); - } - - @Override - public ObjectSchoolEstimateUI getUi() { - return (ObjectSchoolEstimateUI) super.getUi(); - } - - @Override - protected void onSelectedRowChanged(int editingRow, ObjectSchoolEstimateDto bean, boolean create) { - if (getTableModel().isEditable()) { - if (log.isDebugEnabled()) { - log.debug("Row has changed to " + editingRow); - } - getUi().getSpecies().requestFocus(); - } - } - - @Override - protected String getEditBeanIdToLoad() { - return getDataContext().getSelectedFloatingObjectId(); - } - - @Override - protected void initTableUI(DefaultTableCellRenderer renderer) { - JTable table = getUi().getTable(); - - UIHelper.setI18nTableHeaderRenderer(table, - n("observe.content.schoolEstimate.table.speciesThon"), - n("observe.content.schoolEstimate.table.speciesThon.tip"), - n("observe.content.schoolEstimate.table.weight"), - n("observe.content.schoolEstimate.table.weight.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesDto.class)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - } - - @Override - protected void doPersist(FloatingObjectSchoolEstimateDto bean) { - - SaveResultDto saveResult = getObjectSchoolEstimateService().save(bean); - saveResult.toDto(bean); - - } - - @Override - protected void loadEditBean(String beanId) { - Form<FloatingObjectSchoolEstimateDto> form = getObjectSchoolEstimateService().loadForm(beanId); - loadReferentialReferenceSetsInModel(form); - getModel().setForm(form); - FloatingObjectSchoolEstimateDtos.copyFloatingObjectSchoolEstimateDto(form.getObject(), getBean()); - } - - @Override - protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { - - Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); - - switch (propertyName) { - - case ObjectSchoolEstimateDto.PROPERTY_SPECIES: { - String speciesListId = ObserveSwingApplicationContext.get().getConfig().getSpeciesListSeineObjectSchoolEstimateId(); - - ReferentialService referentialService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newReferentialService(); - Form<SpeciesListDto> speciesListDtoForm = referentialService.loadForm(SpeciesListDto.class, speciesListId); - SpeciesListDto speciesListDto = speciesListDtoForm.getObject(); - - Set<String> speciesIds = speciesListDto.getSpeciesIds(); - result = ReferentialReferences.filterContains(result, speciesIds); - - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - } - - break; - - } - - return result; - - } - - protected ObjectSchoolEstimateService getObjectSchoolEstimateService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newObjectSchoolEstimateService(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectSchoolEstimateUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectSchoolEstimateUIModel.java deleted file mode 100644 index 5456579..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/ObjectSchoolEstimateUIModel.java +++ /dev/null @@ -1,90 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import fr.ird.observe.services.dto.seine.FloatingObjectSchoolEstimateDto; -import fr.ird.observe.services.dto.seine.ObjectSchoolEstimateDto; -import fr.ird.observe.services.dto.seine.ObjectSchoolEstimateDtos; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; - -import java.util.Collection; -import java.util.List; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class ObjectSchoolEstimateUIModel extends ContentTableUIModel<FloatingObjectSchoolEstimateDto, ObjectSchoolEstimateDto> { - - private static final long serialVersionUID = 1L; - - public ObjectSchoolEstimateUIModel(ObjectSchoolEstimateUI ui) { - - super(FloatingObjectSchoolEstimateDto.class, - ObjectSchoolEstimateDto.class, - new String[]{ - FloatingObjectSchoolEstimateDto.PROPERTY_OBJECT_SCHOOL_ESTIMATE, - FloatingObjectSchoolEstimateDto.PROPERTY_COMMENT}, - new String[]{ - ObjectSchoolEstimateDto.PROPERTY_SPECIES, - ObjectSchoolEstimateDto.PROPERTY_TOTAL_WEIGHT} - ); - - List<ContentTableMeta<ObjectSchoolEstimateDto>> metas = Lists.newArrayList( - ContentTableModel.newTableMeta(ObjectSchoolEstimateDto.class, ObjectSchoolEstimateDto.PROPERTY_SPECIES, false), - ContentTableModel.newTableMeta(ObjectSchoolEstimateDto.class, ObjectSchoolEstimateDto.PROPERTY_TOTAL_WEIGHT, false)); - - initModel(ui, metas); - - } - - @Override - protected ContentTableModel<FloatingObjectSchoolEstimateDto, ObjectSchoolEstimateDto> createTableModel( - ObserveContentTableUI<FloatingObjectSchoolEstimateDto, ObjectSchoolEstimateDto> ui, - List<ContentTableMeta<ObjectSchoolEstimateDto>> contentTableMetas) { - - return new ContentTableModel<FloatingObjectSchoolEstimateDto, ObjectSchoolEstimateDto>(ui, contentTableMetas) { - private static final long serialVersionUID = 1L; - @Override - protected Collection<ObjectSchoolEstimateDto> getChilds(FloatingObjectSchoolEstimateDto bean) { - return bean.getObjectSchoolEstimate(); - } - - @Override - protected void load(ObjectSchoolEstimateDto source, ObjectSchoolEstimateDto target) { - ObjectSchoolEstimateDtos.copyObjectSchoolEstimateDto(source, target); - } - - @Override - protected void setChilds(FloatingObjectSchoolEstimateDto parent, List<ObjectSchoolEstimateDto> childs) { - parent.setObjectSchoolEstimate(childs); - } - }; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/SchoolEstimateUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/SchoolEstimateUI.jaxx deleted file mode 100644 index c08ee1b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/SchoolEstimateUI.jaxx +++ /dev/null @@ -1,129 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.table.ContentTableUI - superGenericType='SetSeineSchoolEstimateDto, SchoolEstimateDto' - - - contentTitle='{n("observe.common.schoolEstimate")}' - saveNewEntryText='{n("observe.content.action.create.schoolEstimate")}' - saveNewEntryTip='{n("observe.content.action.create.schoolEstimate.tip")}'> - - <style source="../../CommonTable.jcss"/> - - <import> - fr.ird.observe.services.dto.CommentableDto - fr.ird.observe.services.dto.seine.SetSeineSchoolEstimateDto - fr.ird.observe.services.dto.seine.SchoolEstimateDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.SpeciesDto - fr.ird.observe.ui.content.table.* - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - java.awt.Dimension - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <SchoolEstimateUIHandler id='handler' constructorParams='this'/> - - <!-- model --> - <SchoolEstimateUIModel id='model' constructorParams='this'/> - - <!-- edit bean --> - <SetSeineSchoolEstimateDto id='bean'/> - - <!-- table edit bean --> - <SchoolEstimateDto id='tableEditBean'/> - - <!-- table model --> - <ContentTableModel id='tableModel'/> - - <!-- le validateur de l'écran --> - <BeanValidator id='validator' - autoField='true' - beanClass='fr.ird.observe.services.dto.seine.SetSeineSchoolEstimateDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update'> - <!-- clef unique --> - <field name="schoolEstimate" component="editorPanel"/> - </BeanValidator> - - <!-- le validateur d'une entrée de tableau --> - <BeanValidator id='validatorTable' - autoField='true' - beanClass='fr.ird.observe.services.dto.seine.SchoolEstimateDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update'/> - - <!-- formulaire --> - <Table id='editorPanel' fill='both' insets='1'> - - <!-- species --> - <row> - <cell> - <JLabel id='speciesLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='species' genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class' - constructorParams='this'/> - </cell> - </row> - - <!-- weight --> - <row> - <cell> - <JLabel id='totalWeightLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='totalWeight' constructorParams='this'/> - </cell> - </row> - - <!-- mean weight --> - <row> - <cell> - <JLabel id='meanWeightLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='meanWeight' constructorParams='this'/> - </cell> - </row> - </Table> - - <Table id='extraZone' fill='both' weightx='1' insets='1'> - <row> - <cell weighty='1'> - <JScrollPane id='comment' - onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2' - onKeyReleased='getBean().setComment(comment2.getText())'/> - </JScrollPane> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/SchoolEstimateUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/SchoolEstimateUI.jcss deleted file mode 100644 index 221c0b9..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/SchoolEstimateUI.jcss +++ /dev/null @@ -1,64 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#speciesLabel { - text:"observe.common.speciesThon"; - labelFor:{species}; - toolTipText:"observe.content.schoolEstimate.table.speciesThon.tip"; -} - -#species { - property:{SchoolEstimateDto.PROPERTY_SPECIES}; - selectedItem:{tableEditBean.getSpecies()}; - enabled:{!tableModel.isEditable() || !model.isRowSaved()}; -} - -#totalWeightLabel { - text:"observe.common.weight"; - labelFor:{totalWeight}; -} - -#totalWeight { - property:{SchoolEstimateDto.PROPERTY_TOTAL_WEIGHT}; - model:{tableEditBean.getTotalWeight()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_7_DIGITS_PATTERN}; -} - -#meanWeightLabel { - text:"observe.common.meanWeight"; - labelFor:{meanWeight}; -} - -#meanWeight { - property:{SchoolEstimateDto.PROPERTY_MEAN_WEIGHT}; - model:{tableEditBean.getMeanWeight()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; -} - -#comment { - columnHeaderView:{new JLabel(t("observe.common.comment.set"))}; - minimumSize:{new Dimension(10,80)}; -} - -#comment2 { - text:{getStringValue(bean.getComment())}; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/SchoolEstimateUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/SchoolEstimateUIHandler.java deleted file mode 100644 index c52f94e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/SchoolEstimateUIHandler.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.table.impl.seine; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.ReferentialReferences; -import fr.ird.observe.services.dto.referential.SpeciesDto; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.dto.seine.ObjectSchoolEstimateDto; -import fr.ird.observe.services.dto.seine.SchoolEstimateDto; -import fr.ird.observe.services.dto.seine.SetSeineSchoolEstimateDto; -import fr.ird.observe.services.dto.seine.SetSeineSchoolEstimateDtos; -import fr.ird.observe.services.service.seine.SchoolEstimateService; -import fr.ird.observe.services.service.seine.TripSeineService; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JComponent; -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; -import java.util.stream.Collectors; - -import static org.nuiton.i18n.I18n.n; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class SchoolEstimateUIHandler extends ContentTableUIHandler<SetSeineSchoolEstimateDto, SchoolEstimateDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(SchoolEstimateUIHandler.class); - - public SchoolEstimateUIHandler(SchoolEstimateUI ui) { - super(ui, DataContextType.SetSeine); - } - - @Override - public SchoolEstimateUI getUi() { - return (SchoolEstimateUI) super.getUi(); - } - - @Override - protected String getEditBeanIdToLoad() { - return getDataContext().getSelectedSetId(); - } - - @Override - protected void onSelectedRowChanged(int editingRow, SchoolEstimateDto bean, boolean create) { - - ContentTableModel<SetSeineSchoolEstimateDto, SchoolEstimateDto> model = getTableModel(); - - if (!model.isEditable()) { - - // rien a faire - return; - } - - SchoolEstimateUI ui = getUi(); - List<ReferentialReference<SpeciesDto>> availableEspeces; - JComponent requestFocus; - - if (create) { - Set<ReferentialReference<SpeciesDto>> references = getModel().getReferentialReferences(SchoolEstimateDto.PROPERTY_SPECIES); - - List<ReferentialReference<SpeciesDto>> listSpeciesUsed = model.getColumnValues(0); - - Set<String> listSpeciesIdUsed = listSpeciesUsed.stream().map(ReferentialReference::getId).collect(Collectors.toSet()); - - availableEspeces = ReferentialReferences.filterNotContains(references,listSpeciesIdUsed); - - requestFocus = ui.getSpecies(); - } else { - ReferentialReference<SpeciesDto> species = bean.getSpecies(); - availableEspeces = Collections.singletonList(species); - requestFocus = ui.getTotalWeight(); - } - ui.getSpecies().setData(availableEspeces); - requestFocus.requestFocus(); - } - - @Override - protected void initTableUI(DefaultTableCellRenderer renderer) { - JTable table = getUi().getTable(); - - UIHelper.setI18nTableHeaderRenderer( - table, - n("observe.content.schoolEstimate.table.speciesThon"), - n("observe.content.schoolEstimate.table.speciesThon.tip"), - n("observe.content.schoolEstimate.table.weight"), - n("observe.content.schoolEstimate.table.weight.tip"), - n("observe.content.schoolEstimate.table.meanWeight"), - n("observe.content.schoolEstimate.table.meanWeight.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesDto.class)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - } - - @Override - protected void doPersist(SetSeineSchoolEstimateDto bean) { - - SaveResultDto saveResult = getSchoolEstimateService().save(bean); - saveResult.toDto(bean); - } - - @Override - protected void loadEditBean(String beanId) { - Form<SetSeineSchoolEstimateDto> form = getSchoolEstimateService().loadForm(beanId); - loadReferentialReferenceSetsInModel(form); - getModel().setForm(form); - SetSeineSchoolEstimateDtos.copySetSeineSchoolEstimateDto(form.getObject(), getBean()); - } - - @Override - protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { - - Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); - - switch (propertyName) { - - case ObjectSchoolEstimateDto.PROPERTY_SPECIES: { - - String speciesListId = ObserveSwingApplicationContext.get().getConfig().getSpeciesListSeineSchoolEstimateId(); - String tripSeineId = getDataContext().getSelectedTripSeineId(); - - TripSeineService tripSeineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripSeineService(); - result = (List) tripSeineService.getSpeciesByListAndTrip(tripSeineId, speciesListId); - - result = ReferentialReferences.filterEnabled(result); - - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - } - - break; - - } - - return result; - - } - - protected SchoolEstimateService getSchoolEstimateService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newSchoolEstimateService(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/SchoolEstimateUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/SchoolEstimateUIModel.java deleted file mode 100644 index 286062a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/SchoolEstimateUIModel.java +++ /dev/null @@ -1,92 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import fr.ird.observe.services.dto.seine.SchoolEstimateDto; -import fr.ird.observe.services.dto.seine.SchoolEstimateDtos; -import fr.ird.observe.services.dto.seine.SetSeineSchoolEstimateDto; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; - -import java.util.Collection; -import java.util.List; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class SchoolEstimateUIModel extends ContentTableUIModel<SetSeineSchoolEstimateDto, SchoolEstimateDto> { - - private static final long serialVersionUID = 1L; - - public SchoolEstimateUIModel(SchoolEstimateUI ui) { - - super(SetSeineSchoolEstimateDto.class, - SchoolEstimateDto.class, - new String[]{ - SetSeineSchoolEstimateDto.PROPERTY_SCHOOL_ESTIMATE, - SetSeineSchoolEstimateDto.PROPERTY_COMMENT}, - new String[]{ - SchoolEstimateDto.PROPERTY_SPECIES, - SchoolEstimateDto.PROPERTY_TOTAL_WEIGHT, - SchoolEstimateDto.PROPERTY_MEAN_WEIGHT} - ); - - List<ContentTableMeta<SchoolEstimateDto>> metas = Lists.newArrayList( - ContentTableModel.newTableMeta(SchoolEstimateDto.class, SchoolEstimateDto.PROPERTY_SPECIES, false), - ContentTableModel.newTableMeta(SchoolEstimateDto.class, SchoolEstimateDto.PROPERTY_TOTAL_WEIGHT, false), - ContentTableModel.newTableMeta(SchoolEstimateDto.class, SchoolEstimateDto.PROPERTY_MEAN_WEIGHT, false)); - - initModel(ui, metas); - - } - - @Override - protected ContentTableModel<SetSeineSchoolEstimateDto, SchoolEstimateDto> createTableModel( - ObserveContentTableUI<SetSeineSchoolEstimateDto, SchoolEstimateDto> ui, - List<ContentTableMeta<SchoolEstimateDto>> contentTableMetas) { - - return new ContentTableModel<SetSeineSchoolEstimateDto, SchoolEstimateDto>(ui, contentTableMetas) { - private static final long serialVersionUID = 1L; - @Override - protected Collection<SchoolEstimateDto> getChilds(SetSeineSchoolEstimateDto bean) { - return bean.getSchoolEstimate(); - } - - @Override - protected void load(SchoolEstimateDto source, SchoolEstimateDto target) { - SchoolEstimateDtos.copySchoolEstimateDto(source, target); - } - - @Override - protected void setChilds(SetSeineSchoolEstimateDto parent, List<SchoolEstimateDto> childs) { - bean.setSchoolEstimate(childs); - } - }; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetCatchUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetCatchUI.jaxx deleted file mode 100644 index 006aa0d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetCatchUI.jaxx +++ /dev/null @@ -1,141 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.table.ContentTableUI - superGenericType='SetSeineTargetCatchDto, TargetCatchDto' - contentTitle='{n("observe.common.targetCatch")}' - saveNewEntryText='{n("observe.content.action.create.targetCatch")}' - saveNewEntryTip='{n("observe.content.action.create.targetCatch.tip")}'> - - <style source="../../CommonTable.jcss"/> - - <import> - fr.ird.observe.services.dto.CommentableDto - fr.ird.observe.services.dto.seine.SetSeineTargetCatchDto - fr.ird.observe.services.dto.seine.TargetCatchDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.SpeciesDto - fr.ird.observe.services.dto.referential.seine.WeightCategoryDto - fr.ird.observe.ui.content.table.* - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - java.awt.Dimension - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <TargetCatchUIHandler id='handler' constructorParams='this'/> - - <!-- model --> - <TargetCatchUIModel id='model' constructorParams='this'/> - - <!-- edit bean --> - <SetSeineTargetCatchDto id='bean'/> - - <!-- table edit bean --> - <TargetCatchDto id='tableEditBean'/> - - <!-- table model --> - <ContentTableModel id='tableModel'/> - - <!-- le validateur de l'écran --> - <BeanValidator id='validator' - beanClass='fr.ird.observe.services.dto.seine.SetSeineTargetCatchDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update-targetCatch'> - <!-- clef unique --> - <field name="targetCatch" component="editorPanel"/> - </BeanValidator> - - <!-- le validateur d'une entrée de tableau --> - <BeanValidator id='validatorTable' - autoField='true' - beanClass='fr.ird.observe.services.dto.seine.TargetCatchDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update-targetCatch'/> - - <Table id='editorPanel' fill='both' insets='1' - onFocusGained='species.requestFocus()'> - - <!-- species --> - <row> - <cell> - <JLabel id='speciesLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='species' genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class' constructorParams='this'/> - - </cell> - </row> - - <!-- categorie species thon --> - <row> - <cell> - <JLabel id='weightCategoryLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='weightCategory' genericType='ReferentialReference<WeightCategoryDto>' _entityClass='WeightCategoryDto.class' constructorParams='this'/> - </cell> - </row> - - <!-- weight --> - <row> - <cell> - <JLabel id='catchWeightLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='catchWeight' constructorParams='this'/> - </cell> - </row> - - <!-- well --> - <row> - <cell> - <JLabel id='wellLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <JPanel layout='{new BorderLayout()}'> - <JToolBar id='wellToolbar' constraints='BorderLayout.WEST'> - <JButton id='resetWell' constraints='BorderLayout.WEST' styleClass='resetButton'/> - </JToolBar> - <JTextField id='well' constraints='BorderLayout.CENTER'/> - </JPanel> - </cell> - </row> - - <!-- comment --> - <row> - <cell columns='2' weighty='1'> - <JScrollPane id='comment' - onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2' - onKeyReleased='getTableEditBean().setComment(((JTextArea) event.getSource()).getText())'/> - </JScrollPane> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetCatchUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetCatchUI.jcss deleted file mode 100644 index e4d6334..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetCatchUI.jcss +++ /dev/null @@ -1,88 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#tableModel { - deleteExtraMessage:{t("observe.content.targetCatch.table.deleteExtraMessage")}; -} - -#speciesLabel { - text:"observe.content.targetCatch.table.speciesThon"; - toolTipText:"observe.content.targetCatch.table.speciesThon.tip"; - labelFor:{species}; -} - -#species { - property:"species"; - selectedItem:{tableEditBean.getSpecies()}; - enabled:{!tableModel.isEditable() || !model.isRowSaved()}; -} - -#weightCategoryLabel { - text:"observe.common.weightCategory"; - toolTipText:"observe.content.targetCatch.table.weightCategory.tip"; - labelFor:{weightCategory}; -} - -#weightCategory { - property:{TargetCatchDto.PROPERTY_WEIGHT_CATEGORY}; - selectedItem:{tableEditBean.getWeightCategory()}; - enabled:{!tableModel.isEditable() || !model.isRowSaved()}; -} - -#catchWeightLabel { - text:"observe.common.catchWeight"; - labelFor:{catchWeight}; -} - -#catchWeight { - property:{TargetCatchDto.PROPERTY_CATCH_WEIGHT}; - model:{tableEditBean.getCatchWeight()}; - useFloat:true; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL3_PATTERN}; -} - -#wellLabel { - text:"observe.common.well"; - toolTipText:"observe.content.targetCatch.table.well.tip"; - labelFor:{well}; -} - -#resetWell { - toolTipText:"observe.content.action.reset.well.tip"; - enabled:{!tableModel.isEditable() || !model.isRowSaved()}; - _resetTablePropertyName:{TargetCatchDto.PROPERTY_WELL}; -} - -#well { - text:{getStringValue(tableEditBean.getWell())}; - enabled:{!tableModel.isEditable() || !model.isRowSaved()}; - _tablePropertyName:{TargetCatchDto.PROPERTY_WELL}; -} - -#comment { - columnHeaderView:{new JLabel(t("observe.common.comment.targetCatch"))}; - minimumSize:{new Dimension(10,80)}; -} - -#comment2 { - text:{getStringValue(tableEditBean.getComment())}; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetCatchUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetCatchUIHandler.java deleted file mode 100644 index 0fc00e7..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetCatchUIHandler.java +++ /dev/null @@ -1,329 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.table.impl.seine; - -import com.google.common.collect.Iterables; -import com.google.common.collect.Sets; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.ReferentialReferences; -import fr.ird.observe.services.dto.referential.SpeciesDto; -import fr.ird.observe.services.dto.referential.seine.WeightCategoryDto; -import fr.ird.observe.services.dto.referential.seine.WeightCategoryDtos; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.dto.seine.ObjectSchoolEstimateDto; -import fr.ird.observe.services.dto.seine.SetSeineTargetCatchDto; -import fr.ird.observe.services.dto.seine.SetSeineTargetCatchDtos; -import fr.ird.observe.services.dto.seine.TargetCatchDto; -import fr.ird.observe.services.dto.seine.TargetCatchDtos; -import fr.ird.observe.services.service.seine.TargetCatchService; -import fr.ird.observe.services.service.seine.TripSeineService; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIHandler; -import jaxx.runtime.swing.editor.bean.BeanComboBox; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.decorator.Decorator; - -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Set; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class TargetCatchUIHandler extends ContentTableUIHandler<SetSeineTargetCatchDto, TargetCatchDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(TargetCatchUIHandler.class); - - public TargetCatchUIHandler(TargetCatchUI ui) { - super(ui, DataContextType.SetSeine); - } - - @Override - public TargetCatchUI getUi() { - return (TargetCatchUI) super.getUi(); - } - - @Override - public void initUI() { - super.initUI(); - - // lors de la modification d'une species (sur une entree non sauvee) - // - on recalcule la liste des categories pour cette species. - // - on reinitialiser la categorie selectionnee - - getUi().getSpecies().addPropertyChangeListener( - BeanComboBox.PROPERTY_SELECTED_ITEM, - evt -> { - - ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto> model = getTableModel(); - if (model.isNewRow()) { - - // en mode creation , on doit recalculer la liste des categories - ReferentialReference<SpeciesDto> species = (ReferentialReference<SpeciesDto>) evt.getNewValue(); - onSpeciesChanged(species); - - } - } - ); - } - - @Override - protected String getEditBeanIdToLoad() { - return getDataContext().getSelectedSetId(); - } - - @SuppressWarnings("Duplicates") - @Override - protected boolean prepareSave(SetSeineTargetCatchDto bean, List<TargetCatchDto> objets) { - - // on cherche si parmis les captures supprimer certaines ont des échantillons - SetSeineTargetCatchDto originalSetSeineTargetCatchDto = getModel().getForm().getObject(); - SetSeineTargetCatchDto currentSetSeineTargetCatch = getModel().getBean(); - - Set<ReferentialReference<SpeciesDto>> speciesToDelete = Sets.newHashSet(); - - for (TargetCatchDto targetCatchDto : originalSetSeineTargetCatchDto.getTargetCatch()) { - - if (targetCatchDto.isHasSample()) { - - ReferentialReference<SpeciesDto> species = targetCatchDto.getSpecies(); - - Iterable<TargetCatchDto> currentTargetCatchSpecies = TargetCatchDtos.filterBySpecies(currentSetSeineTargetCatch.getTargetCatch(), species); - - if (Iterables.isEmpty(currentTargetCatchSpecies)) { - - speciesToDelete.add(species); - - } - } - - } - - if (!speciesToDelete.isEmpty()) { - - // il existe des echantillons thon a supprimer on demande une confirmation - StringBuilder sb = new StringBuilder(512); - Decorator<ReferentialReference<SpeciesDto>> decorator = getReferentialReferenceDecorator(SpeciesDto.class); - - for (ReferentialReference<SpeciesDto> species : speciesToDelete) { - sb.append(" - ").append(decorator.toString(species)).append('\n'); - } - int reponse = UIHelper.askUser( - t("observe.title.need.confirm"), - t("observe.content.targetDiscarded.message.table.will.delete.targetLength", sb.toString()), - JOptionPane.ERROR_MESSAGE, - new Object[]{ - t("observe.choice.continue"), - t("observe.choice.cancel")}, - 0); - if (log.isDebugEnabled()) { - log.debug("response : " + reponse); - } - boolean canContinue = false; - switch (reponse) { - case 0: - // wil reset ui - canContinue = true; - break; - } - - if (!canContinue) { - - // l'utilisateur a choisi de ne pas continuer - return false; - } - } - return true; - } - - @Override - protected void onSelectedRowChanged(int editingRow, TargetCatchDto bean, boolean create) { - - TargetCatchUI ui = getUi(); - - ReferentialReference<WeightCategoryDto> weightCategory = bean.getWeightCategory(); - - ReferentialReference<SpeciesDto> species = null; - if (weightCategory != null) { - species = getWeightCategorySpecies(weightCategory).orElse(null); - } - - JComponent requestFocus; - if (create) { - - // on reinitilise toujours l'espèce (pour reinitialiser la liste des categories) - ui.getSpecies().setSelectedItem(null); - - if (!getTableModel().isCreate()) { - // on repositionne l'espèce (cela reconstruira la liste des categories) - ui.getSpecies().setSelectedItem(species); - // on repositionne la categorie - ui.getWeightCategory().setSelectedItem(weightCategory); - } - - requestFocus = ui.getSpecies(); - - } else { - - // en mode mise a jour, on restreint la liste des categories - // au singleton de sa valeur correspondante dans le bean - // puisque dans ce mode, pas possibilite de modifier de cette - // valeur (clef metier) - ui.getSpecies().setSelectedItem(species); - ui.getWeightCategory().setData(Collections.singletonList(weightCategory)); - ui.getWeightCategory().setSelectedItem(weightCategory); - - requestFocus = ui.getCatchWeight(); - } - - if (log.isDebugEnabled()) { - log.debug("selected weightcategory " + weightCategory); - log.debug("selected species " + species); - } - requestFocus.requestFocus(); - } - - @Override - protected void initTableUI(DefaultTableCellRenderer renderer) { - - JTable table = getUi().getTable(); - - UIHelper.fixTableColumnWidth(table, 2, 100); - UIHelper.fixTableColumnWidth(table, 3, 50); - UIHelper.fixTableColumnWidth(table, 4, 50); - - UIHelper.setI18nTableHeaderRenderer( - table, - n("observe.content.targetCatch.table.speciesThon"), - n("observe.content.targetCatch.table.speciesThon.tip"), - n("observe.content.targetCatch.table.weightCategory"), - n("observe.content.targetCatch.table.weightCategory.tip"), - n("observe.content.targetCatch.table.well"), - n("observe.content.targetCatch.table.well.tip"), - n("observe.content.targetCatch.table.weight"), - n("observe.content.targetCatch.table.weight.tip"), - n("observe.content.targetCatch.table.comment"), - n("observe.content.targetCatch.table.comment.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesDto.class)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, WeightCategoryDto.class)); - UIHelper.setTableColumnRenderer(table, 2, renderer); - UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 4, UIHelper.newStringTableCellRenderer(renderer, 10, true)); - } - - protected void onSpeciesChanged(ReferentialReference<SpeciesDto> species) { - - List<ReferentialReference<WeightCategoryDto>> availableCategories; - - if (species == null) { - - // aucune espèce selectionnee, on vide simplement la liste des categories - // car il faut d'abord choisir une espèce puis une categorie - availableCategories = Collections.emptyList(); - - } else { - - // un espèce est selectionnee, on calcule les categories pour cette espèce - // on ne conserve que les categories de l'espèce - Set<ReferentialReference<WeightCategoryDto>> allCategories = getModel().getReferentialReferences(TargetCatchDto.PROPERTY_WEIGHT_CATEGORY); - availableCategories = WeightCategoryDtos.filterSpeciesWeightCategories(allCategories, species.getId()); - - } - - // on met a jour la liste des categories disponibles - BeanComboBox<ReferentialReference<WeightCategoryDto>> combo = getUi().getWeightCategory(); - combo.setData(availableCategories); - - // on reinitialise toujours la categorie selectionnee - combo.setSelectedItem(null); - - } - - @Override - protected void doPersist(SetSeineTargetCatchDto bean) { - - SaveResultDto saveResult = getTargetCatchService().save(bean); - saveResult.toDto(bean); - - } - - @Override - protected void loadEditBean(String beanId) { - Form<SetSeineTargetCatchDto> form = getTargetCatchService().loadForm(beanId, false); - loadReferentialReferenceSetsInModel(form); - getModel().setForm(form); - SetSeineTargetCatchDtos.copySetSeineTargetCatchDto(form.getObject(), getBean()); - } - - @Override - protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { - - Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); - - switch (propertyName) { - - case ObjectSchoolEstimateDto.PROPERTY_SPECIES: { - - String speciesListId = ObserveSwingApplicationContext.get().getConfig().getSpeciesListSeineTargetCatchId(); - String tripSeineId = getDataContext().getSelectedTripSeineId(); - - TripSeineService tripSeineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripSeineService(); - result = (List) tripSeineService.getSpeciesByListAndTrip(tripSeineId, speciesListId); - - result = ReferentialReferences.filterEnabled(result); - - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - } - - break; - - } - - return result; - - } - - protected TargetCatchService getTargetCatchService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTargetCatchService(); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetCatchUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetCatchUIModel.java deleted file mode 100644 index 976ccce..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetCatchUIModel.java +++ /dev/null @@ -1,98 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import fr.ird.observe.services.dto.referential.seine.WeightCategoryDto; -import fr.ird.observe.services.dto.seine.SetSeineTargetCatchDto; -import fr.ird.observe.services.dto.seine.TargetCatchDto; -import fr.ird.observe.services.dto.seine.TargetCatchDtos; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; - -import java.util.Collection; -import java.util.List; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class TargetCatchUIModel extends ContentTableUIModel<SetSeineTargetCatchDto, TargetCatchDto> { - - private static final long serialVersionUID = 1L; - - public TargetCatchUIModel(TargetCatchUI ui) { - - super(SetSeineTargetCatchDto.class, - TargetCatchDto.class, - new String[]{ - SetSeineTargetCatchDto.PROPERTY_DISCARDED, - SetSeineTargetCatchDto.PROPERTY_TARGET_CATCH - }, - new String[]{ - TargetCatchDto.PROPERTY_WEIGHT_CATEGORY, - TargetCatchDto.PROPERTY_CATCH_WEIGHT, - TargetCatchDto.PROPERTY_WELL, - TargetCatchDto.PROPERTY_BROUGHT_ON_DECK, - TargetCatchDto.PROPERTY_DISCARDED, - TargetCatchDto.PROPERTY_COMMENT} - ); - - List<ContentTableMeta<TargetCatchDto>> metas = Lists.newArrayList( - ContentTableModel.newTableMeta(TargetCatchDto.class, WeightCategoryDto.PROPERTY_SPECIES, true), - ContentTableModel.newTableMeta(TargetCatchDto.class, TargetCatchDto.PROPERTY_WEIGHT_CATEGORY, true), - ContentTableModel.newTableMeta(TargetCatchDto.class, TargetCatchDto.PROPERTY_WELL, false), - ContentTableModel.newTableMeta(TargetCatchDto.class, TargetCatchDto.PROPERTY_CATCH_WEIGHT, false), - ContentTableModel.newTableMeta(TargetCatchDto.class, TargetCatchDto.PROPERTY_COMMENT, false)); - - initModel(ui, metas); - - } - - @Override - protected ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto> createTableModel( - ObserveContentTableUI<SetSeineTargetCatchDto, TargetCatchDto> ui, - List<ContentTableMeta<TargetCatchDto>> contentTableMetas) { - return new ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto>(ui, contentTableMetas) { - private static final long serialVersionUID = 1L; - @Override - protected Collection<TargetCatchDto> getChilds(SetSeineTargetCatchDto bean) { - return bean.getTargetCatch(); - } - - @Override - protected void load(TargetCatchDto source, TargetCatchDto target) { - TargetCatchDtos.copyTargetCatchDto(source, target); - } - - @Override - protected void setChilds(SetSeineTargetCatchDto parent, List<TargetCatchDto> childs) { - parent.setTargetCatch(childs); - } - }; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetDiscardCatchUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetDiscardCatchUI.jaxx deleted file mode 100644 index 95e54da..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetDiscardCatchUI.jaxx +++ /dev/null @@ -1,151 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.table.ContentTableUI - superGenericType='SetSeineTargetCatchDto, TargetCatchDto' - contentTitle='{n("observe.common.targetDiscarded")}' - saveNewEntryText='{n("observe.content.action.create.targetDiscarded")}' - saveNewEntryTip='{n("observe.content.action.create.targetDiscarded.tip")}'> - - <style source="../../CommonTable.jcss"/> - - <import> - fr.ird.observe.services.dto.CommentableDto - fr.ird.observe.services.dto.seine.SetSeineTargetCatchDto - fr.ird.observe.services.dto.seine.TargetCatchDto - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.SpeciesDto - fr.ird.observe.services.dto.referential.seine.ReasonForDiscardDto - fr.ird.observe.services.dto.referential.seine.WeightCategoryDto - fr.ird.observe.ui.content.table.* - fr.ird.observe.ui.util.BooleanEditor - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - java.awt.Dimension - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <TargetDiscardCatchUIHandler id='handler' constructorParams='this'/> - - <!-- model --> - <TargetDiscardCatchUIModel id='model' constructorParams='this'/> - - <!-- edit bean --> - <SetSeineTargetCatchDto id='bean'/> - - <!-- table edit bean --> - <TargetCatchDto id='tableEditBean'/> - - <!-- table model --> - <ContentTableModel id='tableModel'/> - - <!-- le validateur de l'écran --> - <BeanValidator id='validator' - beanClass='fr.ird.observe.services.dto.seine.SetSeineTargetCatchDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update-targetDiscarded'> - <!-- clef unique --> - <field name="targetCatch" component="editorPanel"/> - </BeanValidator> - - <!-- le validateur d'une entrée de tableau --> - <BeanValidator id='validatorTable' - autoField='true' - beanClass='fr.ird.observe.services.dto.seine.TargetCatchDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update-targetDiscarded'/> - - <Table id='editorPanel' fill='both' insets='1'> - - <!-- species --> - <row> - <cell> - <JLabel id='speciesLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='species' constructorParams='this' genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class'/> - </cell> - </row> - - <!-- categorie weight --> - <row> - <cell> - <JLabel id='weightCategoryLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='weightCategory' constructorParams='this' genericType='ReferentialReference<WeightCategoryDto>' _entityClass='WeightCategoryDto.class'/> - </cell> - </row> - - <!-- raison rejet --> - <row> - <cell> - <JLabel id='reasonForDiscardLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='reasonForDiscard' constructorParams='this' genericType='ReferentialReference<ReasonForDiscardDto>' _entityClass='ReasonForDiscardDto.class'/> - </cell> - </row> - - <!-- weight --> - <row> - <cell> - <JLabel id='catchWeightLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='catchWeight' constructorParams='this'/> - </cell> - </row> - - <!-- sur le pont --> - <row> - <cell columns='2'> - <JLabel id='broughtOnDeckInformation'/> - </cell> - </row> - <row> - <cell> - <JLabel id='broughtOnDeckLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BooleanEditor id='broughtOnDeck'/> - </cell> - </row> - <!-- comment --> - <row> - <cell columns='2' weighty='1'> - <JScrollPane id='comment' - onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2' - onKeyReleased='getTableEditBean().setComment(((JTextArea) event.getSource()).getText())'/> - </JScrollPane> - </cell> - </row> - - </Table> - -</fr.ird.observe.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetDiscardCatchUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetDiscardCatchUI.jcss deleted file mode 100644 index f193531..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetDiscardCatchUI.jcss +++ /dev/null @@ -1,100 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#tableModel { - deleteExtraMessage:{t("observe.content.targetDiscarded.table.deleteExtraMessage")}; -} - -#speciesLabel { - text:"observe.common.speciesThon"; - toolTipText:"observe.content.targetDiscarded.table.speciesThon.tip"; - labelFor:{species}; -} - -#species { - property:"species"; - selectedItem:{tableEditBean.getSpecies()}; - enabled:{!tableModel.isEditable() || !model.isRowSaved()}; -} - -#weightCategoryLabel { - text:"observe.common.weightCategory"; - toolTipText:"observe.content.targetDiscarded.table.weightCategory.tip"; - labelFor:{weightCategory}; -} - -#weightCategory { - property:{TargetCatchDto.PROPERTY_WEIGHT_CATEGORY}; - selectedItem:{tableEditBean.getWeightCategory()}; - enabled:{!tableModel.isEditable() || !model.isRowSaved()}; -} - -#reasonForDiscardLabel { - text:"observe.common.reasonForDiscard"; - toolTipText:"observe.content.targetDiscarded.table.reasonForDiscard.tip"; - labelFor:{reasonForDiscard}; -} - -#reasonForDiscard { - property:{TargetCatchDto.PROPERTY_REASON_FOR_DISCARD}; - selectedItem:{tableEditBean.getReasonForDiscard()}; - enabled:{!tableModel.isEditable() || !model.isRowSaved()}; -} - -#catchWeightLabel { - text:"observe.common.catchWeight"; - labelFor:{catchWeight}; -} - -#catchWeight { - property:{TargetCatchDto.PROPERTY_CATCH_WEIGHT}; - model:{tableEditBean.getCatchWeight()}; - useFloat:true; - numberPattern:{fr.ird.observe.ui.UIHelper.DECIMAL3_PATTERN}; -} - -#broughtOnDeckInformation { - text:"observe.content.broughtOnDeck.comment"; - toolTipText:"observe.content.broughtOnDeck.comment"; - actionIcon:"information"; - font-size:11; - verticalAlignment:"center"; -} - -#broughtOnDeckLabel { - text:"observe.common.broughtOnDeck"; - labelFor:{broughtOnDeck}; -} - -#broughtOnDeck { - booleanValue:{tableEditBean.getBroughtOnDeck()}; - _tablePropertyName:{TargetCatchDto.PROPERTY_BROUGHT_ON_DECK}; -} - -#comment { - columnHeaderView:{new JLabel(t("observe.common.comment.targetDiscarded"))}; - minimumSize:{new Dimension(10,80)}; -} - -#comment2 { - text:{getStringValue(tableEditBean.getComment())}; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetDiscardCatchUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetDiscardCatchUIHandler.java deleted file mode 100644 index 95d64f2..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetDiscardCatchUIHandler.java +++ /dev/null @@ -1,541 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.table.impl.seine; - -import com.google.common.collect.Iterables; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.ReferentialReferences; -import fr.ird.observe.services.dto.referential.SpeciesDto; -import fr.ird.observe.services.dto.referential.seine.ReasonForDiscardDto; -import fr.ird.observe.services.dto.referential.seine.WeightCategoryDto; -import fr.ird.observe.services.dto.referential.seine.WeightCategoryDtos; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.dto.seine.ObjectSchoolEstimateDto; -import fr.ird.observe.services.dto.seine.SetSeineTargetCatchDto; -import fr.ird.observe.services.dto.seine.SetSeineTargetCatchDtos; -import fr.ird.observe.services.dto.seine.TargetCatchDto; -import fr.ird.observe.services.dto.seine.TargetCatchDtos; -import fr.ird.observe.services.service.seine.TargetCatchService; -import fr.ird.observe.services.service.seine.TripSeineService; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIHandler; -import jaxx.runtime.swing.editor.bean.BeanComboBox; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.decorator.Decorator; - -import javax.swing.JComponent; -import javax.swing.JOptionPane; -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedList; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class TargetDiscardCatchUIHandler extends ContentTableUIHandler<SetSeineTargetCatchDto, TargetCatchDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(TargetDiscardCatchUIHandler.class); - - public TargetDiscardCatchUIHandler(TargetDiscardCatchUI ui) { - super(ui, DataContextType.SetSeine); - } - - protected static Collection<ReferentialReference<WeightCategoryDto>> getWeightCategoryUsed( - ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto> model) { - - List<ReferentialReference<WeightCategoryDto>> list = model.getColumnValues(1); - Collection<ReferentialReference<WeightCategoryDto>> set = Sets.newHashSet(list); - list.clear(); - return set; - } - - protected static Collection<ReferentialReference<ReasonForDiscardDto>> getReasonForDiscardUsed( - ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto> model, - ReferentialReference<WeightCategoryDto> weightCategory) { - - Collection<ReferentialReference<ReasonForDiscardDto>> set = Sets.newHashSet(); - if (weightCategory != null) { - for (int i = 0; i < model.getRowCount(); i++) { - TargetCatchDto c = model.getValueAt(i); - if (c != null && weightCategory.equals(c.getWeightCategory()) && c.getReasonForDiscard() != null) { - set.add(c.getReasonForDiscard()); - } - } - } - return set; - } - - @Override - public TargetDiscardCatchUI getUi() { - return (TargetDiscardCatchUI) super.getUi(); - } - - @Override - public void initUI() { - - super.initUI(); - - TargetDiscardCatchUI ui = getUi(); - - // lors de la modification d'une species (sur une entree non sauvee) - // - on recalcule la liste des categories pour cette species. - // - on reinitialiser la categorie selectionnee - - ui.getSpecies().addPropertyChangeListener( - BeanComboBox.PROPERTY_SELECTED_ITEM, - evt -> { - - ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto> model = getTableModel(); - - if (model.isNewRow()) { - - // en mode creation , on doit recalculer la liste des categories - ReferentialReference<SpeciesDto> species = (ReferentialReference<SpeciesDto>) evt.getNewValue(); - onSpeciesChanged(model.getRowBean(), species); - - } - - } - ); - - // lors de la modification d'une catégorie (sur une entree non sauvee) - // - on recalcule la liste des raison rejets. - // - on reinitialiser la raison rejet selectionnee - - ui.getWeightCategory().addPropertyChangeListener( - BeanComboBox.PROPERTY_SELECTED_ITEM, - evt -> { - - ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto> model = getTableModel(); - if (model.isNewRow()) { - - // en mode creation , on doit recalculer la liste des raison rejet - ReferentialReference<WeightCategoryDto> weightCategory = - (ReferentialReference<WeightCategoryDto>) evt.getNewValue(); - onWeightCategoryChanged(model.getRowBean(), weightCategory); - - } - - } - ); - - } - - @Override - protected String getEditBeanIdToLoad() { - return getDataContext().getSelectedSetId(); - } - - @SuppressWarnings("Duplicates") - @Override - protected boolean prepareSave(SetSeineTargetCatchDto bean, List<TargetCatchDto> objets) { - - //on cherche si parmis les captures supprimer certaines ont des échantillons - SetSeineTargetCatchDto originalSetSeineTargetCatchDto = getModel().getForm().getObject(); - SetSeineTargetCatchDto currentSetSeineTargetCatch = getModel().getBean(); - - Set<ReferentialReference<SpeciesDto>> speciesToDelete = Sets.newHashSet(); - - for (TargetCatchDto targetCatchDto : originalSetSeineTargetCatchDto.getTargetCatch()) { - - if (targetCatchDto.isHasSample()) { - - ReferentialReference<SpeciesDto> species = targetCatchDto.getSpecies(); - - Iterable<TargetCatchDto> currentTargetCatchSpecies = TargetCatchDtos.filterBySpecies(currentSetSeineTargetCatch.getTargetCatch(), species); - - if (Iterables.isEmpty(currentTargetCatchSpecies)) { - - speciesToDelete.add(species); - - } - } - - } - - if (!speciesToDelete.isEmpty()) { - // il existe des echantillon thon a supprimer on demande une confirmation - StringBuilder sb = new StringBuilder(512); - Decorator<ReferentialReference<SpeciesDto>> decorator = - getReferentialReferenceDecorator(SpeciesDto.class); - - for (ReferentialReference<SpeciesDto> species : speciesToDelete) { - sb.append(" - ").append(decorator.toString(species)).append('\n'); - } - int reponse = UIHelper.askUser( - t("observe.title.need.confirm"), - t("observe.content.targetDiscarded.message.table.will.delete.targetLength", sb.toString()), - JOptionPane.ERROR_MESSAGE, - new Object[]{ - t("observe.choice.continue"), - t("observe.choice.cancel")}, - 0); - if (log.isDebugEnabled()) { - log.debug("response : " + reponse); - } - boolean canContinue = false; - switch (reponse) { - case 0: - // wil reset ui - canContinue = true; - break; - } - - if (!canContinue) { - - // l'utilisateur a choisi de ne pas continuer - return false; - } - } - - return true; - } - - @SuppressWarnings("Duplicates") - @Override - protected void onSelectedRowChanged(int editingRow, TargetCatchDto bean, boolean create) { - TargetDiscardCatchUI ui = getUi(); - - ReferentialReference<WeightCategoryDto> weightCategory = bean.getWeightCategory(); - - ReferentialReference<SpeciesDto> species = null; - if (weightCategory != null) { - species = getWeightCategorySpecies(weightCategory).orElse(null); - } - - ReferentialReference<ReasonForDiscardDto> reasonForDiscard = bean.getReasonForDiscard(); - if (log.isDebugEnabled()) { - log.debug("selected categoriePoid " + weightCategory); - log.debug("selected species " + species); - log.debug("selected reasonForDiscard " + reasonForDiscard); - } - - JComponent requestFocus; - if (create) { - ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto> model = getTableModel(); - - if (model.isCreate()) { - // par défaut, on considère que l'espèce a été montée sur le pont - // c'est le cas le plus fréquent. - bean.setBroughtOnDeck(true); - } - - // on recalcule la liste des speciess disponibles - List<ReferentialReference<SpeciesDto>> availableSpecies = buildSpeciesList(species, weightCategory); - ui.getSpecies().setData(availableSpecies); - - // on reinitilise toujours l'species (pour reinitialiser la liste des categories) - ui.getSpecies().setSelectedItem(null); - - if (!model.isCreate()) { - // on repositionne l'espèce (cela reconstruira la liste des categories) - ui.getSpecies().setSelectedItem(species); - // on repositionne la categorie - ui.getWeightCategory().setSelectedItem(weightCategory); - ui.getReasonForDiscard().setSelectedItem(reasonForDiscard); - } - - requestFocus = ui.getSpecies(); - } else { - // en mode mise a jour, on restreint la liste des categories - // au singleton de sa valeur correspondante dans le bean - // puisque dans ce mode, pas possibilite de modifier de cette - // valeur (clef metier) - ui.getSpecies().setSelectedItem(species); - ui.getWeightCategory().setData(Collections.singletonList(weightCategory)); - ui.getWeightCategory().setSelectedItem(weightCategory); - ui.getReasonForDiscard().setData(Collections.singletonList(reasonForDiscard)); - ui.getReasonForDiscard().setSelectedItem(reasonForDiscard); - - requestFocus = ui.getCatchWeight(); - } - - requestFocus.requestFocus(); - } - - @Override - protected void initTableUI(DefaultTableCellRenderer renderer) { - JTable table = getUi().getTable(); - UIHelper.fixTableColumnWidth(table, 3, 75); - UIHelper.fixTableColumnWidth(table, 4, 20); - UIHelper.fixTableColumnWidth(table, 5, 50); - - UIHelper.setI18nTableHeaderRenderer( - table, - n("observe.content.targetDiscarded.table.speciesThon"), - n("observe.content.targetDiscarded.table.speciesThon.tip"), - n("observe.content.targetDiscarded.table.weightCategory"), - n("observe.content.targetDiscarded.table.weightCategory.tip"), - n("observe.content.targetDiscarded.table.reasonForDiscard"), - n("observe.content.targetDiscarded.table.reasonForDiscard.tip"), - n("observe.content.targetDiscarded.table.weight"), - n("observe.content.targetDiscarded.table.weight.tip"), - n("observe.content.targetDiscarded.table.broughtOnDeck"), - n("observe.content.targetDiscarded.table.broughtOnDeck.tip"), - n("observe.content.targetDiscarded.table.comment"), - n("observe.content.targetDiscarded.table.comment.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesDto.class)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, WeightCategoryDto.class)); - UIHelper.setTableColumnRenderer(table, 2, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, ReasonForDiscardDto.class)); - UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 4, UIHelper.newStringTableCellRenderer(renderer, 20, false)); - UIHelper.setTableColumnRenderer(table, 5, UIHelper.newStringTableCellRenderer(renderer, 10, true)); - } - - protected void onSpeciesChanged(TargetCatchDto bean, ReferentialReference<SpeciesDto> species) { - - ReferentialReference<WeightCategoryDto> weightCategory = null; - - List<ReferentialReference<WeightCategoryDto>> data; - - if (species == null) { - - // aucune espèce selectionnee, on vide simplement la liste des categories - // car il faut d'abord choisir une espèce puis une categorie - data = Collections.emptyList(); - - } else { - - // un espèce est selectionnee, on met a jour la liste des categories disponibles pour cette espèce - List<ReferentialReference<WeightCategoryDto>> availableCategories = buildWeightCategoryList(species); - - data = availableCategories; - - weightCategory = bean.getWeightCategory(); - - if (weightCategory != null && !availableCategories.contains(weightCategory)) { - weightCategory = null; - } - } - - // on met a jour le model de la liste des categories - BeanComboBox<ReferentialReference<WeightCategoryDto>> combo = getUi().getWeightCategory(); - combo.setData(data); - - // on selectionne la categorie retenue - combo.setSelectedItem(weightCategory); - } - - protected void onWeightCategoryChanged(TargetCatchDto bean, ReferentialReference<WeightCategoryDto> weightCategory) { - TargetDiscardCatchUI ui = getUi(); - - ReferentialReference<ReasonForDiscardDto> reasonForDiscard = null; - List<ReferentialReference<ReasonForDiscardDto>> data; - - if (weightCategory == null) { - // aucune categorie selectionnee, on vide simplement - // la liste des raison rejets car il faut d'abord choisir une - // espèce puis une categorie, puis une raison rejet - data = Collections.emptyList(); - - } else { - - // un categorie est selectionne, on met a jour la liste des raisons - // rejet disponible pour cette categorie - - reasonForDiscard = bean.getReasonForDiscard(); - - List<ReferentialReference<ReasonForDiscardDto>> reasonForDiscardList = buildReasonFordiscardList(weightCategory, reasonForDiscard); - - if (log.isDebugEnabled()) { - log.debug("new reasonForDiscard list " + reasonForDiscardList); - } - - data = reasonForDiscardList; - - if (reasonForDiscard != null && !reasonForDiscardList.contains(reasonForDiscard)) { - // on sélectionne la première raison rejet disponible - reasonForDiscard = null; - } - } - - BeanComboBox<ReferentialReference<ReasonForDiscardDto>> combo = ui.getReasonForDiscard(); - - // on met a jour le model de la liste des raison rejets - combo.setData(data); - - // on selectionne la raison rejet retenue - combo.setSelectedItem(reasonForDiscard); - } - - protected List<ReferentialReference<SpeciesDto>> buildSpeciesList(ReferentialReference<SpeciesDto> species, - ReferentialReference<WeightCategoryDto> weightCategory) { - - List<ReferentialReference<WeightCategoryDto>> weightCategoryList = getAllWeightCategories(); - - removeFullyUsedWeightCategories(weightCategoryList); - - if (weightCategory != null) { - weightCategoryList.add(weightCategory); - } - - Collection<ReferentialReference<SpeciesDto>> usedSpecies = Sets.newHashSet(); - for (ReferentialReference<WeightCategoryDto> cat : weightCategoryList) { - - Optional<ReferentialReference<SpeciesDto>> optionalSpecies = getWeightCategorySpecies(cat); - - if (optionalSpecies.isPresent()) { - usedSpecies.add(optionalSpecies.get()); - } - - } - - List<ReferentialReference<SpeciesDto>> result = Lists.newArrayList(usedSpecies); - weightCategoryList.clear(); - usedSpecies.clear(); - return result; - - } - - protected List<ReferentialReference<WeightCategoryDto>> buildWeightCategoryList(ReferentialReference<SpeciesDto> species) { - - Set<ReferentialReference<WeightCategoryDto>> allCategories = getModel().getReferentialReferences(TargetCatchDto.PROPERTY_WEIGHT_CATEGORY); - List<ReferentialReference<WeightCategoryDto>> weightCategoryList = WeightCategoryDtos.filterSpeciesWeightCategories(allCategories, species.getId()); - - // on filtre toutes les categories qui ont deja references sur toutes les raisons de rejet - removeFullyUsedWeightCategories(weightCategoryList); - - return weightCategoryList; - } - - @SuppressWarnings("unchecked") - protected List<ReferentialReference<ReasonForDiscardDto>> buildReasonFordiscardList(ReferentialReference<WeightCategoryDto> weightCategory, - ReferentialReference<ReasonForDiscardDto> reasonForDiscard) { - - ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto> model = getTableModel(); - Set<ReferentialReference<ReasonForDiscardDto>> reasonForDiscardSet = getModel().getReferentialReferences(TargetCatchDto.PROPERTY_REASON_FOR_DISCARD); - - List<ReferentialReference<ReasonForDiscardDto>> reasonForDiscardList = Lists.newArrayList(reasonForDiscardSet); - - // on filtre les raison rejet sur la categorie - for (int i = 0; i < model.getRowCount(); i++) { - TargetCatchDto c = model.getValueAt(i); - - if (model.getSelectedRow() != i - && c != null - && c.getReasonForDiscard() != null - && (reasonForDiscard == null || !reasonForDiscard.equals(c.getReasonForDiscard())) - && weightCategory.equals(c.getWeightCategory())) { - reasonForDiscardList.remove(c.getReasonForDiscard()); - } - } - - return reasonForDiscardList; - } - - protected List<ReferentialReference<WeightCategoryDto>> getAllWeightCategories() { - - Set<ReferentialReference<WeightCategoryDto>> weightCategorySet = getModel().getReferentialReferences(TargetCatchDto.PROPERTY_WEIGHT_CATEGORY); - List<ReferentialReference<WeightCategoryDto>> weightCategoryList = Lists.newArrayList(weightCategorySet); - return weightCategoryList; - - } - - protected void removeFullyUsedWeightCategories(List<ReferentialReference<WeightCategoryDto>> weightCategoryAvaillables) { - - ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto> model = getTableModel(); - - Set<ReferentialReference<ReasonForDiscardDto>> reasonForDiscardSet = getModel().getReferentialReferences(TargetCatchDto.PROPERTY_REASON_FOR_DISCARD); - - int nbReasonForDiscard = reasonForDiscardSet.size(); - - // on filtre toutes les weightCategory qui ont deja references toutes les raisons rejets - for (ReferentialReference<WeightCategoryDto> c : getWeightCategoryUsed(model)) { - Collection<ReferentialReference<ReasonForDiscardDto>> raisonUsed = getReasonForDiscardUsed(model, c); - if (raisonUsed.size() == nbReasonForDiscard) { - // toutes les raison de rejet epuisé pour cette categorie - weightCategoryAvaillables.remove(c); - } - } - } - - @Override - protected void doPersist(SetSeineTargetCatchDto bean) { - - SaveResultDto saveResult = getTargetCatchService().save(bean); - saveResult.toDto(bean); - - } - - - @Override - protected void loadEditBean(String beanId) { - Form<SetSeineTargetCatchDto> form = getTargetCatchService().loadForm(beanId, true); - loadReferentialReferenceSetsInModel(form); - getModel().setForm(form); - SetSeineTargetCatchDtos.copySetSeineTargetCatchDto(form.getObject(), getBean()); - } - - - @Override - protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { - - Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); - - switch (propertyName) { - - case ObjectSchoolEstimateDto.PROPERTY_SPECIES: { - - String speciesListId = ObserveSwingApplicationContext.get().getConfig().getSpeciesListSeineTargetCatchId(); - String tripSeineId = getDataContext().getSelectedTripSeineId(); - - TripSeineService tripSeineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripSeineService(); - result = (List) tripSeineService.getSpeciesByListAndTrip(tripSeineId, speciesListId); - - result = ReferentialReferences.filterEnabled(result); - - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - } - - break; - - } - - return result; - - } - - protected TargetCatchService getTargetCatchService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTargetCatchService(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetDiscardCatchUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetDiscardCatchUIModel.java deleted file mode 100644 index 1c22ad0..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetDiscardCatchUIModel.java +++ /dev/null @@ -1,98 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import fr.ird.observe.services.dto.referential.seine.WeightCategoryDto; -import fr.ird.observe.services.dto.seine.SetSeineTargetCatchDto; -import fr.ird.observe.services.dto.seine.TargetCatchDto; -import fr.ird.observe.services.dto.seine.TargetCatchDtos; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; - -import java.util.Collection; -import java.util.List; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class TargetDiscardCatchUIModel extends ContentTableUIModel<SetSeineTargetCatchDto, TargetCatchDto> { - - private static final long serialVersionUID = 1L; - - public TargetDiscardCatchUIModel(TargetDiscardCatchUI ui) { - - super(SetSeineTargetCatchDto.class, - TargetCatchDto.class, - new String[]{ - SetSeineTargetCatchDto.PROPERTY_DISCARDED, - SetSeineTargetCatchDto.PROPERTY_TARGET_CATCH}, - new String[]{ - TargetCatchDto.PROPERTY_WEIGHT_CATEGORY, - TargetCatchDto.PROPERTY_CATCH_WEIGHT, - TargetCatchDto.PROPERTY_REASON_FOR_DISCARD, - TargetCatchDto.PROPERTY_DISCARDED, - TargetCatchDto.PROPERTY_BROUGHT_ON_DECK, - TargetCatchDto.PROPERTY_COMMENT}); - - List<ContentTableMeta<TargetCatchDto>> metas = Lists.newArrayList( - ContentTableModel.newTableMeta(TargetCatchDto.class, WeightCategoryDto.PROPERTY_SPECIES, true), - ContentTableModel.newTableMeta(TargetCatchDto.class, TargetCatchDto.PROPERTY_WEIGHT_CATEGORY, true), - ContentTableModel.newTableMeta(TargetCatchDto.class, TargetCatchDto.PROPERTY_REASON_FOR_DISCARD, true), - ContentTableModel.newTableMeta(TargetCatchDto.class, TargetCatchDto.PROPERTY_CATCH_WEIGHT, false), - ContentTableModel.newTableMeta(TargetCatchDto.class, TargetCatchDto.PROPERTY_BROUGHT_ON_DECK, false), - ContentTableModel.newTableMeta(TargetCatchDto.class, TargetCatchDto.PROPERTY_COMMENT, false)); - - initModel(ui, metas); - - } - - @Override - protected ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto> createTableModel( - ObserveContentTableUI<SetSeineTargetCatchDto, TargetCatchDto> ui, - List<ContentTableMeta<TargetCatchDto>> contentTableMetas) { - - return new ContentTableModel<SetSeineTargetCatchDto, TargetCatchDto>(ui, contentTableMetas) { - private static final long serialVersionUID = 1L; - @Override - protected Collection<TargetCatchDto> getChilds(SetSeineTargetCatchDto bean) { - return bean.getTargetCatch(); - } - - @Override - protected void load(TargetCatchDto source, TargetCatchDto target) { - TargetCatchDtos.copyTargetCatchDto(source, target); - } - - @Override - protected void setChilds(SetSeineTargetCatchDto parent, List<TargetCatchDto> childs) { - bean.setTargetCatch(childs); - } - }; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetSampleUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetSampleUI.jaxx deleted file mode 100644 index e8608a7..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetSampleUI.jaxx +++ /dev/null @@ -1,185 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<fr.ird.observe.ui.content.table.ContentTableUI - superGenericType='TargetSampleDto, TargetLengthDto' - abstract="true"> - - <style source="AbstractSampleUI.jcss"/> - - <import> - fr.ird.observe.services.dto.seine.TargetSampleDto - fr.ird.observe.services.dto.seine.TargetLengthDto - fr.ird.observe.ui.content.table.impl.seine.CodeMesureEnum - fr.ird.observe.ui.content.table.impl.seine.ModeSaisieEchantillonEnum - fr.ird.observe.services.dto.referential.ReferentialReference - fr.ird.observe.services.dto.referential.SpeciesDto - fr.ird.observe.ui.content.table.* - - jaxx.runtime.swing.editor.NumberEditor - jaxx.runtime.swing.editor.bean.BeanComboBox - - java.awt.Dimension - - static fr.ird.observe.ui.UIHelper.getStringValue - static org.nuiton.i18n.I18n.n - </import> - - <!-- handler --> - <TargetSampleUIHandler id='handler' initializer='null'/> - - <!-- model --> - <TargetSampleUIModel id='model' constructorParams='this'/> - - <!-- edit bean --> - <TargetSampleDto id='bean'/> - - <!-- table edit bean --> - <TargetLengthDto id='tableEditBean'/> - - <!-- table model --> - <ContentTableModel id='tableModel'/> - - <!-- le validateur de l'écran --> - <BeanValidator id='validator' - beanClass='fr.ird.observe.services.dto.seine.TargetSampleDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update'> - <!-- clef unique --> - <field name="targetLength" component="editorPanel"/> - <field name='comment'/> - </BeanValidator> - - <!-- le validateur d'une entrée de tableau --> - <BeanValidator id='validatorTable' - autoField='true' - beanClass='fr.ird.observe.services.dto.seine.TargetLengthDto' - errorTableModel='{getErrorTableModel()}' - context='ui-update' - parentValidator='{validator}'/> - - <ButtonGroup id='acquisitionModeGroup' - onStateChanged='getHandler().updateModeSaisie((ModeSaisieEchantillonEnum) acquisitionModeGroup.getSelectedValue())'/> - - <script><![CDATA[ - -public static final String POIDS_COMPUTED_TIP = n("observe.common.weight.computed.tip"); -public static final String POIDS_OBSERVED_TIP = n("observe.common.weight.observed.tip"); -public static final String LONGUEUR_COMPUTED_TIP = n("observe.common.length.computed.tip"); -public static final String LONGUEUR_OBSERVED_TIP = n("observe.common.length.observed.tip"); - -public String getWeightDataTip(boolean computed) { - return computed ? t(POIDS_COMPUTED_TIP) : t(POIDS_OBSERVED_TIP); -} - -public String getLengthDataTip(boolean computed) { - return computed ? t(LONGUEUR_COMPUTED_TIP) : t(LONGUEUR_OBSERVED_TIP); -} -]]> - </script> - <Table id='editorPanel' fill='both' insets='1'> - - <!-- mode de saisie --> - <row> - <cell columns="3"> - <JPanel id="modeAndCodePanel"> - <JPanel id='acquisitionModePanel' constraints="BorderLayout.CENTER"> - <JRadioButton id='acquisitionModeEffectif'/> - <JRadioButton id='acquisitionModeIndividu'/> - </JPanel> - <JPanel id='measureTypePanel' layout='{new BorderLayout()}'> - <EnumEditor id='measureType' - constraints="BorderLayout.CENTER" - constructorParams='CodeMesureEnum.class' - genericType='CodeMesureEnum' - onItemStateChanged='getTableEditBean().setMeasureType(measureType.getSelectedIndex())'/> - </JPanel> - </JPanel> - </cell> - </row> - - <!-- species thon --> - <row> - <cell> - <JLabel id='speciesLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <BeanComboBox id='species' genericType='ReferentialReference<SpeciesDto>' _entityClass='SpeciesDto.class' constructorParams='this'/> - </cell> - </row> - - <!-- length --> - <row> - <cell> - <JLabel id='lengthLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='length' constructorParams='this'/> - </cell> - <cell anchor='east'> - <JToolBar id='lengthSourceAction'> - <JButton id='lengthSourceInformation' - onActionPerformed='getHandler().resetLengthSource()'/> - </JToolBar> - </cell> - </row> - - <!-- weight individuel --> - <row> - <cell> - <JLabel id='weightLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='weight' constructorParams='this'/> - </cell> - <cell anchor='east'> - <JToolBar id='weightSourceAction'> - <JButton id='weightSourceInformation' - onActionPerformed='getHandler().resetWeightSource()'/> - </JToolBar> - </cell> - </row> - - <!-- count --> - <row> - <cell> - <JLabel id='countLabel'/> - </cell> - <cell weightx='1' anchor='east'> - <NumberEditor id='count' constructorParams='this'/> - </cell> - </row> - </Table> - - <Table id='extraZone' fill='both' weightx='1' insets='0'> - <row> - <cell weighty='1'> - <JScrollPane id='comment' - onFocusGained='comment2.requestFocus()'> - <JTextArea id='comment2' - onKeyReleased='getBean().setComment(comment2.getText())'/> - </JScrollPane> - </cell> - </row> - </Table> - -</fr.ird.observe.ui.content.table.ContentTableUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetSampleUI.jcss b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetSampleUI.jcss deleted file mode 100644 index 0216968..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetSampleUI.jcss +++ /dev/null @@ -1,87 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -#speciesLabel { - text:"observe.common.speciesThon"; -} - -#modeAndCodePanel { - layout:{new GridLayout(1,0)}; -} - -#acquisitionModeGroup { - selectedValue:{ModeSaisieEchantillonEnum.valueOf(tableEditBean.getAcquisitionMode())}; -} - -#acquisitionModePanel { - border:{new TitledBorder(t("observe.common.acquisitionMode"))}; - layout:{new GridLayout(0,1)}; -} - -#measureTypePanel { - border:{new TitledBorder(t("observe.common.measureType"))}; -} - -#measureType { - selectedIndex:{tableEditBean.getMeasureType()}; -} - -#acquisitionModeEffectif { - buttonGroup:"acquisitionModeGroup"; - value:{ModeSaisieEchantillonEnum.byEffectif}; - text:{ModeSaisieEchantillonEnum.byEffectif.getI18nKey()}; - selected:{tableEditBean.getAcquisitionMode() == 0}; - enabled:{!tableModel.isEditable() || tableModel.isCreate()}; - /*enabled:{!tableModel.isEditable() || !model.isRowSaved()};*/ -} - -#acquisitionModeIndividu { - buttonGroup:"acquisitionModeGroup"; - value:{ModeSaisieEchantillonEnum.byIndividu}; - text:{ModeSaisieEchantillonEnum.byIndividu.getI18nKey()}; - selected:{tableEditBean.getAcquisitionMode() == 1}; - enabled:{!tableModel.isEditable() || tableModel.isCreate()}; - /*enabled:{!tableModel.isEditable() || !model.isRowSaved()};*/ -} - -#lengthLabel { - text:"observe.common.length.inf"; -} - -#length { - _validatorLabel:{"observe.common.length.inf"}; -} - -#countLabel { - text:"observe.common.count"; - labelFor:{count}; -} - -#count { - property:"count"; - model:{tableEditBean.getCount()}; - numberPattern:{fr.ird.observe.ui.UIHelper.INT_6_DIGITS_PATTERN}; -} - -#comment { - columnHeaderView:{new JLabel(t("observe.common.comment.targetSample"))}; -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetSampleUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetSampleUIHandler.java deleted file mode 100644 index 71b1b6f..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetSampleUIHandler.java +++ /dev/null @@ -1,354 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.content.table.impl.seine; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.constants.DataContextType; -import fr.ird.observe.services.dto.Form; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.referential.SpeciesDto; -import fr.ird.observe.services.dto.result.SaveResultDto; -import fr.ird.observe.services.dto.seine.SetSeineDto; -import fr.ird.observe.services.dto.seine.TargetLengthDto; -import fr.ird.observe.services.dto.seine.TargetSampleDto; -import fr.ird.observe.services.dto.seine.TargetSampleDtos; -import fr.ird.observe.services.service.seine.TargetSampleService; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.content.ContentMode; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUI; -import fr.ird.observe.ui.content.table.ContentTableUIHandler; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.JComponent; -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; -import java.beans.PropertyChangeListener; -import java.util.Collection; -import java.util.LinkedList; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class TargetSampleUIHandler extends ContentTableUIHandler<TargetSampleDto, TargetLengthDto> { - - /** Logger */ - private static final Log log = LogFactory.getLog(TargetSampleUIHandler.class); - - /** - * Pour différencier positionner l'invariant de l'écran - * {@link TargetSampleDto#getDiscarded()}. - * - * @since 1.5 - */ - protected final boolean discarded; - - /** - * Ecoute les modifications de la propriété {@link TargetLengthDto#getWeight()}, - * et repasser alors le flag {@link TargetLengthDto#isWeightSource()} à - * {@code false}. - * - * @since 3.0 - */ - protected final PropertyChangeListener weightChanged; - - /** - * Ecoute les modifications de la propriété {@link TargetLengthDto#getLength()}, - * et repasser alors le flag {@link TargetLengthDto#isLengthSource()} à - * {@code false}. - * - * @since 3.0 - */ - protected final PropertyChangeListener lengthChanged; - - public TargetSampleUIHandler(ContentTableUI<TargetSampleDto, TargetLengthDto> ui, - boolean discarded) { - super(ui, DataContextType.SetSeine); - this.discarded = discarded; - weightChanged = evt -> { - TargetLengthDto source = (TargetLengthDto) evt.getSource(); - source.setWeightSource(false); - }; - lengthChanged = evt -> { - TargetLengthDto source = (TargetLengthDto) evt.getSource(); - source.setLengthSource(false); - }; - } - - @Override - public TargetSampleUI getUi() { - return (TargetSampleUI) super.getUi(); - } - - public void resetWeightSource() { - getTableEditBean().setWeightSource(false); - getUi().getWeight().grabFocus(); - } - - public void resetLengthSource() { - getTableEditBean().setLengthSource(false); - getUi().getLength().grabFocus(); - } - - @Override - protected String getEditBeanIdToLoad() { - String id = getDataContext().getSelectedSetId(); - return id; - } - - protected void onSelectedRowChanged(int editingRow, TargetLengthDto bean, boolean create) { - - ContentTableModel<TargetSampleDto, TargetLengthDto> model = getTableModel(); - TargetSampleUI ui = getUi(); - if (!model.isEditable()) { - return; - } - - ReferentialReference<SpeciesDto> species = bean.getSpecies(); - - JComponent requestFocus; - - if (create) { - -// if (model.isCreate() && editingRow > 0) { - if (model.isCreate()) { - - if (editingRow > 0) { - // on recupere l'species de la ligne precedente - TargetLengthDto editBean = model.getValueAt(editingRow - 1); - species = editBean.getSpecies(); - } - - // on passe le mode de saisie en count - ui.getAcquisitionModeGroup().setSelectedValue(null); - ui.getAcquisitionModeGroup().setSelectedValue(ModeSaisieEchantillonEnum.byEffectif); - - // on utilise par défaut le code mesure lf - ui.getMeasureType().setSelectedItem(null); - ui.getMeasureType().setSelectedItem(CodeMesureEnum.lf); - } - - requestFocus = ui.getSpecies(); - - } else { - - requestFocus = ui.getCount(); - - // on passe le mode de saisie - int acquisitionMode = bean.getAcquisitionMode(); - ModeSaisieEchantillonEnum enumValue = - ModeSaisieEchantillonEnum.valueOf(acquisitionMode); - ui.getAcquisitionModeGroup().setSelectedValue(null); - ui.getAcquisitionModeGroup().setSelectedValue(enumValue); - } - - // on met a jour l'espce - ui.getSpecies().setSelectedItem(null); - - if (species != null) { - if (log.isDebugEnabled()) { - log.debug("species to use " + species); - } - ui.getSpecies().setSelectedItem(species); - } - requestFocus.requestFocus(); - - TargetLengthDto tableEditBean = getTableEditBean(); - tableEditBean.removePropertyChangeListener(TargetLengthDto.PROPERTY_WEIGHT, weightChanged); - tableEditBean.addPropertyChangeListener(TargetLengthDto.PROPERTY_WEIGHT, weightChanged); - - tableEditBean.removePropertyChangeListener(TargetLengthDto.PROPERTY_LENGTH, lengthChanged); - tableEditBean.addPropertyChangeListener(TargetLengthDto.PROPERTY_LENGTH, lengthChanged); - } - - @Override - protected void initTableUI(DefaultTableCellRenderer renderer) { - - JTable table = getUi().getTable(); - - UIHelper.setI18nTableHeaderRenderer( - table, - n("observe.content.targetSample.table.speciesThon"), - n("observe.content.targetSample.table.speciesThon.tip"), - n("observe.content.targetSample.table.measureType"), - n("observe.content.targetSample.table.measureType.tip"), - n("observe.content.targetSample.table.length"), - n("observe.content.targetSample.table.length.tip"), - n("observe.content.targetSample.table.meanWeight"), - n("observe.content.targetSample.table.meanWeight.tip"), - n("observe.content.targetSample.table.count"), - n("observe.content.targetSample.table.count.tip"), - n("observe.content.targetSample.table.totalWeight"), - n("observe.content.targetSample.table.totalWeight.tip")); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newReferentialReferenceDecorateTableCellRenderer(renderer, SpeciesDto.class)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newEnumTableCellRenderer(renderer, CodeMesureEnum.class)); - UIHelper.setTableColumnRenderer(table, 2, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 3, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 4, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 5, UIHelper.newEmptyNumberTableCellRenderer(renderer)); - } - - @Override - protected ContentMode getContentMode(DataContext dataContext) { - ContentMode mode = super.getContentMode(dataContext); - - String setId = dataContext.getSelectedSetId(); - - boolean showData = getTargetSampleService().canUseTargetSample(setId, discarded); - - getModel().setShowData(showData); - - if (mode == ContentMode.UPDATE && !showData) { - - mode = ContentMode.READ; - - addMessage(getUi(), - NuitonValidatorScope.INFO, - getEntityLabel(SetSeineDto.class), - discarded ? - t("observe.content.setSeine.message.no.targetCatch") : - t("observe.content.setSeine.message.no.targetDiscarded") - ); - } - return mode; - } - - /** - * Le mode de saisie a été mis à jour. - * - * @param newMode le nouveau de mode de saisie à utiliser - * @since 1.8 - */ - public void updateModeSaisie(ModeSaisieEchantillonEnum newMode) { - - if (log.isDebugEnabled()) { - log.debug("Change mode saisie to " + newMode); - } - if (newMode == null) { - - // mode null (cela peut arriver avec les bindings) - return; - } - - TargetSampleUI ui = getUi(); - - boolean createMode = ui.getTableModel().isCreate(); - - TargetLengthDto editBean = ui.getTableEditBean(); - switch (newMode) { - - case byEffectif: - - // le weight n'est pas modifiable - ui.getWeight().setEnabled(false); - - // l'count est modifiable - ui.getCount().setEnabled(true); - - if (createMode) { - - // on supprime le weight (si il a été saisie) - editBean.setWeight(null); - // on supprime aussi l'count (pour forcer la saisie) - editBean.setCount(null); - } - break; - - case byIndividu: - - // le weight est pas modifiable - ui.getWeight().setEnabled(true); - - // l'count n'est pas modifiable et est toujours de 1 - ui.getCount().setEnabled(false); - - - if (createMode) { - - // on positionne l'count à 1 (seule valeur possible) - editBean.setCount(1); - } - break; - } - - if (createMode) { - - // on propage le mode de saisie dans le bean - editBean.setAcquisitionMode(newMode.ordinal()); - } - } - - @Override - protected void doPersist(TargetSampleDto bean) { - - SaveResultDto saveResult = getTargetSampleService().save(getSelectedParentId(), bean); - saveResult.toDto(bean); - - } - - @Override - protected void loadEditBean(String beanId) { - Form<TargetSampleDto> form = getTargetSampleService().loadForm(beanId, discarded); - loadReferentialReferenceSetsInModel(form); - getModel().setForm(form); - TargetSampleDtos.copyTargetSampleDto(form.getObject(), getBean()); - } - - @Override - protected <D extends ReferentialDto> Collection<ReferentialReference<D>> filterReferentialReferences(Class<D> dtoType, String propertyName, LinkedList<ReferentialReference<D>> incomingReferences) { - - Collection<ReferentialReference<D>> result = super.filterReferentialReferences(dtoType, propertyName, incomingReferences); - - switch (propertyName) { - - case TargetLengthDto.PROPERTY_SPECIES: { - - result = (List) getTargetSampleService().getSampleSpecies(getSelectedParentId(), discarded); - - if (log.isDebugEnabled()) { - log.debug(String.format("Filter referential references (type %s - property %s), final size: %d", dtoType.getSimpleName(), propertyName, incomingReferences.size())); - } - - } - - break; - - } - - return result; - - } - - protected TargetSampleService getTargetSampleService() { - return ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTargetSampleService(); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetSampleUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetSampleUIModel.java deleted file mode 100644 index 73d392a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/content/table/impl/seine/TargetSampleUIModel.java +++ /dev/null @@ -1,99 +0,0 @@ -package fr.ird.observe.ui.content.table.impl.seine; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import fr.ird.observe.services.dto.seine.TargetLengthDto; -import fr.ird.observe.services.dto.seine.TargetLengthDtos; -import fr.ird.observe.services.dto.seine.TargetSampleDto; -import fr.ird.observe.ui.content.table.ContentTableMeta; -import fr.ird.observe.ui.content.table.ContentTableModel; -import fr.ird.observe.ui.content.table.ContentTableUIModel; -import fr.ird.observe.ui.content.table.ObserveContentTableUI; - -import java.util.Collection; -import java.util.List; - -/** - * Created on 9/26/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since XXX - */ -public class TargetSampleUIModel extends ContentTableUIModel<TargetSampleDto, TargetLengthDto> { - - private static final long serialVersionUID = 1L; - - public TargetSampleUIModel(TargetSampleUI ui) { - - super(TargetSampleDto.class, - TargetLengthDto.class, - new String[]{ - TargetSampleDto.PROPERTY_TARGET_LENGTH, - TargetSampleDto.PROPERTY_COMMENT}, - new String[]{ - TargetLengthDto.PROPERTY_SPECIES, - TargetLengthDto.PROPERTY_LENGTH, - TargetLengthDto.PROPERTY_LENGTH_SOURCE, - TargetLengthDto.PROPERTY_WEIGHT, - TargetLengthDto.PROPERTY_WEIGHT_SOURCE, - TargetLengthDto.PROPERTY_COUNT, - TargetLengthDto.PROPERTY_MEASURE_TYPE, - TargetLengthDto.PROPERTY_ACQUISITION_MODE}); - - List<ContentTableMeta<TargetLengthDto>> metas = Lists.newArrayList( - ContentTableModel.newTableMeta(TargetLengthDto.class, TargetLengthDto.PROPERTY_SPECIES, true), - ContentTableModel.newTableMeta(TargetLengthDto.class, TargetLengthDto.PROPERTY_MEASURE_TYPE, true), - ContentTableModel.newTableMeta(TargetLengthDto.class, TargetLengthDto.PROPERTY_LENGTH, true), - ContentTableModel.newTableMeta(TargetLengthDto.class, TargetLengthDto.PROPERTY_WEIGHT, true), - ContentTableModel.newTableMeta(TargetLengthDto.class, TargetLengthDto.PROPERTY_COUNT, false), - ContentTableModel.newTableMeta(TargetLengthDto.class, TargetLengthDto.PROPERTY_TOTAL_WEIGHT, true)); - - initModel(ui, metas); - - } - - @Override - protected ContentTableModel<TargetSampleDto, TargetLengthDto> createTableModel( - ObserveContentTableUI<TargetSampleDto, TargetLengthDto> ui, - List<ContentTableMeta<TargetLengthDto>> contentTableMetas) { - return new ContentTableModel<TargetSampleDto, TargetLengthDto>(ui, contentTableMetas) { - private static final long serialVersionUID = 1L; - @Override - protected Collection<TargetLengthDto> getChilds(TargetSampleDto bean) { - return bean.getTargetLength(); - } - - @Override - protected void load(TargetLengthDto source, TargetLengthDto target) { - TargetLengthDtos.copyTargetLengthDto(source, target); - } - - @Override - protected void setChilds(TargetSampleDto parent, List<TargetLengthDto> childs) { - parent.setTargetLength(Sets.newLinkedHashSet(childs)); - } - }; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/ObstunaAdminAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/ObstunaAdminAction.java deleted file mode 100644 index cbbd757..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/ObstunaAdminAction.java +++ /dev/null @@ -1,352 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.storage; - -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableSet; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.db.constants.DbMode; -import fr.ird.observe.services.configuration.ObserveDataSourceConfiguration; -import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationRest; -import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaPG; -import fr.ird.observe.services.configuration.ObserveDataSourceInformation; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.DataSourceCreateConfigurationDto; -import fr.ird.observe.services.dto.ObserveDbUserDto; -import fr.ird.observe.services.service.BabModelVersionException; -import fr.ird.observe.services.service.DatabaseConnexionNotAuthorizedException; -import fr.ird.observe.services.service.DatabaseNotFoundException; -import fr.ird.observe.ui.storage.tabs.DataSelectionModel; -import jaxx.runtime.JAXXContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.version.Version; -import org.nuiton.version.Versions; - -import java.awt.Window; -import java.util.Set; -import java.util.stream.Collectors; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Les différents types d'actions d'administration possible sur une base - * distante. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public enum ObstunaAdminAction { - - /** - * pour créer une nouvelle base obstuna. - * - * Il faut au préalable avoir exécuté le script {@code create-obstuna_v2.sh}. - */ - CREATE(n("observe.obstuna.action.create"), - n("observe.obstuna.action.create.description"), - null) { - @Override - public RemoteUILauncher newLauncher(JAXXContext context, Window frame) { - return new RemoteUILauncher(this, context, frame, t(getLabel())) { - - protected DataSourceCreateConfigurationDto createConfigurationDto; - protected ObserveSwingDataSource dataSource; - protected Set<ObserveDbUserDto> users; - - @Override - protected void init(StorageUI ui) { - StorageUIModel model = ui.getModel(); - - // on autorise le mode de creation import referentiel - // depuis une source distante - model.getPgConfig().setCanMigrate(true); - super.init(ui); - } - - protected void checkImportDbVersion(StorageUIModel model, ObserveDataSourceConfiguration dataSourceConfig) throws DatabaseConnexionNotAuthorizedException, DatabaseNotFoundException, BabModelVersionException { - - ObserveSwingDataSource importDataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(dataSourceConfig); - - Preconditions.checkState(importDataSource != null, "Can't select data on a null dataSource"); - - try { - - importDataSource.open(); - - model.checkImportDbVersion(importDataSource); - - } finally { - - importDataSource.close(); - } - - } - - protected void initTask(StorageUIModel model) throws Exception { - - if (DbMode.USE_REMOTE.equals(model.getDbMode())) { - ObserveDataSourceConfigurationTopiaPG pgConfig = model.getPgConfig(); - - // pas autorise a migrer automatiquement - pgConfig.setCanMigrate(false); - - dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(pgConfig); - } else { - ObserveDataSourceConfigurationRest restConfig = model.getRestConfig(); - - dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(restConfig); - } - - createConfigurationDto = model.toImportReferentielSourceConfig(); - - ObserveDataSourceConfiguration importReferentialConfig = createConfigurationDto.getImportReferentialDataSourceConfiguration(); - - - if (importReferentialConfig != null) { - - if (log.isInfoEnabled()) { - log.info("Use referentiel import data source " + importReferentialConfig.getLabel()); - } - - checkImportDbVersion(model, importReferentialConfig); - - } - - // data import - - ObserveSwingDataSource importDataConfig = model.toImportDataSourceConfig(); - - if (importDataConfig != null) { - - if (log.isInfoEnabled()) { - log.info("Use data import data source " + importDataConfig.getLabel()); - } - - checkImportDbVersion(model, importDataConfig.getConfiguration()); - - DataSelectionModel dataModel = model.getSelectDataModel(); - - ImmutableSet<String> importDataIds = ImmutableSet.copyOf( - dataModel.getSelectedData() - .stream() - .map(DataReference::getId) - .collect(Collectors.toSet())); - - createConfigurationDto.setImportDataConfiguration(importDataConfig.getConfiguration(), importDataIds); - } - - users = model.getSecurityModel().getUsers(); - - super.initTask(model); - } - - @Override - protected String getPgLabel() { - return t("observe.storage.label.db.to.create"); - } - - @Override - protected void execute() throws Exception { - if (log.isInfoEnabled()) { - log.info("Create db..."); - } - - try { - dataSource.create(createConfigurationDto); - - if (log.isInfoEnabled()) { - log.info("Open [" + dataSource.getLabel() + "] and create it."); - } - - } finally { - if (dataSource.isOpen()) { - dataSource.close(); - } - } - } - - @Override - protected void applySecurity() { - if (log.isInfoEnabled()) { - log.info("Apply security..."); - } - dataSource.applySecurity(users); - } - }; - } - }, - /** - * pour mettre à jour une base distante. - * - * Il faut au préalable avoir une base en version {@code 1.0}. - */ - UPDATE(n("observe.obstuna.action.update"), - n("observe.obstuna.action.update.description"), - Versions.valueOf("1.0")) { - @Override - public RemoteUILauncher newLauncher(JAXXContext context, Window frame) { - return new RemoteUILauncher(this, context, frame, t(getLabel())) { - - protected ObserveSwingDataSource dataSource; - protected ObserveDataSourceInformation dataSourceInformation; - protected Version targetVersion; - protected Set<ObserveDbUserDto> users; - - @Override - protected void initTask(StorageUIModel model) throws Exception { - - if (DbMode.USE_REMOTE.equals(model.getDbMode())) { - ObserveDataSourceConfigurationTopiaPG pgConfig = model.getPgConfig(); - - dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(pgConfig); - - } else { - - ObserveDataSourceConfigurationRest restConfig = model.getRestConfig(); - - dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(restConfig); - } - - targetVersion = ObserveSwingApplicationContext.get().getConfig().getModelVersion(); - - users = model.getSecurityModel().getUsers(); - - dataSourceInformation = model.getDataSourceInformation(); - - } - - @Override - protected void execute() throws Exception { - - dataSource.migrateData(dataSourceInformation, targetVersion); - } - - @Override - protected String getPgLabel() { - return t("observe.storage.label.db.to.update"); - } - - @Override - protected void applySecurity() { - if (log.isInfoEnabled()) { - log.info("Apply security..."); - } - dataSource.applySecurity(users); - } - }; - } - }, - /** - * pour mettre à jour la sécurité d'une base obstuna. - * - * Il faut au préalable avoir une base en version {@code 1.4}. - */ - SECURITY(n("observe.obstuna.action.security"), - n("observe.obstuna.action.security.description"), - Versions.valueOf("1.4")) { - @Override - public RemoteUILauncher newLauncher(JAXXContext context, Window frame) { - return new RemoteUILauncher(this, context, frame, t(getLabel())) { - - protected ObserveSwingDataSource dataSource; - protected Set<ObserveDbUserDto> users; - - @Override - protected void initTask(StorageUIModel model) throws Exception { - - if (DbMode.USE_REMOTE.equals(model.getDbMode())) { - ObserveDataSourceConfigurationTopiaPG pgConfig = model.getPgConfig(); - - // pas autorise a migrer automatiquement - pgConfig.setCanMigrate(false); - - dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(pgConfig); - } else { - ObserveDataSourceConfigurationRest restConfig = model.getRestConfig(); - - dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(restConfig); - } - - users = model.getSecurityModel().getUsers(); - - } - - @Override - protected String getPgLabel() { - return t("observe.storage.label.db.to.update.security"); - } - - @Override - protected void applySecurity() { - if (log.isInfoEnabled()) { - log.info("Apply security..."); - } - dataSource.applySecurity(users); - } - }; - } - }; - - /** Logger */ - private static final Log log = LogFactory.getLog(ObstunaAdminAction.class); - - private final String label; - - private final String description; - - private final Version requiredVersion; - - ObstunaAdminAction(String label, - String description, - Version requiredVersion) { - this.label = label; - this.description = description; - this.requiredVersion = requiredVersion; - } - - public String getLabel() { - return label; - } - - public String getDescription() { - return description; - } - - public Version getRequiredVersion() { - return requiredVersion; - } - - public static ObstunaAdminAction valueOfIgnoreCase(String value) { - for (ObstunaAdminAction step : ObstunaAdminAction.values()) { - if (step.name().equalsIgnoreCase(value)) { - return step; - } - } - return null; - } - - public abstract RemoteUILauncher newLauncher(JAXXContext context, - Window frame); -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/RemoteUILauncher.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/RemoteUILauncher.java deleted file mode 100644 index 86ead38..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/RemoteUILauncher.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.storage; - -import fr.ird.observe.db.constants.DbMode; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.storage.tabs.SecurityModel; -import jaxx.runtime.JAXXContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.awt.Window; -import java.util.ArrayList; -import java.util.List; - -/** - * Un wizard pour effectuer des opération de création ou mise à jour d'une - * base distante. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public abstract class RemoteUILauncher extends StorageUILauncher { - - /** Logger */ - private static final Log log = LogFactory.getLog(RemoteUILauncher.class); - - protected ObstunaAdminAction action; - - public RemoteUILauncher(ObstunaAdminAction action, - JAXXContext context, - Window frame, - String title) { - super(context, frame, title); - this.action = action; - } - - @Override - protected void init(StorageUI ui) { - super.init(ui); - - StorageUIModel model = ui.getModel(); - model.setCanCreateLocalService(false); - model.setCanUseLocalService(false); - model.setCanUseRemoteService(true); - model.setCanUseServerService(true); - model.setDbMode(DbMode.USE_REMOTE); - model.setAdminAction(action); - - List<StorageStep> steps = new ArrayList<>(); - steps.add(StorageStep.CONFIG); - - if (action == ObstunaAdminAction.CREATE) { - - // configuration de l'import de référentiel - steps.add(StorageStep.CONFIG_REFERENTIEL); - - // configuration de l'import de données - steps.add(StorageStep.CONFIG_DATA); - - // choix des données à importer - steps.add(StorageStep.SELECT_DATA); - - } - steps.add(StorageStep.ROLES); - steps.add(StorageStep.CONFIRM); - - model.setSteps(steps.toArray(new StorageStep[steps.size()])); - ui.setSize(800, 600); - } - - @Override - protected void doAction(StorageUI ui) { - super.doAction(ui); - StorageUIModel model = ui.getModel(); - SecurityModel securityModel = model.getSecurityModel(); - if (log.isInfoEnabled()) { - log.info("Will use security model " + securityModel); - } - - try { - - initTask(model); - } catch (Exception e) { - UIHelper.handlingError("Could not init task.", e); - throw new RuntimeException(e); - } - - try { - execute(); - - } catch (Exception e) { - UIHelper.handlingError("Could not create db.", e); - throw new RuntimeException(e); - } - - try { - applySecurity(); - } catch (Exception e) { - UIHelper.handlingError("Could not apply security to db.", e); - throw new RuntimeException(e); - } - } - -// @Override -// protected void doClose(StorageUI ui, boolean wasCanceld) { -// super.doClose(ui, wasCanceld); -// ui.setVisible(false); -// } - - protected abstract String getPgLabel(); - - protected void initTask(StorageUIModel model) throws Exception { - // FIXME - // task.init(model.toPostgresStorageConfig(getPgLabel()), model.getSecurityModel(), false); - } - - protected void execute() throws Exception { - } - - protected void applySecurity() { - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/StorageBackupUILauncher.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/StorageBackupUILauncher.java deleted file mode 100644 index 50f4daa..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/StorageBackupUILauncher.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.storage; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.db.constants.DbMode; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.ui.storage.tabs.DataSelectionModel; -import jaxx.runtime.JAXXContext; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.awt.Window; -import java.io.File; -import java.util.Set; - -/** - * Un wizard pour effectuer des backup de storages. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.2 - */ -public class StorageBackupUILauncher extends StorageUILauncher { - - - /** - * Logger - */ - private static final Log log = LogFactory.getLog(StorageBackupUILauncher.class); - - public StorageBackupUILauncher(JAXXContext context, - Window frame, - String title) { - super(context, frame, title); - } - - @Override - protected void init(StorageUI ui) { - super.init(ui); - ui.getBACKUP().getDoBackup().setSelected(true); - ui.getBACKUP().getDoBackup().setVisible(false); - - ObserveSwingDataSource source = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); - - StorageUIModel model = ui.getModel(); - model.setCanCreateLocalService(false); - - if (source.isLocal()) { - model.setCanUseLocalService(true); - model.setDbMode(DbMode.USE_LOCAL); - } else if (source.isRemote()) { - model.setCanUseRemoteService(true); - model.setDbMode(DbMode.USE_REMOTE); - } else if (source.isServer()) { - model.setCanUseServerService(true); - model.setDbMode(DbMode.USE_SERVER); - } - - model.setSteps(StorageStep.BACKUP, - StorageStep.SELECT_DATA, - StorageStep.CONFIRM - ); - ui.setTitle(title); - try { - - // Selection des données uniquement pour une base locale - // Voir https://forge.codelutin.com/issues/7207 - boolean selectAllData = model.isLocal(); - getStorageUIHandler().initSelectData(ui, source, selectAllData); - - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error(e, e); - } - } - } - - @Override - protected void doAction(StorageUI ui) { - super.doAction(ui); - StorageUIHandler handler = getStorageUIHandler(); - - ObserveSwingDataSource source = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); - - StorageUIModel storageModel = ui.getModel(); - File backupFile = storageModel.getBackupFile(); - - DataSelectionModel dataModel = storageModel.getSelectDataModel(); - Set<DataReference> trips = null; - if (dataModel != null && !dataModel.isDataFull()) { - // on renseigne les marees a exporter uniquement si - // on en a selectionner, de plus si on a selectionne - // toutes les marees, on le les passe pas : car c un dump - // complet de la base. - trips = dataModel.getSelectedData(); - } - handler.backupLocalDatabase(source, backupFile, trips); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/StorageStep.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/StorageStep.java deleted file mode 100644 index e279240..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/StorageStep.java +++ /dev/null @@ -1,113 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.storage; - -import jaxx.runtime.swing.wizard.WizardStep; - -import static org.nuiton.i18n.I18n.n; - -/** - * Pour caractériser les étapes (correspond aux onglets de l'ui). - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public enum StorageStep implements WizardStep { - - /** pour choisir le mode de connexion (local ou remote) */ - CHOOSE_DB_MODE( - n("observe.storage.step.dbMode"), - n("observe.storage.step.dbMode.description") - ), - /** - * pour configurer la connexion à la source de données (uniquement si - * besoin) - */ - CONFIG( - n("observe.storage.step.config"), - n("observe.storage.step.config.description") - ), - /** - * pour configurer le referentiel a utiliser lors de la creation d'une base - * distante - */ - CONFIG_REFERENTIEL( - n("observe.storage.step.configReferentiel"), - n("observe.storage.step.configReferentiel.description") - ), - /** - * pour configurer la sources des données a utiliser lors de la creation d'une base - * distante - */ - CONFIG_DATA( - n("observe.storage.step.configData"), - n("observe.storage.step.configData.description") - ), - /** - * pour effectuer une sauvegarde de la base locale. (uniquement disponible - * si on veut générer une nouvelle base locale) - */ - BACKUP( - n("observe.storage.step.backup"), - n("observe.storage.step.backup.description") - ), - /** - * pour sélectionner les données à sauvegarder (unqiuement sur une ui de - * backup) - */ - SELECT_DATA( - n("observe.storage.step.selectData"), - n("observe.storage.step.selectData.description") - ), - /** - * Pour sélectionner les rôles à appliquer pour la création ou mise à jour - * d'une base distante - */ - ROLES( - n("observe.storage.step.roles"), - n("observe.storage.step.roles.description") - ), - /** pour confirmer et réaliser les actions demandées */ - CONFIRM( - n("observe.storage.step.confirm"), - n("observe.storage.step.confirm.description") - ); - - private final String label; - - private final String description; - - StorageStep(String label, String description) { - this.label = label; - this.description = description; - } - - @Override - public String getLabel() { - return label; - } - - @Override - public String getDescription() { - return description; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/StorageUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/StorageUI.jaxx deleted file mode 100644 index 404516d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/StorageUI.jaxx +++ /dev/null @@ -1,189 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<JDialog id="storageMain" - implements='jaxx.runtime.swing.wizard.WizardUI<StorageStep, StorageUIModel>' - width='550' height='600' defaultCloseOperation='dispose_on_close' - > - - <import> - fr.ird.observe.ui.UIHelper - fr.ird.observe.ui.storage.tabs.StorageTabUI - fr.ird.observe.ui.storage.tabs.BackupUI - fr.ird.observe.ui.storage.tabs.ChooseDbModeUI - fr.ird.observe.ui.storage.tabs.ConfigReferentielUI - fr.ird.observe.ui.storage.tabs.ConfigDataUI - fr.ird.observe.ui.storage.tabs.ConfigUI - fr.ird.observe.ui.storage.tabs.ConfirmUI - fr.ird.observe.ui.storage.tabs.RolesUI - fr.ird.observe.ui.storage.tabs.SelectDataUI - - java.awt.Window - - jaxx.runtime.JAXXContext - javax.swing.UIManager - </import> - - <StorageUIHandler id='handler' initializer='getContextValue(StorageUIHandler.class)'/> - - <StorageUIModel id='model' javaBean='getContextValue(StorageUIModel.class)'/> - - <!-- le bloqueur d'ui lorsqu'une action est en cours ou annulée --> - <BlockingLayerUI id='busyBlockLayerUI'/> - - <CardLayout> - <!-- les differents contenu d'onglets --> - <ChooseDbModeUI id='CHOOSE_DB_MODE' constructorParams='this'/> - <ConfigUI id='CONFIG' constructorParams='this'/> - <ConfigReferentielUI id='CONFIG_REFERENTIEL' constructorParams='this'/> - <ConfigDataUI id='CONFIG_DATA' constructorParams='this'/> - <BackupUI id='BACKUP' constructorParams='this'/> - <SelectDataUI id='SELECT_DATA' constructorParams='this'/> - <RolesUI id='ROLES' constructorParams='this'/> - <ConfirmUI id='CONFIRM' constructorParams='this'/> - </CardLayout> - - <script><![CDATA[ - -private boolean contextInitialized; - -public StorageUI(Window owner, JAXXContext parentContext) { - super(owner); - // verification du context parent - UIHelper.checkJAXXContextEntry(parentContext, UIHelper.newContextEntryDef(StorageUIHandler.class)); - UIHelper.checkJAXXContextEntry(parentContext, UIHelper.newContextEntryDef(StorageUIModel.class)); - UIHelper.checkJAXXContextEntry(parentContext, UIHelper.newContextEntryDef("apply", Runnable.class)); - UIHelper.checkJAXXContextEntry(parentContext, UIHelper.newContextEntryDef("cancel", Runnable.class)); - - if (owner != null) { - setContextValue(owner, "parent"); - } - UIHelper.initContext(this, parentContext); - contextInitialized = true; -} - -public void destroy() { - getHandler().destroy(this); -} - -@Override -public void dispose() { - if (log.isDebugEnabled()) { - log.debug("dispose storage ui " + this); - } - destroy(); - super.dispose(); -} - -@Override -protected void finalize() throws Throwable { - super.finalize(); - destroy(); -} - -@Override -public void start() { - getHandler().start(this); -} - -@Override -public StorageStep getSelectedStep() { - int index = tabs.getSelectedIndex(); - StorageTabUI c = null; - if (index > -1) { - c = (StorageTabUI) tabs.getComponentAt(index); - } - StorageStep result = c == null ? null : c.getStep(); - return result; -} - -@Override -public StorageTabUI getStepUI(StorageStep step) { - if (step != null) { - return (StorageTabUI) getObjectById(step.name()); - } - return null; -} - -@Override -public StorageTabUI getStepUI(int stepIndex) { - if (stepIndex > tabs.getTabCount()) { - return null; - } - return (StorageTabUI) tabs.getComponentAt(stepIndex); -} - -@Override -public StorageTabUI getSelectedStepUI() { - StorageStep step = getSelectedStep(); - StorageTabUI ui = getStepUI(step); - return ui; -} - -@Override -public void onStepChanged(StorageStep oldStep, StorageStep newStep) { - getHandler().onStepChanged(this, oldStep, newStep); -} - -@Override -public void onStepsChanged(StorageStep[] steps) { - -} - -void $afterCompleteSetup() { - getHandler().initUI(this); -} -]]> - </script> - - <!-- les onglets --> - <JTabbedPane id='tabs' decorator='boxed' - constraints='BorderLayout.CENTER' - onStateChanged='if (getSelectedStep() != null) { getModel().gotoStep(getSelectedStep()); }'/> - - <!-- les actions --> - <Table id='actions' weightx='1' fill='both' constraints='BorderLayout.SOUTH'> - <row> - <cell weightx='0.5' fill="both"> - <!-- pour annuler --> - <JButton id="cancelAction" - onActionPerformed='getHandler().launchCancel(this)'/> - </cell> - <cell weightx='0.5' fill="both"> - <!-- pour aller sur l'onglet précédent --> - <JButton id="previousAction" - onActionPerformed='getModel().gotoPreviousStep()'/> - </cell> - <cell weightx='0.5' fill="both"> - <!-- pour aller sur l'onglet suivant --> - <JButton id="nextAction" - onActionPerformed='getModel().gotoNextStep()'/> - </cell> - <cell weightx='0.5' fill="both"> - <!-- pour apliquer la configuration --> - <JButton id="applyAction" - onActionPerformed='getHandler().launchApply(this)'/> - </cell> - </row> - </Table> - -</JDialog> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/StorageUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/StorageUIHandler.java deleted file mode 100644 index a64a8a7..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/StorageUIHandler.java +++ /dev/null @@ -1,813 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.storage; - -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableSet; -import fr.ird.observe.ObserveActionExecutor; -import fr.ird.observe.ObserveRunner; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.ObserveTextGenerator; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.db.constants.ConnexionStatus; -import fr.ird.observe.db.constants.CreationMode; -import fr.ird.observe.db.constants.DbMode; -import fr.ird.observe.db.event.ObserveSwingDataSourceEvent; -import fr.ird.observe.db.event.ObserveSwingDataSourceListenerAdapter; -import fr.ird.observe.services.configuration.ObserveDataSourceConfiguration; -import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationRest; -import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaH2; -import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaPG; -import fr.ird.observe.services.configuration.ObserveDataSourceInformation; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.DataSourceCreateConfigurationDto; -import fr.ird.observe.services.dto.ObserveDbUserDto; -import fr.ird.observe.services.service.AddSqlScriptProducerRequest; -import fr.ird.observe.services.service.SqlScriptProducerService; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.storage.tabs.DataSelectionModel; -import fr.ird.observe.ui.storage.tabs.RolesTableModel; -import fr.ird.observe.ui.storage.tabs.SecurityModel; -import fr.ird.observe.ui.storage.tabs.StorageTabUI; -import jaxx.runtime.context.DefaultApplicationContext.AutoLoad; -import jaxx.runtime.swing.wizard.WizardUILancher; -import org.apache.commons.io.FileUtils; -import org.apache.commons.io.IOUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JTabbedPane; -import java.awt.Component; -import java.awt.Window; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.util.Date; -import java.util.Set; -import java.util.stream.Collectors; - -import static org.nuiton.i18n.I18n.t; - -/** - * Le handler des actions sur base. - * - * On retrouve ici les méthodes pour importer, exporter, faire des backup, - * synchroniser les bases. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -@AutoLoad -public class StorageUIHandler { - - /** Logger */ - private static final Log log = LogFactory.getLog(StorageUIHandler.class); - - /** - * Prépare une service de persistance à partir d'un modèle. - * - * Le service ne sera pas ouvert. - * - * @param model le modèle de la source de données - * @return le service de persistance initialisé mais non ouvert. - */ - public ObserveSwingDataSource newDataSourceFromModel( - StorageUIModel model) { - - ObserveSwingDataSource dataSource = null; - ObserveDataSourceConfiguration configuration; - switch (model.getDbMode()) { - case CREATE_LOCAL: - case USE_LOCAL: - configuration = model.toH2StorageConfig(t("observe.storage.label.local")); - - dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(configuration); - - dataSource.addObserveSwingDataSourceListener( - new ObserveSwingDataSourceListenerAdapter() { - - @Override - public void onOpened(ObserveSwingDataSourceEvent event) { - ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); - // la base locale existe desormais - context.getConfig().setLocalStorageExist(true); - } - }); - - break; - case USE_REMOTE: - configuration = model.toPGStorageConfig(t("observe.storage.label.remote")); - dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(configuration); - break; - case USE_SERVER: - configuration = model.toRestStorageConfig(t("observe.storage.label.server")); - dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(configuration); - break; - } - - return dataSource; - } - - public void initUI(final StorageUI ui) { - - StorageUIModel model = ui.getModel(); - - // on écoute les changements d'étapes - model.addPropertyChangeListener(StorageUIModel.STEP_PROPERTY_NAME, evt -> { - StorageUIModel model1 = (StorageUIModel) evt.getSource(); - StorageStep oldStep = (StorageStep) evt.getOldValue(); - StorageStep newStep = (StorageStep) evt.getNewValue(); - if (log.isDebugEnabled()) { - log.debug("step has changed <old:" + oldStep + ", new:" + newStep + ">"); - } - int oldStepIndex = oldStep == null ? -1 : model1.getStepIndex(oldStep); - int newStepIndex = model1.getStepIndex(newStep); - JTabbedPane tabs = ui.getTabs(); - if (oldStepIndex + 1 == newStepIndex) { - - // creation d'un nouvel onglet - StorageTabUI c = (StorageTabUI) ui.getObjectById(newStep.name()); - String title = t(newStep.getLabel()); - String tip = t(newStep.getDescription()); - - if (log.isDebugEnabled()) { - log.debug("Create tab " + title + " ui = " + c); - } - tabs.addTab(title, null, c, tip); - tabs.setMnemonicAt(newStepIndex, title.charAt(0)); - - // selection du nouvel onglet - int index = tabs.indexOfComponent(c); - if (index > -1) { - tabs.setSelectedIndex(index); - } - ui.onStepChanged(oldStep, newStep); - - } else if (oldStepIndex > newStepIndex) { - - // il s'agit d'un retour en arrière - // on supprime tous les onglets obsoletes - int index = newStepIndex + 1; - while (tabs.getTabCount() > index) { - if (log.isDebugEnabled()) { - log.debug("remove tab : " + index); - } - tabs.remove(index); - } - - ui.onStepChanged(oldStep, newStep); - } else { - throw new IllegalStateException("can not go from " + oldStep + " to " + newStep); - } - }); - - // initialisation des onglets - ui.CHOOSE_DB_MODE.init(); - ui.CONFIG.init(); - ui.CONFIG_REFERENTIEL.init(); - ui.CONFIG_DATA.init(); - ui.BACKUP.init(); - ui.SELECT_DATA.init(); - ui.ROLES.init(); - ui.CONFIRM.init(); - - // recuperation de la source de données en cours d'utilisation - ObserveDataSourceConfiguration dataSourceConfiguration = ui.getContextValue(ObserveDataSourceConfiguration.class); - - // chargement du modèle - model.init(ui, dataSourceConfiguration); - } - - public void start(StorageUI ui) { - - // on demarre le modele pour le type de base connu - ui.getModel().start(ui.getModel().getDbMode()); - - // centrage sur la frame parent - UIHelper.center(ui.getContextValue(Window.class, "parent"), ui); - - // affichage ui - ui.setVisible(true); - } - - public void onStepChanged(StorageUI ui, StorageStep oldStep, StorageStep newStep) { - if (newStep == null) { - return; - } - if (log.isDebugEnabled()) { - log.debug("new step : " + newStep); - } - StorageUIModel model = ui.getModel(); - - boolean mustRecompute = oldStep == null || oldStep.ordinal() < newStep.ordinal(); - - if (StorageStep.CONFIG == newStep) { - - model.updateEditConfigValues(); - - if (mustRecompute) { - - // on redemande un test de connexion a chaque fois qu'on rentre dans l'onglet - model.setConnexionStatus(ConnexionStatus.UNTESTED); - } - - } - - if (StorageStep.CONFIG_REFERENTIEL == newStep && mustRecompute) { - - // mise à jour de l'univers des étapes (ajout/suppression étape confg_data et select_data possible) - ui.getModel().updateUniverse(); - - } - - if (StorageStep.CONFIG_DATA == newStep && mustRecompute) { - - // mise à jour de l'univers des étapes (ajout/suppression étape select_data possible) - ui.getModel().updateUniverse(); - - } - - if (StorageStep.SELECT_DATA == newStep && mustRecompute) { - - if (ObstunaAdminAction.CREATE == ui.getModel().getAdminAction() - && (model.getSelectDataModel() == null || model.getSelectDataModel().isEmpty())) { - - // récupération des données possibles à importer - initSelectData(ui); - - } - - } - - if (StorageStep.ROLES == newStep && mustRecompute) { - - // récupération des rôles de la base cible - updateSecurity(model, ui.getROLES().getRolesModel()); - - } - - if (StorageStep.CONFIRM == newStep) { - - // generation du rapport - String text = computeReport(ui, oldStep); - ui.CONFIRM.getResume().setText(text); - - } - - } - - public void launchApply(final StorageUI ui) { - - ui.getModel().setAlreadyApplied(true); - - Runnable action = WizardUILancher.APPLY_DEF.getContextValue(ui); - - if (action == null) { - final StorageUILauncher launcher = ui.getContextValue(StorageUILauncher.class); - - action = () -> { - try { - launcher.doAction(ui); - } finally { - launcher.doClose(ui, false); - } - }; - } - ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); - if (mainUI == null) { - if (log.isWarnEnabled()) { - log.warn("Launch standalone apply action " + action); - } - //FIXME Action executor will not execute task until previous is finished... - action.run(); - } else { - ObserveActionExecutor executor = ObserveRunner.getActionExecutor(); - - executor.addAction(t("observe.action.storage.applyAction"), action); - } - } - - public void launchCancel(StorageUI ui) { - - Runnable action = WizardUILancher.CANCEL_DEF.getContextValue(ui); - - ObserveMainUI mainUI = ObserveSwingApplicationContext.get().getMainUI(); - if (mainUI == null) { - if (log.isWarnEnabled()) { - log.warn("Launch standalone cancel action " + action); - } - //FIXME Action executor will not execute task until previous is finished... - if (action != null) { - action.run(); - } - } else { - ObserveActionExecutor executor = ObserveRunner.getActionExecutor(); - executor.addAction(t("observe.storage.action.cancel"), action); - } - } - - /** - * Utiliser le storage defini dans le modèle donné. - * - * @param model le model++ du storage a creer ou utiliser - */ - public void doChangeStorage(StorageUIModel model) { - ObserveSwingApplicationContext observeContext = ObserveSwingApplicationContext.get(); - - ObserveSwingApplicationConfig config = observeContext.getConfig(); - - // faut-il detruire la base locale ? - boolean destroyLocalBase = - config.isLocalStorageExist() && - model.getDbMode() == DbMode.CREATE_LOCAL; - - if (log.isDebugEnabled()) { - log.debug(">>> should destroy local db ? " + destroyLocalBase); - } - - - ObserveSwingDataSource currentDataSource = observeContext.getDataSourcesManager().getMainDataSource(); - - ObserveSwingDataSource localDataSource = null; - - if (currentDataSource != null && currentDataSource.isLocal()) { - localDataSource = currentDataSource; - } - - boolean localDbIsSane = true; - if (destroyLocalBase || model.isDoBackup()) { - if (localDataSource == null) { - ObserveDataSourceConfigurationTopiaH2 localConfiguration = config.getDataSourceConfigurationH2(t("observe.storage.label.local")); - - // la base ne doit pas etre mise a jour dans ce cas - localConfiguration.setCanMigrate(false); - - // on charge un storage sur la base locale - localDataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(localConfiguration); - } - - // Let's check if the datasource is opened or not : - // we could have close the datasource through the ui - // If the datasource is closed, we try to open it - if (!localDataSource.isOpen()) { - try { - - localDataSource.open(); - - } catch (Exception e) { - // on a pas reussi à ouvrir la base locale - // cela ne doit pas empécher de continuer - // il faut juste supprimer physiquement le repertoire - // de la base - UIHelper.handlingError(t("observe.error.storage.could.not.load.local.db", e.getMessage()), e); - - // on conserve l'état - localDbIsSane = false; - - // pour la suite on fait comme si il n'y a pas de local storage - localDataSource = null; - } - } - } - - if (model.isDoBackup()) { - if (!localDbIsSane) { - - // la base locale n'est pas saine, on doit arrêter l'objectOperation - // de changement de base sous peine de perdre la base. - Exception e = new Exception(t("observe.error.storage.could.not.backup.unsane.local.db")); - UIHelper.handlingError(e); - return; - } - // effectue la backup de la base locale existante - File f = model.getBackupFile(); - if (log.isDebugEnabled()) { - log.debug(">>> do backup with " + localDataSource + " in " + f); - } - try { - SqlScriptProducerService dumpProducerService = localDataSource.newSqlScriptProducerService(); - backupLocalDatabase(dumpProducerService, f); - } catch (Exception e) { - UIHelper.handlingError(e); - return; - } - } - - if (destroyLocalBase) { - if (log.isDebugEnabled()) { - log.debug(">>> destroy local db " + localDataSource); - } - if (!localDbIsSane) { - // la base locale n'est pas saine, on va supprimer directement - // le dossier de la base - File localDBDirectory = config.getLocalDBDirectory(); - if (log.isInfoEnabled()) { - log.info(">>> destroy local db directory " + localDBDirectory); - } - try { - FileUtils.deleteDirectory(localDBDirectory); - } catch (IOException e) { - UIHelper.handlingError(e); - } - } else { - try { - localDataSource.destroy(); - } catch (Exception e) { - UIHelper.handlingError(e); - return; - } - } - } - - // suppression du storage precedent - if (currentDataSource != null && currentDataSource.isOpen()) { - if (log.isDebugEnabled()) { - log.debug(">>> close main storage " + currentDataSource); - } - // on doit fermer le storage en cours d'utilisation - currentDataSource.close(); - } - - // suppression du storage local - if (localDataSource != null && localDataSource != currentDataSource) { - // ce cas peut arriver lorsque l'on fait juste une backup - // sans vouloir supprimer la base locale - if (log.isDebugEnabled()) { - log.debug(">>> close local storage " + localDataSource); - } - // on doit fermer le storage local ouvert - localDataSource.close(); - } - - localDataSource = null; - - if (log.isDebugEnabled()) { - log.debug("Will create new storage..."); - } - - // preparation du nouveau storage - - try { - - currentDataSource = newDataSourceFromModel(model); - - // si on utilise la base local on lance une migration de la base si necessaire - if (DbMode.USE_LOCAL.equals((model.getDbMode()))) { - - ObserveDataSourceInformation dataSourceInformation = currentDataSource.checkCanConnect(); - - currentDataSource.migrateData(dataSourceInformation, config.getModelVersion()); - - } - - observeContext.getDataSourcesManager().setMainDataSource(currentDataSource); - observeContext.prepareMainStorage(currentDataSource, true); - - if (model.getDbMode() == DbMode.CREATE_LOCAL) { - - DataSourceCreateConfigurationDto creationConfigurationDto = model.getCreationConfigurationDto(); - - try { - - currentDataSource.create(creationConfigurationDto); - - } catch (Exception e) { - //si il y a une erreur lor de la création de la base locla - - // on suprimer la base - File localDBDirectory = config.getLocalDBDirectory(); - if (log.isInfoEnabled()) { - log.info(">>> destroy local db directory " + localDBDirectory); - } - try { - FileUtils.deleteDirectory(localDBDirectory); - } catch (IOException e2) { - UIHelper.handlingError(e2); - } - - config.setLocalStorageExist(false); - observeContext.getDataSourcesManager().setMainDataSource(null); - - throw e; - } - } else { - // ouverture du nouveau storage - currentDataSource.open(); - } - - if (DbMode.CREATE_LOCAL.equals(model.getDbMode()) - && (CreationMode.IMPORT_REMOTE_STORAGE.equals(model.getCreationMode()) || CreationMode.IMPORT_SERVER_STORAGE.equals(model.getCreationMode())) - && config.isLocalStorageExist()) { - // si on a creer la base locale a partir d'un import d'une base - // distante, on sauvegarde la base locale comme dump initial - // il s'agit d'un dump du référentiel - File f = config.getInitialDbDump(); - if (f.exists()) { - // on supprime le dump sql de la base embarquée - if (!f.delete()) { - throw new IllegalStateException("could not delete " + f); - } - } - if (log.isInfoEnabled()) { - log.info(">>> create initial dump with " + localDataSource + " in " + f); - } - try { - SqlScriptProducerService dumpProducerService = observeContext.getMainDataSourceServicesProvider().newSqlScriptProducerService(); - backupLocalDatabase(dumpProducerService, f); - config.setInitialDumpExist(true); - } catch (Exception e) { - UIHelper.handlingError(e); - } - } - - if (log.isInfoEnabled()) { - log.info(">>> main storage opened " + currentDataSource.getLabel()); - } - - if (model.isStoreRemoteConfig()) { - storeRemoteConfig(model); - } - - } catch (Exception ex) { - UIHelper.handlingError(ex); - throw new RuntimeException(ex); - } - } - - /** - * Sauvegarder dans la configuration de l'application le paramétrage de la - * source de données distante donnée. - * - * @param model le model de la source de données - */ - public void storeRemoteConfig(StorageUIModel model) { - ObserveSwingApplicationConfig config = ObserveSwingApplicationContext.get().getConfig(); - // on sauvegarde dans le parametrage dans la configuration de - // l'application - - if (model.isEditRemoteConfig()) { - - ObserveDataSourceConfigurationTopiaPG configurationTopiaPG = model.toPGStorageConfig(""); - config.fromStorageConfig(configurationTopiaPG); - - } else if (model.isEditServerConfig()) { - - ObserveDataSourceConfigurationRest configurationRest = model.toRestStorageConfig(""); - config.fromStorageConfig(configurationRest); - - } - } - - /** - * @return le lastName par defaut du fichier de sauvegarde de la base locale - * (expression calculée à partir de la date courante et du pattern - * {@link ObserveSwingApplicationConfig#BACKUP_DB_PATTERN}). - */ - public String getDefaultBackupFilename() { - return String.format(ObserveSwingApplicationConfig.BACKUP_DB_PATTERN, new Date()); - } - - /** - * Effectue une sauvegarde de la base locale vers le fichier choisi. - * - * @param dumpProducerService le service de dump - * @param dst le fichier de sauvegarde - */ - public void backupLocalDatabase(SqlScriptProducerService dumpProducerService, File dst) { - if (dst == null) { - throw new IllegalArgumentException( - "file where to backup can not be null"); - } - if (log.isDebugEnabled()) { - log.debug(dst); - } - - AddSqlScriptProducerRequest request = AddSqlScriptProducerRequest.forH2().addSchema().addReferential().addAllData(); - byte[] dataDump = dumpProducerService.produceAddSqlScript(request); - - try (FileOutputStream outputStream = new FileOutputStream(dst)) { - - outputStream.write(dataDump); - } catch (Exception e) { - UIHelper.handlingError(e); - } - } - - /** - * Effectue une sauvegarde d'un service de persitances vers le fichier - * choisi. - * - * On peut spécifier les donnéees à exporter via le paramètre {@code - * marees}. - * - * <b>Note:</b> Si ce paramètre vaut {@code null}, on export tout. - * - * @param dataSource la source de donnée qui encapsule la base locale - * @param dst le fichier de sauvegarde - * @param trips les marees a exporter (si {@code null} on exporte tout) - */ - public void backupLocalDatabase(ObserveSwingDataSource dataSource, - File dst, - Set<DataReference> trips) { - - SqlScriptProducerService dumpService = dataSource.newSqlScriptProducerService(); - - - if (trips == null) { - if (log.isInfoEnabled()) { - log.info("will export all datas."); - } - backupLocalDatabase(dumpService, dst); - return; - } - if (dst == null) { - throw new IllegalArgumentException( - "file where to backup can not be null"); - } - if (log.isInfoEnabled()) { - log.info("will export " + trips.size() + " marees to " + dst); - } - if (log.isDebugEnabled()) { - log.debug(trips); - } - - // on doit dumper la base distante dans une base h2 et en faire - // la sauvegarde - - ImmutableSet<String> tripIds = ImmutableSet.copyOf(trips.stream().map(DataReference.ID_FUNCTION).collect(Collectors.toSet())); - - AddSqlScriptProducerRequest request = AddSqlScriptProducerRequest.forH2().addSchema().addReferential().dataIdsToAdd(tripIds); - byte[] dump = dumpService.produceAddSqlScript(request); - - try (FileOutputStream fileOutputStream = new FileOutputStream(dst)) { - - IOUtils.write(dump, fileOutputStream); - - } catch (IOException e) { - UIHelper.handlingError(e); - } - } - - public String computeReport(StorageUI ui, StorageStep step) { - if (log.isDebugEnabled()) { - log.debug("Build report from step " + step); - } - StorageUIModel model = ui.getModel(); - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ObserveTextGenerator textGenerator = applicationContext.getTextGenerator(); - String report = textGenerator.getDataSourceConnectionReport(model); - return report; - } - - public void destroy(StorageUI ui) { - ui.getModel().destroy(); - if (log.isDebugEnabled()) { - log.debug("destroy ui " + ui.getName()); - } - UIHelper.TabbedPaneIterator<Component> itr = - UIHelper.newTabbedPaneIterator(ui.getTabs()); - for (; itr.hasNext(); ) { - StorageTabUI tab = - (StorageTabUI) itr.next(); - if (log.isDebugEnabled()) { - log.debug("destroy ui " + tab.getName()); - } - tab.destroy(); - } - UIHelper.destroy(ui); - } - - protected DecoratorService getDecoratorService() { - DecoratorService decoratorService = - ObserveSwingApplicationContext.get().getDecoratorService(); - return decoratorService; - } - - public void initSelectData(StorageUI ui, ObserveSwingDataSource source, boolean selectAll) { - - StorageUIModel model = ui.getModel(); - - try { - - Preconditions.checkState(source != null, "Can't select data on a null dataSource"); - - DataSelectionModel dataModel = new DataSelectionModel(); - dataModel.setUseData(true); - dataModel.setUseOpenData(true); - dataModel.setUseReferentiel(false); - - DataSelectionModel.populate(dataModel, source); - - if (selectAll) { - - dataModel.addAllSelectedData(); - - } - - // positionnement du model de selection de données - // dans le model du wizard - model.setSelectDataModel(dataModel); - - // initialisation de l'ui dedié - ui.getSELECT_DATA().initTree(source); - - } catch (Exception e) { - throw new RuntimeException("Could not grab data to select", e); - } - - } - - protected void initSelectData(StorageUI ui) { - - StorageUIModel model = ui.getModel(); - - try { - - // Creation de la data source de lecture des données à sélectionner - ObserveSwingDataSource importDataSource = model.toImportDataSourceConfig(); - - Preconditions.checkState(importDataSource != null, "Can't select data on a null dataSource"); - - try { - - importDataSource.open(); - - model.checkImportDbVersion(importDataSource); - - initSelectData(ui, importDataSource, false); - - } finally { - importDataSource.close(); - } - - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error(e, e); - } - } - } - - protected void updateSecurity(StorageUIModel model, RolesTableModel roleModel) { - - SecurityModel security = model.getSecurityModel(); - - ObserveSwingDataSource dataSource = null; - - switch (model.getDbMode()) { - case USE_REMOTE: - ObserveDataSourceConfigurationTopiaPG pgConfig = model.getPgConfig(); - - dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(pgConfig); - break; - case USE_SERVER: - ObserveDataSourceConfigurationRest restConfig = model.getRestConfig(); - dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(restConfig); - - } - - if (dataSource != null) { - try { - - Set<ObserveDbUserDto> users = dataSource.getUsers(); - - if (log.isInfoEnabled()) { - log.info("Db roles : " + users); - } - - security.init(users); - roleModel.init(security); - - } catch (Exception e) { - throw new RuntimeException("Could not obtain db roles", e); - } finally { - if (dataSource.isOpen()) { - dataSource.close(); - } - } - } - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/StorageUILauncher.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/StorageUILauncher.java deleted file mode 100644 index 7745c8e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/StorageUILauncher.java +++ /dev/null @@ -1,520 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.storage; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.db.constants.DbMode; -import fr.ird.observe.ui.ObserveMainUIHandler; -import fr.ird.observe.ui.UIHelper; -import jaxx.runtime.JAXXContext; -import jaxx.runtime.JAXXObject; -import jaxx.runtime.swing.wizard.BusyChangeListener; -import jaxx.runtime.swing.wizard.WizardModel; -import jaxx.runtime.swing.wizard.WizardUILancher; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.awt.Window; -import java.util.Arrays; -import java.util.Set; -import java.util.stream.Collectors; - -import static org.nuiton.i18n.I18n.t; - -/** - * Le wizard de base pour les opération sur le service de données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class StorageUILauncher extends WizardUILancher<StorageStep, StorageUIModel, StorageUI> { - - /** Logger */ - private static final Log log = LogFactory.getLog(StorageUILauncher.class); - - protected final String title; - - public StorageUILauncher(JAXXContext context, - Window frame, - StorageUIModel model, - String title) { - super(context, frame, StorageUI.class, StorageUIModel.class, model); - this.title = title; - } - - public StorageUILauncher(JAXXContext context, - Window frame, - String title) { - super(context, frame, StorageUI.class, StorageUIModel.class); - this.title = title; - } - - @Override - protected void init(StorageUI ui) { - if (log.isInfoEnabled()) { - log.info("Will init " + ui.getName()); - } - super.init(ui); - if (title != null) { - ui.setTitle(title); - } - BusyChangeListener listener = new BusyChangeListener(ui); - UIHelper.setLayerUI(ui.getTabs(), ui.getBusyBlockLayerUI()); - listener.setBlockingUI(ui.getBusyBlockLayerUI()); - ui.getModel().addPropertyChangeListener(WizardModel.BUSY_PROPERTY_NAME, listener); - ui.setContextValue(this); - } - - @Override - public void start() { - super.start(); - ui.getModel().setBusy(false); - } - - @Override - protected void doCancel(StorageUI ui) { - if (log.isDebugEnabled()) { - log.debug("Will cancel " + ui.getName()); - } - ui.getModel().setBusy(true); - super.doCancel(ui); - ObserveMainUIHandler.restartEdit(); - } - - @Override - protected void doAction(StorageUI ui) { - ui.getModel().setBusy(true); - super.doAction(ui); - } - - protected StorageUIHandler getStorageUIHandler() { - StorageUIHandler handler = - ui.getContextValue(StorageUIHandler.class); - return handler; - } - - @Override - protected void doClose(StorageUI ui, boolean wasCanceled) { - if (log.isDebugEnabled()) { - log.debug("Will close " + ui.getName() + " (was canceled ? " + wasCanceled + ")"); - } - super.doClose(ui, wasCanceled); - ui.getModel().setBusy(false); - ui.dispose(); - } - - /** - * Méthode pour lancer le changement de source de données. - * - * @param rootContext le context applicatif - * @param mainUI main ui - * @param modes les modes optionnel à utiliser - * @param title le titre de la fenetre - * @see StorageUIHandler - * @see StorageUI - */ - public static void changeStorage(final JAXXContext rootContext, - final Window mainUI, - final Set<DbMode> modes, - final String title) { - - new StorageUILauncher(rootContext, mainUI, title) { - - @Override - protected void init(StorageUI ui) { - super.init(ui); - if (log.isDebugEnabled()) { - log.debug("Incoming dbmode : " + modes.stream().map(DbMode::name).collect(Collectors.joining(", "))); - } - StorageUIModel model = ui.getModel(); - if (CollectionUtils.isNotEmpty(modes)) { - if (log.isInfoEnabled()) { - log.info("will use incoming mode " + modes.stream().map(DbMode::name).collect(Collectors.joining(", "))); - } - - model.setExcludeSteps( - Arrays.asList(StorageStep.SELECT_DATA, - StorageStep.BACKUP, - StorageStep.CONFIG_REFERENTIEL, - StorageStep.CONFIG_DATA, - StorageStep.ROLES) - ); - model.setCanCreateLocalService(modes.contains(DbMode.CREATE_LOCAL)); - model.setCanUseLocalService(modes.contains(DbMode.USE_LOCAL)); - model.setCanUseRemoteService(modes.contains(DbMode.USE_REMOTE)); - model.setCanUseServerService(modes.contains(DbMode.USE_SERVER)); - - model.updateUniverse(); - model.setDbMode(modes.stream().findFirst().get()); - - } else { - ObserveSwingApplicationConfig config = ObserveSwingApplicationContext.get().getConfig(); - Boolean localOpened = config.getMainStorageOpenedLocal(); - if (model.isLocalStorageExist() && localOpened != null && localOpened) { - if (log.isDebugEnabled()) { - log.debug("Can not use local db (already opened)"); - } - model.setCanUseLocalService(false); - } - model.setCanCreateLocalService(true); - model.setCanUseRemoteService(true); - model.setCanUseServerService(true); - } - model.updateUniverse(); - } - - @Override - protected void doAction(StorageUI ui) { - super.doAction(ui); - StorageUIHandler handler = getStorageUIHandler(); - handler.doChangeStorage(ui.getModel()); - } - - }.start(); - } - - /** - * Méthode pour lancer l'action de connexion à une base distante. - * - * Cette méthode doit être appelée avant toute action avec une base distante - * : - * - * synchronisation, récupération du référentiel distant... - * - * @param context le context applicatif - * @param mainUI la fenetre principale parent (peut etre null) - * @param model le modèle de source de données à utiliser - * @see StorageUI - */ - public static void obtainRemoteConnexion(final JAXXContext context, - Window mainUI, - final StorageUIModel model) { - obtainConnexion(context, mainUI, model, t("observe.title.connect.remoteDB"), DbMode.USE_REMOTE); - } - - /** - * Méthode pour lancer l'action de connexion à une base distante. - * - * Cette méthode doit être appelée avant toute action avec un server distant - * : - * - * synchronisation, récupération du référentiel distant... - * - * @param context le context applicatif - * @param mainUI la fenetre principale parent (peut etre null) - * @param model le modèle de source de données à utiliser - * @see StorageUI - */ - public static void obtainServerConnexion(final JAXXContext context, - Window mainUI, - final StorageUIModel model) { - obtainConnexion(context, mainUI, model, t("observe.title.connect.serverDB"), DbMode.USE_SERVER); - } - - /** - * Méthode pour lancer l'action de connexion à une source distante. - * - * Cette méthode doit être appelée avant toute action avec un source distante - * : - * - * synchronisation, récupération du référentiel distant... - * - * @param context le context applicatif - * @param mainUI la fenetre principale parent (peut etre null) - * @param model le modèle de source de données à utiliser - * @param title le titre de la fenêtre - * @param model le type deconnexion (base distante ou serveur distant) - * @see StorageUI - */ - public static void obtainConnexion(final JAXXContext context, - Window mainUI, - final StorageUIModel model, - String title, - DbMode dbMode) { - - - if (mainUI == null) { - mainUI = ObserveSwingApplicationContext.get().getMainUI(); - } - addStorageUIHandler(context); - StorageUILauncher launcher = new StorageUILauncher( - context, - mainUI, - model, - title) { - - @Override - protected void init(StorageUI ui) { - StorageUIModel model = ui.getModel(); - - model.setCanCreateLocalService(false); - model.setCanUseLocalService(false); - model.setCanUseRemoteService(true); - model.setCanUseServerService(true); - - model.setExcludeSteps(Arrays.asList( - StorageStep.CHOOSE_DB_MODE, - StorageStep.CONFIG_REFERENTIEL, - StorageStep.CONFIG_DATA, - StorageStep.SELECT_DATA, - StorageStep.ROLES, - StorageStep.BACKUP, - StorageStep.CONFIRM) - ); - model.setSteps(StorageStep.CONFIG); - model.updateUniverse(); - - model.setDbMode(dbMode); - } - - @Override - protected StorageUI createUI(JAXXContext context, - Window mainUI, - Class<StorageUI> storageUIClass, - Class<StorageUIModel> modelClass, - StorageUIModel model) throws Exception { - if (!(mainUI instanceof JAXXObject)) { - mainUI = null; - } - return super.createUI(context, - mainUI, - storageUIClass, - modelClass, - model - ); - } - - @Override - protected void doAction(StorageUI ui) { - super.doAction(ui); - if (log.isDebugEnabled()) { - log.debug("Apply new remote connexion to " + model); - } - ui.getModel().copyTo(model); - model.validate(); - } - }; - - launcher.start(); - } - - /** - * Méthode pour lancer l'action de connexion à une base locale. - * - * @param context le context applicatif - * @param mainUI la fenetre principale parent (peut etre null) - * @param model le modèle de source de données à utiliser - * @see StorageUI - */ - public static void obtainLocalConnexion(final JAXXContext context, - Window mainUI, - final StorageUIModel model) { - - if (mainUI == null) { - mainUI = ObserveSwingApplicationContext.get().getMainUI(); - } - - addStorageUIHandler(context); - - StorageUILauncher launcher = new StorageUILauncher( - context, - mainUI, - model, - t("observe.title.connect.localDB")) { - - @Override - protected StorageUI createUI(JAXXContext context, - Window mainUI, - Class<StorageUI> storageUIClass, - Class<StorageUIModel> modelClass, - StorageUIModel model) throws Exception { - if (!(mainUI instanceof JAXXObject)) { - // sinon on a pas de context propagé... - mainUI = null; - } - return super.createUI(context, mainUI, storageUIClass, modelClass, model); - } - - @Override - protected void init(StorageUI ui) { - StorageUIModel model = ui.getModel(); - - int nbModes = 0; - - DbMode mode = null; - if (model.isCanCreateLocalService()) { - nbModes++; - mode = DbMode.CREATE_LOCAL; - } - if (model.isCanUseLocalService()) { - nbModes++; - mode = DbMode.USE_LOCAL; - } - if (model.isCanUseRemoteService()) { - nbModes++; - mode = DbMode.USE_REMOTE; - } - if (model.isCanUseServerService()) { - nbModes++; - mode = DbMode.USE_SERVER; - } - - if (nbModes == 1) { - - if (log.isDebugEnabled()) { - log.debug("Only one mode available [" + mode + - "], set it in model"); - } - - // un seul mode possible, on le sélectionne - model.setDbMode(mode); - } - - // on supprime des étapes - model.setExcludeSteps(Arrays.asList( - StorageStep.BACKUP, - StorageStep.CONFIG_REFERENTIEL, - StorageStep.CONFIG_DATA, - StorageStep.SELECT_DATA, - StorageStep.CONFIRM)); - - model.updateUniverse(); - } - - @Override - protected void doAction(StorageUI ui) { - super.doAction(ui); - if (log.isDebugEnabled()) { - log.debug("Apply new local connexion to " + model); - } - ui.getModel().copyTo(model); - model.validate(); - } - }; - - launcher.start(); - } - - /** - * Méthode pour lancer l'action de connexion à une base locale ou distante. - * - * @param context le context applicatif - * @param mainUI la fenetre principale parent (peut etre null) - * @param model le modèle de source de données à utiliser - * @see StorageUI - */ - public static void obtainConnexion(final JAXXContext context, - Window mainUI, - final StorageUIModel model) { - - if (mainUI == null) { - mainUI = ObserveSwingApplicationContext.get().getMainUI(); - } - addStorageUIHandler(context); - StorageUILauncher launcher = new StorageUILauncher( - context, - mainUI, - model, - t("observe.title.connect.existingDB")) { - - @Override - protected void init(StorageUI ui) { - StorageUIModel model = ui.getModel(); - DbMode dbMode = model.getDbMode(); - - // exclusion des étapes non requises - model.setExcludeSteps(Arrays.asList( - StorageStep.SELECT_DATA, - StorageStep.CONFIG_REFERENTIEL, - StorageStep.CONFIG_DATA, - StorageStep.ROLES, - StorageStep.BACKUP, - StorageStep.CONFIRM) - ); - model.setSteps(StorageStep.CONFIG); - model.updateUniverse(); - - // par defaut, on se positionne sur la base distante ? - model.setDbMode(dbMode); - } - - @Override - public void start() { - super.start(); - } - - @Override - protected StorageUI createUI(JAXXContext context, - Window mainUI, - Class<StorageUI> storageUIClass, - Class<StorageUIModel> modelClass, - StorageUIModel model) throws Exception { - if (!(mainUI instanceof JAXXObject)) { - mainUI = null; - } - return super.createUI(context, - mainUI, - storageUIClass, - modelClass, - model - ); - } - - @Override - protected void doAction(StorageUI ui) { - super.doAction(ui); - if (log.isDebugEnabled()) { - log.debug("Apply new remote connexion to " + model); - } - ui.getModel().copyTo(model); - model.validate(); - } - }; - - launcher.start(); - } - - protected static void addStorageUIHandler(JAXXContext context) { - StorageUIHandler handler = - context.getContextValue(StorageUIHandler.class); - if (handler == null) { - - handler = new StorageUIHandler(); - context.setContextValue(handler); - - if (log.isWarnEnabled()) { - log.warn("Register in context an storage handler : " + handler); - } - } else { - if (log.isWarnEnabled()) { - log.warn("Use existing handler " + handler); - } - } - } - - public String getTitle() { - return title; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/StorageUIModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/StorageUIModel.java deleted file mode 100644 index 1ac2533..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/StorageUIModel.java +++ /dev/null @@ -1,2058 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.storage; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.ObserveSwingTechnicalException; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.db.constants.ConnexionStatus; -import fr.ird.observe.db.constants.CreationMode; -import fr.ird.observe.db.constants.DbMode; -import fr.ird.observe.services.ObserveDataSourceConfigurationMainFactory; -import fr.ird.observe.services.configuration.ObserveDataSourceConfiguration; -import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationRest; -import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaH2; -import fr.ird.observe.services.configuration.ObserveDataSourceConfigurationTopiaPG; -import fr.ird.observe.services.configuration.ObserveDataSourceInformation; -import fr.ird.observe.services.dto.DataSourceCreateConfigurationDto; -import fr.ird.observe.services.dto.DataSourceCreateWithNoReferentialImportException; -import fr.ird.observe.services.dto.IncompatibleDataSourceCreateConfigurationException; -import fr.ird.observe.services.dto.ObserveDbUserDto; -import fr.ird.observe.services.security.BadObserveWebUserPasswordException; -import fr.ird.observe.services.security.ObserveWebSecurityExceptionSupport; -import fr.ird.observe.services.security.UnknownObserveWebUserException; -import fr.ird.observe.services.security.UnknownObserveWebUserForDatabaseException; -import fr.ird.observe.services.security.UserLoginNotFoundException; -import fr.ird.observe.services.security.UserPasswordNotFoundException; -import fr.ird.observe.services.service.AddSqlScriptProducerRequest; -import fr.ird.observe.services.service.BabModelVersionException; -import fr.ird.observe.services.service.DatabaseConnexionNotAuthorizedException; -import fr.ird.observe.services.service.DatabaseNotFoundException; -import fr.ird.observe.services.service.PingService; -import fr.ird.observe.services.service.SqlScriptProducerService; -import fr.ird.observe.ui.storage.tabs.DataSelectionModel; -import fr.ird.observe.ui.storage.tabs.SecurityModel; -import jaxx.runtime.JAXXContext; -import jaxx.runtime.swing.wizard.WizardModel; -import jaxx.runtime.swing.wizard.WizardUILancher; -import org.apache.commons.io.IOUtils; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.version.Version; - -import java.beans.PropertyChangeListener; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.net.MalformedURLException; -import java.net.URL; -import java.nio.file.Files; -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.Set; - -import static fr.ird.observe.ui.admin.AdminUIModel.LOG_PROPERTY_CHANGE_LISTENER; -import static org.nuiton.i18n.I18n.t; - -/** - * Le modele de l'ui pour changer de source de données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class StorageUIModel extends WizardModel<StorageStep> { - - /** Logger */ - private static final Log log = LogFactory.getLog(StorageUIModel.class); - - public static final String DB_MODE_PROPERTY_NAME = "dbMode"; - - public static final String CREATION_MODE_PROPERTY_NAME = "creationMode"; - - public static final String DO_BACKUP_PROPERTY_NAME = "doBackup"; - - public static final String BACKUP_FILE_PROPERTY_NAME = "backupFile"; - - public static final String DUMP_FILE_PROPERTY_NAME = "dumpFile"; - - public static final String LOCAL_STORAGE_EXIST_PROPERTY_NAME = "localStorageExist"; - - public static final String USE_SSL_PROPERTY_NAME = "useSsl"; - - public static final String REMOTE_URL_ROPERTY_NAME = "remoteUrl"; - - public static final String SERVER_DATABASE_PROPERTY_NAME = "serverDatabase"; - - public static final String REMOTE_LOGIN_ROPERTY_NAME = "remoteLogin"; - - public static final String REMOTE_PASSWORD_PROPERTY_NAME = "remotePassword"; - - public static final String STORE_REMOTE_CONFIG_PROPERTY_NAME = "storeRemoteConfig"; - - public static final String CONNEXION_STATUS_PROPERTY_NAME = "connexionStatus"; - - public static final String PREVIOUS_SERVICE_PROPERTY_NAME = "previousSource"; - - public static final String CAN_MIGRATE_PROPERTY_NAME = "canMigrate"; - - public static final String SHOW_MIGRATION_SQL_PROPERTY_NAME = "showMigrationSql"; - - public static final String SHOW_MIGRATION_PROGRESSION_PROPERTY_NAME = "showMigrationProgression"; - - private static final String CAN_USE_LOCALE_SERVICE_PROPERTY_NAME = "canUseLocalService"; - - private static final String CAN_CREATE_LOCALE_SERVICE_PROPERTY_NAME = "canCreateLocalService"; - - private static final String CAN_USE_REMOTE_SERVICE_PROPERTY_NAME = "canUseRemoteService"; - - private static final String CAN_USE_SERVER_SERVICE_PROPERTY_NAME = "canUseServerService"; - - public static final String REFERENTIEL_IMPORT_MODE_PROPERTY_NAME = "referentielImportMode"; - - public static final String DATA_IMPORT_MODE_PROPERTY_NAME = "dataImportMode"; - - public static final String EDIT_REMOTE_CONFIG_PROPERTY_NAME = "editRemoteConfig"; - - public static final String EDIT_SERVER_CONFIG_PROPERTY_NAME = "editServerConfig"; - - public static final String VALID_PROPERTY_NAME = "valid"; - - public static final String ALREADY_APPLIED_PROPERTY_NAME = "alreadyApplied"; - - private static final char[] EMPTY_PASSWORD = new char[0]; - - private static final String LOGIN_REFERENTIEL = "referentiel"; - - /** Le dbMode de connexion requis. */ - protected DbMode dbMode; - - protected boolean editServerConfig; - - protected boolean editRemoteConfig; - - /** Un drapeau pour savoir si une base locale existe. */ - protected boolean localStorageExist; - - /** - * Un drapeau pour savoir si l'utilisateur a demandé une sauvegarde de la - * base locale. - * - * Cette option n'est active uniquement si le drapeau localStorageExist est - * à true. - */ - protected boolean doBackup; - - /** - * Un drapeau pour savoir si on a déjà lancé l'action Appliquer (pour éviter le code ré-entrant). - * - * @since 4.0.4 - */ - protected boolean alreadyApplied; - - /** - * le fichier ou effectuer la sauvegarde de la base locale si le drapeau - * doBackup est active. - */ - protected File backupFile = new File(""); - - /** un drapeau pour savoir s'il faut sauver la configuration à distante */ - protected boolean storeRemoteConfig; - - /** le storage precedemment utilise */ - protected ObserveDataSourceConfiguration previousDataSourceConfiguration; - - protected ConnexionStatus connexionStatus; - protected String connexionStatusError; - - /** un drapeau pour definir si on peut utiliser la base locale */ - protected boolean canUseLocalService = true; - - /** un drapeau pour definir si on peut créer une base locale */ - protected boolean canCreateLocalService = true; - - /** un drapeau pour savoir si on a le droit d'utiliser une connexion distante */ - protected boolean canUseRemoteService = true; - - /** un drapeau pour savoir si on a le droit d'utiliser un serveur distant */ - protected boolean canUseServerService = true; - - /** le modèle de sélection de données (utilisé pour les exports) */ - protected DataSelectionModel selectDataModel; - - /** le modèle de sécurité (utilisé pour la mise à jour sécurité sur base distante) */ - protected SecurityModel securityModel; - - /** la configuration d'une base locale */ - protected ObserveDataSourceConfigurationTopiaH2 h2Config; - - /** la configuration d'une base distante */ - protected ObserveDataSourceConfigurationTopiaPG pgConfig; - - /** la configuration d'un serveur web */ - protected ObserveDataSourceConfigurationRest restConfig; - - protected String serverUrl; - - /** Les information de connextion a la base **/ - protected ObserveDataSourceInformation dataSourceInformation; - - /** Les information de connextion a la base **/ - protected ObserveDataSourceInformation h2DataSourceInformation; - - /** le fichier d'import des donné */ - protected File dumpFile; - - /** le mode de creation d'une base */ - protected CreationMode creationMode; - - /** la configuration pour impoter les données */ - protected ObserveDataSourceConfiguration importDataConfig; - - /** l'action d'administration de base obstuna */ - protected ObstunaAdminAction adminAction; - - /** la configuration de la base de referentiel à importer */ - protected StorageUIModel centralSourceModel; - - /** la configuration de la base de données à importer */ - protected StorageUIModel dataSourceModel; - - /** - * Le mode d'import de référentiel (uniquement pour la création de base distante). - * - * @since 3.0 - */ - protected CreationMode referentielImportMode; - - /** - * Le mode d'import des données (uniquement pour la création de base distante). - * - * @since 3.6 - */ - protected CreationMode dataImportMode; - - public StorageUIModel() { - super(StorageStep.class, - StorageStep.CHOOSE_DB_MODE, - StorageStep.BACKUP, - StorageStep.CONFIRM - ); - selectDataModel = new DataSelectionModel(); - securityModel = new SecurityModel(); - - connexionStatus = ConnexionStatus.UNTESTED; - - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ObserveDataSourceConfigurationMainFactory configurationMainFactory = applicationContext.getObserveDataSourceConfigurationMainFactory(); - - Version modelVersion = applicationContext.getConfig().getModelVersion(); - - h2Config = configurationMainFactory.createObserveDataSourceConfigurationTopiaH2( - t("observe.storage.label.local"), - null, - ObserveSwingApplicationConfig.DB_NAME, - "", - EMPTY_PASSWORD, - false, - false, - modelVersion - ); - - pgConfig = configurationMainFactory.createObserveDataSourceConfigurationTopiaPG( - t("observe.storage.label.remote"), - "", - "", - EMPTY_PASSWORD, - false, - false, - false, - modelVersion - ); - - restConfig = configurationMainFactory.createObserveDataSourceConfigurationRest( - t("observe.storage.label.server"), - null, - "", - EMPTY_PASSWORD, - null, - modelVersion - ); - - PropertyChangeListener clearStatus = evt -> { - setConnexionStatus(ConnexionStatus.UNTESTED); - dataSourceInformation = null; - }; - - addPropertyChangeListener(REMOTE_URL_ROPERTY_NAME, clearStatus); - addPropertyChangeListener(REMOTE_LOGIN_ROPERTY_NAME, clearStatus); - addPropertyChangeListener(REMOTE_PASSWORD_PROPERTY_NAME, clearStatus); - addPropertyChangeListener(SERVER_DATABASE_PROPERTY_NAME, clearStatus); - addPropertyChangeListener(USE_SSL_PROPERTY_NAME, clearStatus); - } - - @Override - public void setStep(StorageStep step) { - setAlreadyApplied(false); - super.setStep(step); - } - - /** - * La méthode pour initialiser le modèle à partir du context applicatif et - * d'un service existant. - * - * @param context le context applicatif - * @param source le service existant - */ - public void init(JAXXContext context, ObserveDataSourceConfiguration source) { - - ObserveSwingApplicationConfig config = ObserveSwingApplicationContext.get().getConfig(); - - StorageUIModel incomingModel = WizardUILancher.newModelEntry(StorageUIModel.class).getContextValue(context); - - if (incomingModel != null) { - - if (log.isDebugEnabled()) { - log.debug("from a incoming model " + incomingModel.getLabel() + " : " + incomingModel); - } - - // on initialie a partir d'un autre modèle - incomingModel.copyTo(this); - - return; - } - - StorageUIHandler storageUIHandler = context.getContextValue(StorageUIHandler.class); - - // ajout paramétrage depuis la configuration - - boolean isLocalStorageExist = config.isLocalStorageExist(); - setLocalStorageExist(isLocalStorageExist); - if (!isLocalStorageExist) { - - // on force a ne pas pouvoir utilisaer la base locale - setCanUseLocalService(false); - } - - if (log.isDebugEnabled()) { - log.debug("Local storage exists ? " + isLocalStorageExist()); - log.debug("can use local storage ? " + isCanUseLocalService()); - log.debug("can create local storage ? " + isCanCreateLocalService()); - log.debug("can use remote storage ? " + isCanUseRemoteService()); - log.debug("can use server storage ? " + isCanUseServerService()); - log.debug("previous service ? " + source); - } - - setStoreRemoteConfig(config.isStoreRemoteStorage()); - setBackupFile(new File(config.getBackupDirectory(), storageUIHandler.getDefaultBackupFilename())); - setDumpFile(config.getBackupDirectory()); - setShowMigrationProgression(config.isShowMigrationProgression()); - setShowMigrationSql(config.isShowMigrationSql()); - setDoBackup(false); - setPreviousDataSourceConfiguration(source); - - if (log.isDebugEnabled()) { - log.debug("canMigrate ? " + isCanMigrate()); - } - - CreationMode mode = config.getDefaultCreationMode(); - - // on initialise les configuration avec les valeurs par défaut - h2Config = config.getDataSourceConfigurationH2(t("observe.storage.label.local")); - pgConfig = config.getDataSourceConfigurationPG(t("observe.storage.label.remote")); - restConfig = config.getDataSourceConfigurationRest(t("observe.storage.label.server")); - - if (source != null) { - - // on initialise le modèle à partir d'un service existant - - if (log.isDebugEnabled()) { - log.debug("from a previous service " + source); - } - - if (source instanceof ObserveDataSourceConfigurationTopiaH2) { - - // on est actuellement connecte sur une base locale - fromStorageConfig((ObserveDataSourceConfigurationTopiaH2) source); - - } else if (source instanceof ObserveDataSourceConfigurationTopiaPG) { - - if (!isLocalStorageExist) { - // aucune base locale, on positionne le mode de création - // de base locale par défaut. - - setCreationMode(mode); - } - - // on est sur une base distante - fromStorageConfig((ObserveDataSourceConfigurationTopiaPG) source); - - } else if (source instanceof ObserveDataSourceConfigurationRest) { - - // on est sur une base distante - fromStorageConfig((ObserveDataSourceConfigurationRest) source); - } - - return; - } - - if (log.isDebugEnabled()) { - log.debug("no service found, using default configuration"); - } - - DbMode newDbMode = config.getDefaultDbMode(); - if (getAdminAction() != null) { - - // une action d'admin obstuna toujours sur base distante - newDbMode = DbMode.USE_REMOTE; - } else { - if (isCanUseLocalService()) { - mode = null; - } else if (isCanCreateLocalService()) { - mode = CreationMode.IMPORT_EXTERNAL_DUMP; - } else if (isCanUseRemoteService()) { - mode = CreationMode.IMPORT_REMOTE_STORAGE; - } else if (isCanUseServerService()) { - mode = CreationMode.IMPORT_SERVER_STORAGE; - } - } - if (log.isDebugEnabled()) { - log.debug("Will use creationMode : " + mode); - } - setDbMode(newDbMode); - setCreationMode(mode); - } - - /** - * La méthode pour initialiser le modèle à partir du context applicatif et - * d'une configuration de source de donnée existante. - * - * @param context le context applicatif - * @param previousConfig la configuration de service existant - * @since 2.0 - */ - public void initFromPreviousConfig(JAXXContext context, - ObserveDataSourceConfiguration previousConfig, - ObserveDataSourceInformation previousInfo) { - - Objects.requireNonNull(previousConfig, "previousConfig parameter can not be null in method initFromPreviousConfig"); - - ObserveSwingApplicationConfig config = ObserveSwingApplicationContext.get().getConfig(); - - StorageUIHandler storageUIHandler = context.getContextValue(StorageUIHandler.class); - - // ajout paramétrage depuis la configuration - - boolean isLocalStorageExist = config.isLocalStorageExist(); - setLocalStorageExist(isLocalStorageExist); - - if (log.isDebugEnabled()) { - log.debug("Local storage exists ? " + isLocalStorageExist()); - log.debug("can use local storage ? " + isCanUseLocalService()); - log.debug("can create local storage ? " + isCanCreateLocalService()); - log.debug("can use remote storage ? " + isCanUseRemoteService()); - log.debug("can use server storage ? " + isCanUseServerService()); - log.debug("previous service ? " + previousConfig); - } - - setStoreRemoteConfig(config.isStoreRemoteStorage()); - setBackupFile(new File(config.getBackupDirectory(), storageUIHandler.getDefaultBackupFilename())); - setDumpFile(config.getBackupDirectory()); - setShowMigrationProgression(config.isShowMigrationProgression()); - setShowMigrationSql(config.isShowMigrationSql()); - setDoBackup(false); - - if (log.isDebugEnabled()) { - log.debug("canMigrate ? " + isCanMigrate()); - } - - // on initialise les configuration avec les valeurs par défaut - h2Config = config.getDataSourceConfigurationH2(t("observe.storage.label.local")); - pgConfig = config.getDataSourceConfigurationPG(t("observe.storage.label.remote")); - restConfig = config.getDataSourceConfigurationRest(t("observe.storage.label.server")); - - if (previousConfig instanceof ObserveDataSourceConfigurationTopiaH2) { - - // on est actuellement connecte sur une base locale - fromStorageConfig((ObserveDataSourceConfigurationTopiaH2) previousConfig); - h2DataSourceInformation = previousInfo; - } else if (previousConfig instanceof ObserveDataSourceConfigurationTopiaPG) { - - if (!isLocalStorageExist) { - - // aucune base locale, on ne peut pas utiliser la base locale - setCanUseLocalService(false); - } - - // on est sur une base distante - fromStorageConfig((ObserveDataSourceConfigurationTopiaPG) previousConfig); - - } else if (previousConfig instanceof ObserveDataSourceConfigurationRest) { - - // on est sur une base distante - fromStorageConfig((ObserveDataSourceConfigurationRest) previousConfig); - } - setDataSourceInformation(previousInfo); - } - - /** - * La méthode pour initialiser le modèle à partir du context applicatif et - * d'un service existant. - */ - public void initFromModel() { - - ObserveSwingApplicationConfig config = ObserveSwingApplicationContext.get().getConfig(); - - - // ajout paramétrage depuis la configuration - boolean isLocalStorageExist = config.isLocalStorageExist(); - setLocalStorageExist(isLocalStorageExist); - if (!isLocalStorageExist) { - - // on force a ne pas pouvoir utilisaer la base locale - setCanUseLocalService(false); - } - - if (log.isDebugEnabled()) { - log.debug("Local storage exists ? " + isLocalStorageExist()); - log.debug("can use local storage ? " + isCanUseLocalService()); - log.debug("can create local storage ? " + isCanCreateLocalService()); - log.debug("can use remote storage ? " + isCanUseRemoteService()); - log.debug("can use server storage ? " + isCanUseServerService()); - } - - setStoreRemoteConfig(config.isStoreRemoteStorage()); - setDumpFile(config.getBackupDirectory()); - setShowMigrationProgression(config.isShowMigrationProgression()); - setShowMigrationSql(config.isShowMigrationSql()); - setDoBackup(false); - setPreviousDataSourceConfiguration(null); - - if (log.isDebugEnabled()) { - log.debug("canMigrate ? " + isCanMigrate()); - } - - CreationMode mode = config.getDefaultCreationMode(); - - if (log.isDebugEnabled()) { - log.debug("no service found, using default configuration"); - } - - // aucun service de persistance ouvert, - // on utilise la configuration par defaut - // ce cas ne devrait arriver uniquement tant qu'aucune - // base locale est crée - h2Config = config.getDataSourceConfigurationH2(t("observe.storage.label.local")); - pgConfig = config.getDataSourceConfigurationPG(t("observe.storage.label.remote")); - restConfig = config.getDataSourceConfigurationRest(t("observe.storage.label.server")); - - DbMode newDbMode = config.getDefaultDbMode(); - if (getAdminAction() != null) { - - // une action d'admin obstuna toujours sur base distante - newDbMode = DbMode.USE_REMOTE; - } else { - if (isCanUseLocalService()) { - mode = null; - } else if (isCanCreateLocalService()) { - mode = CreationMode.IMPORT_EXTERNAL_DUMP; - } else if (isCanUseRemoteService()) { - mode = CreationMode.IMPORT_REMOTE_STORAGE; - } else if (isCanUseServerService()) { - mode = CreationMode.IMPORT_SERVER_STORAGE; - } - } - if (log.isDebugEnabled()) { - log.debug("Will use creationMode : " + mode); - } - setDbMode(newDbMode); - setCreationMode(mode); - } - - protected void startCentralSourceModel() { - - if (!isNeedReferentielDataSource()) { - - // pas besoin de la base distante - return; - } - - // par default, on tente d'utiliser la base distance - getCentralSourceModel().initFromModel(); - centralSourceModel.setCanCreateLocalService(false); - centralSourceModel.setCanUseLocalService(false); - centralSourceModel.setCanUseRemoteService(true); - centralSourceModel.setCanUseServerService(true); - centralSourceModel.start(DbMode.USE_REMOTE); - - if (log.isDebugEnabled()) { - centralSourceModel.removePropertyChangeListener(LOG_PROPERTY_CHANGE_LISTENER); - centralSourceModel.addPropertyChangeListener(LOG_PROPERTY_CHANGE_LISTENER); - } - - // on teste si la connexion distante existe - if (centralSourceModel.isValid()) { - centralSourceModel.testRemote(); - } - } - - protected void startCentralDataSourceModel() { - - if (!isNeedDataDataSource()) { - - // pas besoin de la base distante - return; - } - - // par default, on tente d'utiliser la base distance - getDataSourceModel().initFromModel(); - dataSourceModel.setCanCreateLocalService(false); - dataSourceModel.setCanUseLocalService(false); - dataSourceModel.setCanUseRemoteService(true); - dataSourceModel.setCanUseServerService(true); - dataSourceModel.start(DbMode.USE_REMOTE); - - if (log.isDebugEnabled()) { - dataSourceModel.removePropertyChangeListener(LOG_PROPERTY_CHANGE_LISTENER); - dataSourceModel.addPropertyChangeListener(LOG_PROPERTY_CHANGE_LISTENER); - } - - // on teste si la connexion distante existe - if (dataSourceModel.isValid()) { - dataSourceModel.testRemote(); - } - } - - public boolean isNeedReferentielDataSource() { - return adminAction != null && - adminAction == ObstunaAdminAction.CREATE; - } - - public boolean isNeedDataDataSource() { - return adminAction != null && - adminAction == ObstunaAdminAction.CREATE; - } - - public void start(DbMode dbMode) { - - if (log.isDebugEnabled()) { - log.debug("Will use dbMode : " + dbMode + " vs previous mode " + getDbMode()); - } - setDbMode(dbMode); - - startCentralSourceModel(); - startCentralDataSourceModel(); - - start(); - firePropertyChange(DB_MODE_PROPERTY_NAME, getDbMode()); - firePropertyChange(CREATION_MODE_PROPERTY_NAME, getCreationMode()); - firePropertyChange(DUMP_FILE_PROPERTY_NAME, getDumpFile()); - firePropertyChange(BACKUP_FILE_PROPERTY_NAME, getBackupFile()); - firePropertyChange(DO_BACKUP_PROPERTY_NAME, isDoBackup()); - firePropertyChange(CAN_USE_LOCALE_SERVICE_PROPERTY_NAME, isCanUseLocalService()); - firePropertyChange(CAN_CREATE_LOCALE_SERVICE_PROPERTY_NAME, isCanCreateLocalService()); - firePropertyChange(CAN_USE_REMOTE_SERVICE_PROPERTY_NAME, isCanUseRemoteService()); - firePropertyChange(CAN_USE_SERVER_SERVICE_PROPERTY_NAME, isCanUseServerService()); - firePropertyChange(CONNEXION_STATUS_PROPERTY_NAME, getConnexionStatus()); - firePropertyChange(PREVIOUS_SERVICE_PROPERTY_NAME, getPreviousDataSourceConfiguration()); - firePropertyChange(LOCAL_STORAGE_EXIST_PROPERTY_NAME, isLocalStorageExist()); - firePropertyChange(STORE_REMOTE_CONFIG_PROPERTY_NAME, isStoreRemoteConfig()); - firePropertyChange(REMOTE_URL_ROPERTY_NAME, getRemoteUrl()); - firePropertyChange(REMOTE_LOGIN_ROPERTY_NAME, getRemoteLogin()); - firePropertyChange(REMOTE_PASSWORD_PROPERTY_NAME, getRemotePassword()); - firePropertyChange(SERVER_DATABASE_PROPERTY_NAME, getServerDatabase()); - - firePropertyChange(EDIT_REMOTE_CONFIG_PROPERTY_NAME, isEditRemoteConfig()); - firePropertyChange(EDIT_SERVER_CONFIG_PROPERTY_NAME, isEditServerConfig()); - - firePropertyChange(USE_SSL_PROPERTY_NAME, null, isUseSsl()); - firePropertyChange(CAN_MIGRATE_PROPERTY_NAME, isCanMigrate()); - firePropertyChange(SHOW_MIGRATION_SQL_PROPERTY_NAME, isShowMigrationSql()); - firePropertyChange(SHOW_MIGRATION_PROGRESSION_PROPERTY_NAME, isShowMigrationProgression()); - } - - public boolean isCanUseLocalService() { - return canUseLocalService; - } - - public boolean isCanCreateLocalService() { - return canCreateLocalService; - } - - public boolean isCanUseRemoteService() { - return canUseRemoteService; - } - - public boolean isCanUseServerService() { - return canUseServerService; - } - - public SecurityModel getSecurityModel() { - return securityModel; - } - - public ObstunaAdminAction getAdminAction() { - return adminAction; - } - - public String getAdminActionLabel() { - return t(getAdminAction().getLabel()); - } - - public DataSelectionModel getSelectDataModel() { - return selectDataModel; - } - - public void setSelectDataModel(DataSelectionModel selectDataModel) { - this.selectDataModel = selectDataModel; - } - - public CreationMode getReferentielImportMode() { - return referentielImportMode; - } - - public CreationMode getDataImportMode() { - return dataImportMode; - } - - public boolean isImportReferentiel() { - return referentielImportMode != null && CreationMode.EMPTY != referentielImportMode; - } - - public boolean isImportData() { - return dataImportMode != null && CreationMode.EMPTY != dataImportMode; - } - - public StorageUIModel getCentralSourceModel() { - if (centralSourceModel == null) { - centralSourceModel = new StorageUIModel() { - - @Override - public String getLabel() { - String txt = t("observe.storage.label.import.referentiel"); - if (getDbMode() == DbMode.CREATE_LOCAL) { - txt = t("observe.storage.label.import.referentiel", getH2Config().getDirectory().getAbsolutePath()); - } else if (isRemote()) { - txt = t("observe.storage.label.import.referentiel.remote", getRemoteUrl()); - } else if (isServer()) { - txt = t("observe.storage.label.import.referentiel.server", getServerUrl()); - } - return txt; - } - - @Override - public void validate() { - super.validate(); - - // on declanche la revalidation du modèle - StorageUIModel.this.firePropertyChange(VALID_PROPERTY_NAME, isValid()); - } - }; - } - return centralSourceModel; - } - - public StorageUIModel getDataSourceModel() { - if (dataSourceModel == null) { - dataSourceModel = new StorageUIModel() { - - @Override - public String getLabel() { - String txt = t("observe.storage.label.import.data"); - if (getDbMode() == DbMode.CREATE_LOCAL) { - txt = t("observe.storage.label.import.data", getH2Config().getDirectory().getAbsolutePath()); - } else if (isRemote()) { - txt = t("observe.storage.label.import.data.remote", getRemoteUrl()); - } else if (isServer()) { - txt = t("observe.storage.label.import.data.server", getServerUrl()); - } - return txt; - } - - @Override - public void validate() { - super.validate(); - - // on declanche la revalidation du modèle - StorageUIModel.this.firePropertyChange(VALID_PROPERTY_NAME, isValid()); - } - }; - } - return dataSourceModel; - } - - public void setAdminAction(ObstunaAdminAction adminAction) { - this.adminAction = adminAction; - } - - protected void firePropertyChange(String propertyName, Object newValue) { - firePropertyChange(propertyName, null, newValue); - } - - @Override - public void updateUniverse() { - if (dbMode == null) { - - // pas de mode choisi donc l'univers ne change pas - return; - } - List<StorageStep> universe = new ArrayList<>(); - if (adminAction == null) { - - // when doing an admin mode we do not choose db mode, we always work on remote - universe.add(StorageStep.CHOOSE_DB_MODE); - } - - boolean canBackup = localStorageExist; - switch (dbMode) { - case CREATE_LOCAL: - CreationMode creationMode = getCreationMode(); - - if (creationMode != null) { - switch (creationMode) { - case IMPORT_EXTERNAL_DUMP: - universe.add(StorageStep.CONFIG); - break; - //case IMPORT_LOCAL_STORAGE: - case IMPORT_REMOTE_STORAGE: - importDataConfig = pgConfig; - universe.add(StorageStep.CONFIG); - break; - case IMPORT_SERVER_STORAGE: - importDataConfig = restConfig; - universe.add(StorageStep.CONFIG); - break; - } - } - break; - case USE_LOCAL: - // pas de backup si on veut utiliser la base locale - canBackup = false; - break; - case USE_REMOTE: - canBackup = false; - universe.add(StorageStep.CONFIG); - break; - case USE_SERVER: - canBackup = false; - universe.add(StorageStep.CONFIG); - break; - } - if (canBackup) { - universe.add(StorageStep.BACKUP); - - // when backup is possible always - setDoBackup(true); - } - if (adminAction != null) { - if (adminAction == ObstunaAdminAction.CREATE) { - universe.add(StorageStep.CONFIG_REFERENTIEL); - - if (getReferentielImportMode() != null && getReferentielImportMode() != CreationMode.EMPTY) { - - // can import data only if import a referentiel - universe.add(StorageStep.CONFIG_DATA); - } - - if (getDataImportMode() != null && getDataImportMode() != CreationMode.EMPTY) { - universe.add(StorageStep.SELECT_DATA); - } - } - universe.add(StorageStep.ROLES); - } - universe.add(StorageStep.CONFIRM); - if (excludeSteps != null) { - universe.removeAll(excludeSteps); - } - if (log.isDebugEnabled()) { - log.debug("steps to use : " + universe); - } - setSteps(universe.toArray(new StorageStep[universe.size()])); - } - - @Override - public boolean validate(StorageStep s) { - boolean validate = super.validate(s); - if (validate) { - switch (s) { - case CHOOSE_DB_MODE: - validate = dbMode != null; - if (validate) { - if (!isCanUseRemoteService() && dbMode.equals(DbMode.USE_REMOTE)) { - validate = false; - } else if (!isCanUseLocalService() && dbMode.equals(DbMode.USE_LOCAL)) { - validate = false; - } else if (!isCanCreateLocalService() && dbMode.equals(DbMode.CREATE_LOCAL)) { - validate = false; - } else if (!isCanUseServerService() && dbMode.equals(DbMode.USE_SERVER)) { - validate = false; - } - } - if (validate && isLocal()) { - if (dbMode == DbMode.CREATE_LOCAL) { - validate = getCreationMode() != null; - } - } - break; - case CONFIG: - if (DbMode.USE_REMOTE.equals(dbMode) - || DbMode.USE_SERVER.equals(dbMode) - || DbMode.CREATE_LOCAL.equals(dbMode) - && (CreationMode.IMPORT_SERVER_STORAGE.equals(creationMode) - || CreationMode.IMPORT_REMOTE_STORAGE.equals(creationMode))) { - validate = ConnexionStatus.SUCCESS.equals(getConnexionStatus()); - //FIXME Il faut savoir si l'utilisateur est le - //FIXME propriétaire de la base -// if (validate) { -// if (getAdminAction() != null) { -// -// // il faut des droits rw sur la base distante -// validate = dataSourceInformation != null && -// dataSourceInformation.canReadReferential() && -// dataSourceInformation.canWriteReferential() && -// dataSourceInformation.canWriteData() && -// dataSourceInformation.canReadData(); -// } -// } - } else if (DbMode.CREATE_LOCAL.equals(dbMode) && CreationMode.IMPORT_EXTERNAL_DUMP.equals(creationMode)) { - validate = isValidDumpFile(dumpFile); - } - break; - case CONFIG_REFERENTIEL: - - switch (getReferentielImportMode()) { - - case EMPTY: - validate = true; - break; - case IMPORT_LOCAL_STORAGE: - case IMPORT_INTERNAL_DUMP: - - break; - case IMPORT_EXTERNAL_DUMP: - // external dumb must be filled - validate = isValidDumpFile(centralSourceModel.getDumpFile()); - break; - case IMPORT_REMOTE_STORAGE: - case IMPORT_SERVER_STORAGE: - // remote db connexion must be valid - validate = centralSourceModel.isValid(); - - if (validate) { - - // check remote db != remote import db - validate = !centralSourceModel.getRemoteUrl().equals( - getRemoteUrl()); - } - if (validate) { - - validate = centralSourceModel.getDataSourceInformation().canReadReferential(); - } - break; - } - - break; - - case CONFIG_DATA: - - switch (getDataImportMode()) { - - case EMPTY: - validate = true; - break; - case IMPORT_LOCAL_STORAGE: - case IMPORT_INTERNAL_DUMP: - - break; - case IMPORT_EXTERNAL_DUMP: - // external dumb must be filled - validate = isValidDumpFile(dataSourceModel.getDumpFile()); - break; - case IMPORT_REMOTE_STORAGE: - // remote db connexion must be valid - validate = dataSourceModel.isValid(); - - if (validate) { - - // check remote db != remote import db - validate = !dataSourceModel.getRemoteUrl().equals(getRemoteUrl()); - - } - - if (validate) { - - validate = dataSourceModel.getDataSourceInformation().canReadData(); - - } - - break; - } - - break; - case BACKUP: - validate = !doBackup || - backupFile != null && - !backupFile.exists() && - backupFile.getName().endsWith(".sql.gz"); - break; - case SELECT_DATA: - // chemit 20100525 : aucune contrainte dans ce cas - validate = selectDataModel != null; - break; - case ROLES: - - Set<ObserveDbUserDto> role = getSecurityModel().getUsers(); - - int assigned = getSecurityModel().getAssigned(); - - validate = role.size() == assigned; - break; - case CONFIRM: - validate = true; - break; - } - } - return validate; - } - - public void validate() { - super.validate(); - - // toujours forcer la propagation - firePropertyChange(VALID_PROPERTY_NAME, isValid()); - } - - public boolean isValid() { - boolean result = false; - if (dbMode != null) { - switch (dbMode) { - - case CREATE_LOCAL: - result = getCreationMode() != null && - validate(StorageStep.CONFIG); - break; - case USE_REMOTE: - case USE_SERVER: - result = validate(StorageStep.CONFIG); - break; - case USE_LOCAL: - //TODO A tester... - result = h2Config.getDatabaseFile().exists(); - break; - } - } - return result; - } - - public boolean isAlreadyApplied() { - return alreadyApplied; - } - - public void setAlreadyApplied(boolean alreadyApplied) { - boolean oldValue = isAlreadyApplied(); - this.alreadyApplied = alreadyApplied; - firePropertyChange(ALREADY_APPLIED_PROPERTY_NAME, oldValue, alreadyApplied); - } - - public boolean isUseSelectData() { - return getSteps() != null && - getSteps().contains(StorageStep.SELECT_DATA); - } - - public boolean isBackupAction() { - return getSteps() != null && getStepIndex(StorageStep.BACKUP) == 0; - } - - public boolean isLocal() { - return dbMode != null && (dbMode == DbMode.CREATE_LOCAL || dbMode == DbMode.USE_LOCAL); - } - - public boolean isRemote() { - return dbMode != null && dbMode == DbMode.USE_REMOTE; - } - - public boolean isServer() { - return dbMode != null && dbMode == DbMode.USE_SERVER; - } - - public boolean isCanMigrate() { - boolean result = false; - if (dbMode != null) { - switch (dbMode) { - case USE_LOCAL: - result = true; - break; - case CREATE_LOCAL: - // en cration de base local on autorise les migration uniquement pour les imports de dump - result = CreationMode.IMPORT_EXTERNAL_DUMP.equals(creationMode) || CreationMode.IMPORT_INTERNAL_DUMP.equals(creationMode); - break; - case USE_REMOTE: - case USE_SERVER: - result = ObstunaAdminAction.UPDATE.equals(adminAction); - break; - } - } - return result; - } - - public String getLabel() { - String txt; - if (dbMode == DbMode.CREATE_LOCAL) { - txt = h2Config.getLabel(); - } else { - if (isRemote()) { - txt = pgConfig.getLabel(); - } else { - txt = restConfig.getLabel(); - } - } - return txt; - } - - public boolean isLocalStorageExist() { - return localStorageExist; - } - - public boolean isStoreRemoteConfig() { - return storeRemoteConfig; - } - - public File getBackupFile() { - return backupFile; - } - - public boolean isDoBackup() { - return doBackup; - } - - public Version getModelVersion() { - return ObserveSwingApplicationContext.get().getConfig().getModelVersion(); - } - - public DbMode getDbMode() { - return dbMode; - } - - public boolean isEditRemoteConfig() { - return editRemoteConfig; - } - - public boolean isEditServerConfig() { - return editServerConfig; - } - - public ObserveDataSourceConfiguration getPreviousDataSourceConfiguration() { - return previousDataSourceConfiguration; - } - - public void setDbMode(DbMode dbMode) { - DbMode oldValue = this.dbMode; - this.dbMode = dbMode; - firePropertyChange(DB_MODE_PROPERTY_NAME, oldValue, dbMode); - updateEditConfig(); - if (oldValue != dbMode) { - - // on recalcule l'univers des étapes disponibles - updateUniverse(); - } - - // validation du modèle - validate(); - - // le drapeau canMigrate peut avoir changé, on doit notifié les écouteurs - firePropertyChange(CAN_MIGRATE_PROPERTY_NAME, null, isCanMigrate()); - } - - protected void updateEditConfig() { - - boolean oldValueRemote = isEditRemoteConfig(); - boolean oldValueServer = isEditServerConfig(); - - editRemoteConfig = DbMode.USE_REMOTE.equals(dbMode) || - DbMode.CREATE_LOCAL.equals(dbMode) && CreationMode.IMPORT_REMOTE_STORAGE.equals(creationMode); - firePropertyChange(EDIT_REMOTE_CONFIG_PROPERTY_NAME, oldValueRemote, editRemoteConfig); - - editServerConfig = DbMode.USE_SERVER.equals(dbMode) || - DbMode.CREATE_LOCAL.equals(dbMode) && CreationMode.IMPORT_SERVER_STORAGE.equals(creationMode); - firePropertyChange(EDIT_SERVER_CONFIG_PROPERTY_NAME, oldValueServer, editServerConfig); - } - - public void updateEditConfigValues() { - - if (isEditRemoteConfig()) { - // bind from pg config model - setRemoteLogin(pgConfig.getUsername()); - setRemoteUrl(pgConfig.getJdbcUrl()); - setRemotePassword(pgConfig.getPassword()); - } - - if (isEditServerConfig()) { - // bind from rest config model - setRemoteLogin(restConfig.getLogin()); - setRemoteUrl(restConfig.getServerUrl() == null ? "" : restConfig.getServerUrl().toString()); - setRemotePassword(restConfig.getPassword()); - setServerDatabase(restConfig.getOptionalDatabaseName().orElse(null)); - } - - } - - public void setLocalStorageExist(boolean localStorageExist) { - boolean oldValue = this.localStorageExist; - this.localStorageExist = localStorageExist; - firePropertyChange(LOCAL_STORAGE_EXIST_PROPERTY_NAME, oldValue, - localStorageExist); - validate(); - } - - public void setStoreRemoteConfig(boolean storeRemoteConfig) { - boolean oldValue = this.storeRemoteConfig; - this.storeRemoteConfig = storeRemoteConfig; - firePropertyChange(STORE_REMOTE_CONFIG_PROPERTY_NAME, oldValue, - storeRemoteConfig); - } - - public void setDoBackup(boolean doBackup) { - boolean oldValue = this.doBackup; - this.doBackup = doBackup; - firePropertyChange(DO_BACKUP_PROPERTY_NAME, oldValue, doBackup); - } - - public void setBackupFile(File backupFile) { - File oldValue = this.backupFile; - this.backupFile = backupFile; - firePropertyChange(BACKUP_FILE_PROPERTY_NAME, oldValue, backupFile); - validate(); - } - - public void setReferentielImportMode(CreationMode referentielImportMode) { - CreationMode oldValue = this.referentielImportMode; - this.referentielImportMode = referentielImportMode; - firePropertyChange(REFERENTIEL_IMPORT_MODE_PROPERTY_NAME, - oldValue, - referentielImportMode); - - if (oldValue != referentielImportMode) { - updateUniverse(); - } - validate(); - } - - public void setDataImportMode(CreationMode dataImportMode) { - CreationMode oldValue = this.dataImportMode; - this.dataImportMode = dataImportMode; - firePropertyChange(DATA_IMPORT_MODE_PROPERTY_NAME, - oldValue, - dataImportMode); - if (oldValue != dataImportMode) { - - // reset selected data to import - setSelectDataModel(null); - - updateUniverse(); - } - validate(); - } - - public void setExcludeSteps(List<StorageStep> excludeSteps) { - this.excludeSteps = excludeSteps; - } - - public void destroy() { - super.destroy(); - } - - public void setShowMigrationSql(boolean showMigrationSql) { - boolean oldValue = pgConfig.isShowMigrationSql(); - pgConfig.setShowMigrationSql(showMigrationSql); - h2Config.setShowMigrationSql(showMigrationSql); - firePropertyChange(SHOW_MIGRATION_SQL_PROPERTY_NAME, oldValue, showMigrationSql); - } - - public void setShowMigrationProgression(boolean showMigrationProgression) { - boolean oldValue = pgConfig.isShowMigrationProgression(); - pgConfig.setShowMigrationProgression(showMigrationProgression); - h2Config.setShowMigrationProgression(showMigrationProgression); - firePropertyChange(SHOW_MIGRATION_PROGRESSION_PROPERTY_NAME, oldValue, showMigrationProgression); - } - - // ---------------------------------------------------------- - // -- h2Config delegate methods - // ---------------------------------------------------------- - - public CreationMode getCreationMode() { - return creationMode; - } - - public File getDumpFile() { - return dumpFile; - } - - public void setCreationMode(CreationMode creationMode) { - CreationMode oldValue = getCreationMode(); - this.creationMode = creationMode; - firePropertyChange(CREATION_MODE_PROPERTY_NAME, oldValue, creationMode); - updateEditConfig(); - if (oldValue != creationMode) { - updateUniverse(); - } - if (CreationMode.IMPORT_REMOTE_STORAGE.equals(creationMode) || CreationMode.IMPORT_SERVER_STORAGE.equals(creationMode)) { - //TC-20100308 : dans le cas d'un import du référentiel distant - //TC-20100308 : on utilise toujours l'utilisateur referentiel - String s = getRemoteLogin(); - if (s != null && !LOGIN_REFERENTIEL.equals(s)) { - setRemoteLogin(LOGIN_REFERENTIEL); - setRemotePassword(EMPTY_PASSWORD); - } - } - validate(); - } - - public void setDumpFile(File dumpFile) { - File oldValue = this.dumpFile; - this.dumpFile = dumpFile; - firePropertyChange(DUMP_FILE_PROPERTY_NAME, oldValue, dumpFile); - validate(); - } - - // ---------------------------------------------------------- - // -- pg2Config delegate methods - // ---------------------------------------------------------- - - public String getRemoteLogin() { - String login = ""; - - if (isEditRemoteConfig()) { - - login = pgConfig.getUsername(); - - } else if (isEditServerConfig()) { - - login = restConfig.getLogin(); - - } - return login; - } - - public char[] getRemotePassword() { - char[] password = EMPTY_PASSWORD; - - if (isEditRemoteConfig()) { - - password = pgConfig.getPassword(); - - } else if (isEditServerConfig()) { - - password = restConfig.getPassword(); - - } - return password; - } - - public String getRemoteUrl() { - String url = ""; - - if (isEditRemoteConfig()) { - - url = pgConfig.getJdbcUrl(); - - } else if (isEditServerConfig()) { - - url = serverUrl; - - } - return url; - } - - protected String getServerUrl() { - return serverUrl; - } - - protected void setServerUrl(String serverUrl) { - this.serverUrl = serverUrl; - } - - public boolean isUseSsl() { - return pgConfig.isUseSsl(); - } - - public String getServerDatabase() { - return restConfig.getOptionalDatabaseName().orElse(null); - } - - public ConnexionStatus getConnexionStatus() { - return connexionStatus; - } - - public void setPreviousDataSourceConfiguration(ObserveDataSourceConfiguration previousDataSourceConfiguration) { - this.previousDataSourceConfiguration = previousDataSourceConfiguration; - } - - public ObserveDataSourceConfigurationTopiaH2 getH2Config() { - return h2Config; - } - - public ObserveDataSourceConfigurationTopiaPG getPgConfig() { - return pgConfig; - } - - public ObserveDataSourceConfigurationRest getRestConfig() { - return restConfig; - } - - public void setRemoteLogin(String remoteLogin) { - -// String oldValue = getRemoteLogin(); - - if (isEditRemoteConfig()) { - - pgConfig.setUsername(remoteLogin); - - } else if (isEditServerConfig()) { - - restConfig.setLogin(remoteLogin); - - } - - firePgConfigChanged(REMOTE_LOGIN_ROPERTY_NAME, null, remoteLogin); - } - - public void setRemotePassword(char... remotePassword) { -// char[] oldValue = getRemotePassword(); - - if (isEditRemoteConfig()) { - - pgConfig.setPassword(remotePassword); - - } else if (isEditServerConfig()) { - - restConfig.setPassword(remotePassword); - - } - firePgConfigChanged(REMOTE_PASSWORD_PROPERTY_NAME, null, remotePassword); - } - - public void setCanUseLocalService(boolean canUseLocalService) { - this.canUseLocalService = canUseLocalService; - firePgConfigChanged(CAN_USE_LOCALE_SERVICE_PROPERTY_NAME, null, - canUseLocalService); - } - - public void setCanCreateLocalService(boolean canCreateLocalService) { - this.canCreateLocalService = canCreateLocalService; - firePgConfigChanged(CAN_CREATE_LOCALE_SERVICE_PROPERTY_NAME, null, - canCreateLocalService); - } - - public void setCanUseRemoteService(boolean canUseRemoteService) { - this.canUseRemoteService = canUseRemoteService; - firePropertyChange(CAN_USE_REMOTE_SERVICE_PROPERTY_NAME, null, canUseRemoteService); - } - - public void setCanUseServerService(boolean canUseServerService) { - this.canUseServerService = canUseServerService; - firePropertyChange(CAN_USE_SERVER_SERVICE_PROPERTY_NAME, null, canUseServerService); - } - - public void setRemoteUrl(String remoteUrl) { - if (isEditRemoteConfig()) { - - pgConfig.setJdbcUrl(remoteUrl); - - } else if (isEditServerConfig()) { - - serverUrl = remoteUrl; - - } - firePgConfigChanged(REMOTE_URL_ROPERTY_NAME, null, remoteUrl); - } - - public void setUseSsl(boolean useSsl) { - pgConfig.setUseSsl(useSsl); - firePgConfigChanged(USE_SSL_PROPERTY_NAME, null, useSsl); - } - - public void setServerDatabase(String database) { - if (StringUtils.isBlank(database)) { - restConfig.setOptionalDatabaseName(null); - } else { - restConfig.setOptionalDatabaseName(database); - } - firePgConfigChanged(SERVER_DATABASE_PROPERTY_NAME, null, database); - } - - // ---------------------------------------------------------- - // -- StorageConfigSupport implementation methods - // ---------------------------------------------------------- - - public void fromStorageConfig(ObserveDataSourceConfigurationTopiaH2 sourceConfig) { - - setDbMode(sourceConfig.getDatabaseFile().exists() ? DbMode.USE_LOCAL : DbMode.CREATE_LOCAL); - h2Config = sourceConfig; - } - - public void fromStorageConfig(ObserveDataSourceConfigurationTopiaPG sourceConfig) { - setDbMode(DbMode.USE_REMOTE); - pgConfig = sourceConfig; - } - - public void fromStorageConfig(ObserveDataSourceConfigurationRest sourceConfig) { - setDbMode(DbMode.USE_SERVER); - restConfig = sourceConfig; - } - - public DataSourceCreateConfigurationDto getCreationConfigurationDto() throws IOException, DatabaseConnexionNotAuthorizedException, DatabaseNotFoundException, BabModelVersionException { - - DataSourceCreateConfigurationDto result = null; - - if (getDbMode() == DbMode.CREATE_LOCAL) { - result = new DataSourceCreateConfigurationDto(); - - if (CreationMode.IMPORT_EXTERNAL_DUMP.equals(creationMode) || CreationMode.IMPORT_INTERNAL_DUMP.equals(creationMode)) { - - File dumpFile; - - if (CreationMode.IMPORT_EXTERNAL_DUMP.equals(creationMode)) { - dumpFile = getDumpFile(); - } else { - dumpFile = ObserveSwingApplicationContext.get().getConfig().getInitialDbDump(); - } - - byte[] dump = Files.readAllBytes(dumpFile.toPath()); - result.setImportDatabase(dump); - - } else { - - ObserveDataSourceConfiguration configSrc = null; - - switch (getCreationMode()) { - case IMPORT_LOCAL_STORAGE: - configSrc = h2Config; - break; - case IMPORT_REMOTE_STORAGE: - configSrc = pgConfig; - break; - case IMPORT_SERVER_STORAGE: - configSrc = restConfig; - break; - } - - if (configSrc != null) { - try (ObserveSwingDataSource source = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(configSrc)) { - - source.open(); - - SqlScriptProducerService dumpService = source.newSqlScriptProducerService(); - - AddSqlScriptProducerRequest request = AddSqlScriptProducerRequest.forH2().addSchema().addReferential(); - byte[] dump = dumpService.produceAddSqlScript(request); - - result.setImportDatabase(dump); - } - - } - - } - - } - - return result; - } - - public ObserveDataSourceConfigurationTopiaH2 toH2StorageConfig(String label) { - - ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); - ObserveDataSourceConfigurationMainFactory configurationFactory = context.getObserveDataSourceConfigurationMainFactory(); - ObserveDataSourceConfigurationTopiaH2 result = configurationFactory.createObserveDataSourceConfigurationTopiaH2( - label, - h2Config.getDirectory(), - h2Config.getDbName(), - h2Config.getUsername(), - h2Config.getPassword(), - h2Config.isShowMigrationProgression(), - h2Config.isShowMigrationSql(), - h2Config.getModelVersion() - ); - return result; - } - - public ObserveDataSourceConfigurationTopiaPG toPGStorageConfig(String label) { - - ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); - ObserveDataSourceConfigurationMainFactory configurationFactory = context.getObserveDataSourceConfigurationMainFactory(); - ObserveDataSourceConfigurationTopiaPG result = configurationFactory.createObserveDataSourceConfigurationTopiaPG( - label, - pgConfig.getJdbcUrl(), - pgConfig.getUsername(), - pgConfig.getPassword(), - pgConfig.isUseSsl(), - pgConfig.isShowMigrationProgression(), - pgConfig.isShowMigrationSql(), - pgConfig.getModelVersion() - ); - return result; - } - - public ObserveDataSourceConfigurationRest toRestStorageConfig(String label) { - - ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); - ObserveDataSourceConfigurationMainFactory configurationFactory = context.getObserveDataSourceConfigurationMainFactory(); - ObserveDataSourceConfigurationRest result = configurationFactory.createObserveDataSourceConfigurationRest( - label, - restConfig.getServerUrl(), - restConfig.getLogin(), - restConfig.getPassword(), - restConfig.getOptionalDatabaseName().orElse(null), - restConfig.getModelVersion() - ); - return result; - } - - protected void copyTo(StorageUIModel dst) { - dst.setLocalStorageExist(isLocalStorageExist()); - dst.setBackupFile(getBackupFile()); - dst.setDoBackup(isDoBackup()); - dst.setStoreRemoteConfig(isStoreRemoteConfig()); - dst.setPreviousDataSourceConfiguration(getPreviousDataSourceConfiguration()); - dst.setCanCreateLocalService(isCanCreateLocalService()); - dst.setCanUseLocalService(isCanUseLocalService()); - dst.setCanUseRemoteService(isCanUseRemoteService()); - dst.setCanUseServerService(isCanUseServerService()); - dst.fromStorageConfig(h2Config); - dst.fromStorageConfig(pgConfig); - dst.fromStorageConfig(restConfig); - dst.setDbMode(getDbMode()); - dst.setSelectDataModel(getSelectDataModel()); - dst.setSecurityModel(getSecurityModel()); - dst.setAdminAction(getAdminAction()); - - dst.updateEditConfig(); - - dst.setUseSsl(isUseSsl()); - dst.setRemoteUrl(getRemoteUrl()); - dst.setRemoteLogin(getRemoteLogin()); - dst.setRemotePassword(getRemotePassword()); - dst.setServerDatabase(getServerDatabase()); - - dst.setDataSourceInformation(getDataSourceInformation()); - dst.setConnexionStatus(getConnexionStatus()); - - } - - public void firePgConfigChanged(String propertyName, - Object oldValue, - Object newValue) { - firePropertyChange(propertyName, oldValue, newValue); - validate(); - } - - /** - * Teste une connexion à distance à partir du modèle passé en paramètre. - * - * @return {@code true} si la connexion a pu être établie, - * {@code false} sinon. - */ - public boolean testRemote() { - - ObserveDataSourceConfiguration config = null; - boolean result = false; - boolean error = false; - connexionStatusError = ""; - setBusy(true); - - try { - - if (isEditRemoteConfig()) { - config = pgConfig; - } else if (isEditServerConfig()) { - try { - URL url = new URL(serverUrl); - - restConfig.setServerUrl(url); - - config = restConfig; - - } catch (MalformedURLException e) { - - connexionStatusError = t("observe.storage.error.badUrl", serverUrl); - - setConnexionStatus(ConnexionStatus.FAILED); - - } - - } - - if (config != null) { - - ObserveSwingDataSource dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(config); - - try { - - if (DbMode.USE_SERVER.equals(getDbMode()) - || DbMode.CREATE_LOCAL.equals(getDbMode()) && CreationMode.IMPORT_SERVER_STORAGE.equals(creationMode)) { - - PingService pingService = dataSource.newPingService(); - - Version modelServerVersion = pingService.ping(); - - if (!getModelVersion().equals(modelServerVersion)) { - - connexionStatusError = t("observe.storage.error.serverVersionMismatch", modelServerVersion, getModelVersion()); - - setConnexionStatus(ConnexionStatus.FAILED); - - error = true; - } - - } - - if (!error) { - - dataSourceInformation = dataSource.checkCanConnect(); - - Version versionDataSource = dataSourceInformation.getVersion(); - - // en mise a jour de la base on ne test pas la version - if (getModelVersion().equals(versionDataSource) || isCanMigrate() || ObstunaAdminAction.CREATE.equals(adminAction)) { - - setConnexionStatus(ConnexionStatus.SUCCESS); - - result = true; - - } else { - - connexionStatusError = t("observe.storage.error.dbVersionMismatch", versionDataSource, getModelVersion()); - - setConnexionStatus(ConnexionStatus.FAILED); - - } - } - - } catch (UnknownObserveWebUserException e) { - - connexionStatusError = t("observe.storage.error.rest.user.unknown", e.getUserLogin()); - setConnexionStatus(ConnexionStatus.FAILED); - - } catch (BadObserveWebUserPasswordException e) { - - connexionStatusError = t("observe.storage.error.rest.password.bad", e.getUserLogin()); - setConnexionStatus(ConnexionStatus.FAILED); - - } catch (UnknownObserveWebUserForDatabaseException e) { - - connexionStatusError = t("observe.storage.error.rest.database.unknownForUser", e.getDatabaseName(), e.getRole()); - setConnexionStatus(ConnexionStatus.FAILED); - - } catch (UserLoginNotFoundException e) { - - connexionStatusError = t("observe.storage.error.rest.user.required"); - setConnexionStatus(ConnexionStatus.FAILED); - - } catch (UserPasswordNotFoundException e) { - - connexionStatusError = t("observe.storage.error.rest.pasword.required"); - setConnexionStatus(ConnexionStatus.FAILED); - - } catch (ObserveWebSecurityExceptionSupport e) { - - connexionStatusError = e.getClass().getSimpleName(); - setConnexionStatus(ConnexionStatus.FAILED); - - } catch (Exception e) { - - connexionStatusError = e.getMessage(); - - if (log.isErrorEnabled()) { - log.error("Error in test remote", e); - } - - setConnexionStatus(ConnexionStatus.FAILED); - - } finally { - if (dataSource.isOpen()) { - dataSource.close(); - } - } - } - - } finally { - setBusy(false); - } - - return result; - } - - - public String getConnexionStatusError() { - return connexionStatusError; - } - - public void setSecurityModel(SecurityModel securityModel) { - this.securityModel = securityModel; - } - - public boolean isShowMigrationSql() { - return pgConfig.isShowMigrationSql(); - } - - public boolean isShowMigrationProgression() { - return pgConfig.isShowMigrationProgression(); - } - - public void setConnexionStatus(ConnexionStatus connexionStatus) { - ConnexionStatus oldValue = this.connexionStatus; - this.connexionStatus = connexionStatus; - firePgConfigChanged(CONNEXION_STATUS_PROPERTY_NAME, oldValue, connexionStatus); - } - - public void checkImportDbVersion(ObserveSwingDataSource source) { - - Version importServiceDbVersion = source.getVersion(); - Version currentDbVersion = getModelVersion(); - if (importServiceDbVersion.before(currentDbVersion)) { - throw new IllegalStateException("Import db version (" + importServiceDbVersion + ") is not compatible with the current database version (" + currentDbVersion + ")"); - } - - } - - public DataSourceCreateConfigurationDto toImportReferentielSourceConfig() { - - DataSourceCreateConfigurationDto importReferenceConfig = new DataSourceCreateConfigurationDto(); - - // on peut créer une base vide - importReferenceConfig.setCanCreateEmptyDatabase(true); - - if (isImportReferentiel()) { - - String dbLabel = t("observe.storage.label.reference.import.db"); - - switch (getReferentielImportMode()) { - - case IMPORT_EXTERNAL_DUMP: - - if (ObstunaAdminAction.CREATE.equals(getAdminAction())) { - - // on import que le référentiel donc on créé un base temporaire pour cette import - ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); - - DataSourceCreateConfigurationDto createConfigurationDto = new DataSourceCreateConfigurationDto(); - - File dumpFile = getCentralSourceModel().getDumpFile(); - - try (FileInputStream inputStream = new FileInputStream(dumpFile)) { - - byte[] bytes = IOUtils.toByteArray(inputStream); - - createConfigurationDto.setImportDatabase(bytes); - - } catch (Exception e) { - - throw new RuntimeException("Could not read dump file", e); - - } - - try (ObserveSwingDataSource importDataSource = context.createTemporaryH2Storage(dbLabel)) { - - try { - importDataSource.create(createConfigurationDto); - } catch (IncompatibleDataSourceCreateConfigurationException - | DataSourceCreateWithNoReferentialImportException - | DatabaseNotFoundException - | DatabaseConnexionNotAuthorizedException - | BabModelVersionException e) { - throw new ObserveSwingTechnicalException("Could not create import data source", e); - } - - importReferenceConfig.setImportReferentialDataSourceConfiguration(importDataSource.getConfiguration()); - - } - - - } else { - - File dumpFile = getDumpFile(); - - try (FileInputStream inputStream = new FileInputStream(dumpFile)) { - - byte[] bytes = IOUtils.toByteArray(inputStream); - - importReferenceConfig.setImportDatabase(bytes); - - } catch (IOException e) { - - throw new RuntimeException("Could not read dump file", e); - - } - - } - - - break; - case IMPORT_REMOTE_STORAGE: - - // import referentiel from a remote db - ObserveDataSourceConfigurationTopiaPG pgConfig = getCentralSourceModel().toPGStorageConfig(dbLabel); - - pgConfig.setCanMigrate(false); - - importReferenceConfig.setImportReferentialDataSourceConfiguration(pgConfig); - - break; - - case IMPORT_SERVER_STORAGE: - - // import referentiel from a server db - ObserveDataSourceConfigurationRest restConfig = getCentralSourceModel().toRestStorageConfig(dbLabel); - - importReferenceConfig.setImportReferentialDataSourceConfiguration(restConfig); - - break; - - default: - throw new IllegalStateException("Can't come here"); - - } - - } - - return importReferenceConfig; - - - } - - public ObserveSwingDataSource toImportDataSourceConfig() { - - ObserveSwingDataSource importDataSource; - - if (isImportData()) { - - String dbLabel = t("observe.storage.label.data.import.db"); - - switch (getDataImportMode()) { - - case IMPORT_EXTERNAL_DUMP: - - ObserveSwingApplicationContext context = ObserveSwingApplicationContext.get(); - - DataSourceCreateConfigurationDto createConfigurationDto = new DataSourceCreateConfigurationDto(); - - File dumpFile = ObstunaAdminAction.CREATE.equals(getAdminAction()) ? getDataSourceModel().getDumpFile() : getDumpFile(); - - try (FileInputStream inputStream = new FileInputStream(dumpFile)) { - - byte[] bytes = IOUtils.toByteArray(inputStream); - - createConfigurationDto.setImportDatabase(bytes); - - - } catch (Exception e) { - - throw new RuntimeException("Could not read dump file", e); - - } - - try (ObserveSwingDataSource importDataSource2 = context.createTemporaryH2Storage(dbLabel)) { - - importDataSource = importDataSource2; - - try { - importDataSource2.create(createConfigurationDto); - } catch (IncompatibleDataSourceCreateConfigurationException - | DataSourceCreateWithNoReferentialImportException - | DatabaseNotFoundException - | DatabaseConnexionNotAuthorizedException - | BabModelVersionException e) { - throw new ObserveSwingTechnicalException("Could not create import data source", e); - } - - } - - break; - case IMPORT_REMOTE_STORAGE: { - - // import referentiel from a remote db - ObserveDataSourceConfigurationTopiaPG dataSourceConfig = getDataSourceModel().toPGStorageConfig(dbLabel); - - dataSourceConfig.setCanMigrate(false); - - importDataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(dataSourceConfig); - - } - break; - - case IMPORT_SERVER_STORAGE: { - - // import referentiel from a server db - ObserveDataSourceConfigurationRest dataSourceConfig = getDataSourceModel().toRestStorageConfig(dbLabel); - - importDataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(dataSourceConfig); - - } - break; - default: - throw new IllegalStateException("Can't come here"); - } - - } else { - - importDataSource = null; - - } - - return importDataSource; - - } - - public ObserveDataSourceInformation getDataSourceInformation() { - if (DbMode.USE_LOCAL.equals(dbMode)) { - return getH2DataSourceInformation(); - } - - return dataSourceInformation; - } - - public ObserveDataSourceInformation getH2DataSourceInformation() { - if (h2DataSourceInformation == null && localStorageExist) { - ObserveSwingDataSource dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().newDataSource(h2Config); - try { - h2DataSourceInformation = dataSource.checkCanConnect(); - } catch (Exception e) { - if (log.isDebugEnabled()) { - log.debug("error on load data source information for local storage", e); - } - } - } - - return h2DataSourceInformation; - } - - public void setDataSourceInformation(ObserveDataSourceInformation dataSourceInformation) { - this.dataSourceInformation = dataSourceInformation; - } - - private boolean isValidDumpFile(File dumpFile) { - return dumpFile != null && - dumpFile.exists() && - dumpFile.getName().endsWith(".sql.gz"); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/BackupUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/BackupUI.jaxx deleted file mode 100644 index 63f7afa..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/BackupUI.jaxx +++ /dev/null @@ -1,86 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<!-- *************************************** --> -<!-- L'écran de sauvegarde de la base locale --> -<!-- *************************************** --> - -<StorageTabUI> - - <import> - fr.ird.observe.ui.storage.StorageStep - java.io.File - </import> - - <StorageStep id='step' initializer='StorageStep.BACKUP'/> - - <fr.ird.observe.ui.storage.StorageUIModel id='model'/> - - <script><![CDATA[ - -@Override -public void init() { - getHandler().initUI(this); -} -]]> - </script> - - <JPanel id='content'> - <Table fill='both' constraints='BorderLayout.CENTER'> - <row> - <cell columns='2'> - <JCheckBox id='doBackup' - onStateChanged='getModel().setDoBackup(((JCheckBox)event.getSource()).isSelected())'/> - </cell> - </row> - <row> - <cell weightx='1' fill="both"> - <Table fill='both'> - <row> - <cell> - <JLabel id="directoryLabel"/> - </cell> - <cell weightx='1' fill="horizontal"> - <JTextField id='directoryText' - onKeyReleased='getHandler().changeDirectory(this, new File(((JTextField)event.getSource()).getText()))'/> - </cell> - <cell anchor="east"> - <JButton id="chooseFileAction" - onActionPerformed="getHandler().chooseBackupFile(this)"/> - </cell> - </row> - <row> - <cell> - <JLabel id="fileLabel"/> - </cell> - <cell weightx='1' fill="horizontal" columns="2"> - <JTextField id='filenameText' - onKeyReleased='getHandler().changeFilename(this, ((JTextField) event.getSource()).getText())'/> - </cell> - </row> - </Table> - </cell> - </row> - </Table> - </JPanel> - -</StorageTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ChooseDbModeUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ChooseDbModeUI.jaxx deleted file mode 100644 index 48ef0ee..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ChooseDbModeUI.jaxx +++ /dev/null @@ -1,109 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<!-- ***************************************** --> -<!-- L'écran de sélection de type de connexion --> -<!-- ***************************************** --> -<StorageTabUI> - - <import> - fr.ird.observe.ObserveSwingApplicationContext - fr.ird.observe.configuration.ObserveSwingApplicationConfig - fr.ird.observe.ui.UIHelper - fr.ird.observe.ui.storage.StorageStep - fr.ird.observe.db.constants.DbMode - fr.ird.observe.db.constants.CreationMode - </import> - - <StorageStep id='step' initializer='StorageStep.CHOOSE_DB_MODE'/> - - <fr.ird.observe.ui.storage.StorageUIModel id='model'/> - - <ObserveSwingApplicationConfig id='config' initializer="ObserveSwingApplicationContext.get().getConfig()"/> - - <ButtonGroup id='dbMode' onStateChanged='getModel().setDbMode((DbMode) dbMode.getSelectedValue())'/> - - <ButtonGroup id='creationMode' onStateChanged='getModel().setCreationMode((CreationMode) creationMode.getSelectedValue())'/> - - <CardLayout2Ext id='creationModeLayout' constructorParams='this, "creationModeContent"'/> - - <script><![CDATA[ -@Override -public void init() { - getHandler().initUI(this); -} - -protected String updateMigrationPolicy(boolean canMigrate) { - if (canMigrate) { - return t("observe.storage.report.can.migrate", config.getModelVersion()); - } else { - return t("observe.storage.report.can.not.migrate"); - } -} - -protected String updateCreationModeContent(DbMode mode) { - return mode == DbMode.CREATE_LOCAL ? "createMode" : "noCreateMode"; -} -]]> - </script> - - <JPanel id='content'> - - <JPanel layout='{new BorderLayout()}' constraints='BorderLayout.NORTH'> - <JPanel id='dbModeContent' constraints='BorderLayout.NORTH'> - <JRadioButton id="useLocalMode" styleClass='dbMode'/> - <JRadioButton id="useRemoteMode" styleClass='dbMode'/> - <JRadioButton id="useServerMode" styleClass='dbMode'/> - <JRadioButton id="createLocalMode" styleClass='dbMode'/> - </JPanel> - - <JPanel id='creationModeContent' constraints='BorderLayout.CENTER'> - - <JPanel id='useCreateMode' constraints='"createMode"'> - <JRadioButton id="importInternalDumpMode" styleClass='creationMode'/> - <JRadioButton id="importExternalDumpMode" styleClass='creationMode'/> - <JRadioButton id="importLocalStorageMode" styleClass='creationMode'/> - <JRadioButton id="importRemoteStorageMode" styleClass='creationMode'/> - <JRadioButton id="importServerStorageMode" styleClass='creationMode'/> - </JPanel> - <JLabel id='noCreateMode' constraints='"noCreateMode"'/> - - </JPanel> - - <JPanel id='migrationContent' constraints='BorderLayout.SOUTH'> - <JLabel id='migrationPolicy'/> - <JCheckBox id='showMigrationSql' - onStateChanged='getModel().setShowMigrationSql(((JCheckBox)event.getSource()).isSelected())'/> - <JCheckBox id='showMigrationProgression' - onStateChanged='getModel().setShowMigrationProgression(((JCheckBox)event.getSource()).isSelected())'/> - </JPanel> - </JPanel> - - <JScrollPane id="resumePane" constraints='BorderLayout.CENTER'> - <JTextPane id='resume'/> - </JScrollPane> - - </JPanel> - - <JScrollPane id="descriptionPane" visible='false'/> - -</StorageTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ConfigDataUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ConfigDataUI.jaxx deleted file mode 100644 index fcfd9e6..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ConfigDataUI.jaxx +++ /dev/null @@ -1,174 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<!-- ************************************************** --> -<!-- L'écran de configuration des données à importer --> -<!-- ************************************************** --> - -<StorageTabUI> - - <import> - fr.ird.observe.db.constants.CreationMode - fr.ird.observe.ui.storage.StorageStep - - javax.swing.Icon - - java.io.File - - static org.nuiton.i18n.I18n.n - </import> - - <StorageStep id='step' initializer='StorageStep.CONFIG_DATA'/> - - <fr.ird.observe.ui.storage.StorageUIModel id='model'/> - <fr.ird.observe.ui.storage.StorageUIModel id='centralSourceModel' initializer='model.getDataSourceModel()'/> - - <ButtonGroup id='creationMode' - onStateChanged='model.setDataImportMode((CreationMode) creationMode.getSelectedValue())'/> - - <CardLayout id='configLayout'/> - - <script><![CDATA[ -@Override -public void init() { - getHandler().initUI(this); -} -]]> - </script> - - <JPanel id='content' layout='{new BorderLayout()}'> - - <Table id="dataSourceConfig" insets="1" weightx='1' fill='both' - constraints='BorderLayout.CENTER'> - <row> - <cell anchor='north'> - <JPanel id='dataModeConfig'> - <JRadioButton id="noImportData" styleClass='creationMode'/> - <JRadioButton id="importDataFromBackup" styleClass='creationMode'/> - <JRadioButton id="importDataFromRemote" styleClass='creationMode'/> - <JRadioButton id="importDataFromServer" styleClass='creationMode'/> - </JPanel> - </cell> - </row> - <row> - <cell anchor='center'> - <JPanel id='configContent'> - - <!-- pas d'import de data --> - <Table id='EMPTY' constraints='"EMPTY"' fill='both'> - <row> - <cell> - <JLabel id='noImportDataConfig'/> - </cell> - </row> - </Table> - - <!-- importer des données a partir d'une sauvegarde --> - <Table id='IMPORT_EXTERNAL_DUMP' constraints='"IMPORT_EXTERNAL_DUMP"'> - <row> - <cell> - <JLabel text='observe.storage.importExternalDumpData.config'/> - </cell> - </row> - <row weighty='1'> - <cell weightx='1' fill="horizontal"> - <JTextField id="dumpFile" - onKeyReleased='centralSourceModel.setDumpFile(new File(((JTextField)event.getSource()).getText())); model.validate();'/> - </cell> - <cell anchor="east"> - <JButton id="fileChooserAction" - onActionPerformed="getHandler().chooseDumpFile(this)"/> - </cell> - </row> - </Table> - - <!-- importer les données a partir d'une base distante --> - <Table id='IMPORT_REMOTE_STORAGE' fill="both" - constraints='"IMPORT_REMOTE_STORAGE"'> - <row> - <cell> - <JLabel - text='observe.storage.importRemoteStorageData.config'/> - </cell> - </row> - <row> - <cell weightx='1' fill='both'> - <JLabel id='centralSourceLabel'/> - </cell> - <cell> - <JButton id='configureCentralSource' - onActionPerformed='getHandler().obtainRemoteConnexion(this)'/> - </cell> - <cell anchor='east'> - <JLabel id='centralSourceStatus'/> - </cell> - </row> - <row> - <cell fill='both' columns="2"> - <JLabel id='centralSourcePolicy'/> - </cell> - </row> - <row> - <cell fill='both' columns="2"> - <JLabel id='centralSourceInfoLabel'/> - </cell> - </row> - </Table> - - <!-- importer les données a partir d'une base distante --> - <Table id='IMPORT_SERVER_STORAGE' fill="both" - constraints='"IMPORT_SERVER_STORAGE"'> - <row> - <cell> - <JLabel - text='observe.storage.importServerStorageData.config'/> - </cell> - </row> - <row> - <cell weightx='1' fill='both'> - <JLabel id='centralSourceServerLabel'/> - </cell> - <cell> - <JButton id='configureCentralSourceServer' - onActionPerformed='getHandler().obtainServerConnexion(this)'/> - </cell> - <cell anchor='east'> - <JLabel id='centralSourceServerStatus'/> - </cell> - </row> - <row> - <cell fill='both' columns="2"> - <JLabel id='centralSourceServerPolicy'/> - </cell> - </row> - <row> - <cell fill='both' columns="2"> - <JLabel id='centralSourceServerInfoLabel'/> - </cell> - </row> - </Table> - </JPanel> - </cell> - </row> - </Table> - </JPanel> - -</StorageTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ConfigReferentielUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ConfigReferentielUI.jaxx deleted file mode 100644 index 1348012..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ConfigReferentielUI.jaxx +++ /dev/null @@ -1,181 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<!-- ************************************************** --> -<!-- L'écran de configuration du référentiel à importer --> -<!-- ************************************************** --> - -<StorageTabUI> - - <import> - fr.ird.observe.db.constants.CreationMode - fr.ird.observe.ui.storage.StorageStep - - javax.swing.Icon - - java.io.File - - static org.nuiton.i18n.I18n.n - </import> - - <StorageStep id='step' initializer='StorageStep.CONFIG_REFERENTIEL'/> - - <fr.ird.observe.ui.storage.StorageUIModel id='model'/> - <fr.ird.observe.ui.storage.StorageUIModel id='centralSourceModel' - initializer='model.getCentralSourceModel()'/> - - <ButtonGroup id='creationMode' - onStateChanged='model.setReferentielImportMode((CreationMode) creationMode.getSelectedValue())'/> - - <CardLayout id='configLayout'/> - - <script><![CDATA[ -@Override -public void init() { - getHandler().initUI(this); -} -]]> - </script> - - <JPanel id='content' layout='{new BorderLayout()}'> - - <Table id="referentielSourceConfig" insets="1" weightx='1' fill='both' - constraints='BorderLayout.CENTER'> - <row> - <cell anchor='north'> - <JPanel id='referentielModeConfig'> - <JRadioButton id="noImportReferentiel" styleClass='creationMode'/> - <JRadioButton id="importReferentielFromBackup" - styleClass='creationMode'/> - <JRadioButton id="importReferentielFromRemote" - styleClass='creationMode'/> - <JRadioButton id="importReferentielFromServer" - styleClass='creationMode'/> - </JPanel> - </cell> - </row> - <row> - <cell anchor='center'> - <JPanel id='configContent'> - - <!-- pas de referentiel --> - <Table id='EMPTY' constraints='"EMPTY"' fill='both'> - <row> - <cell> - <JLabel id='noImportReferentielConfig'/> - </cell> - </row> - </Table> - - <!-- importer le référentiel a partir d'une sauvegarde --> - <Table id='IMPORT_EXTERNAL_DUMP' - constraints='"IMPORT_EXTERNAL_DUMP"'> - <row> - <cell> - <JLabel - text='observe.storage.importExternalDumpReferentiel.config'/> - </cell> - </row> - <row weighty='1'> - <cell weightx='1' fill="horizontal"> - <JTextField id="dumpFile" - onKeyReleased='centralSourceModel.setDumpFile(new File(((JTextField)event.getSource()).getText())); model.validate();'/> - </cell> - <cell anchor="east"> - <JButton id="fileChooserAction" - onActionPerformed="getHandler().chooseDumpFile(this)"/> - </cell> - </row> - </Table> - - <!-- importer le référentiel a partir d'une base distante --> - <Table id='IMPORT_REMOTE_STORAGE' fill="both" - constraints='"IMPORT_REMOTE_STORAGE"'> - <row> - <cell> - <JLabel - text='observe.storage.importRemoteStorageReferentiel.config'/> - </cell> - </row> - <row> - <cell weightx='1' fill='both'> - <JLabel id='centralSourceLabel'/> - </cell> - <cell> - <JButton id='configureCentralSource' - onActionPerformed='getHandler().obtainRemoteConnexion(this)'/> - </cell> - <cell anchor='east'> - <JLabel id='centralSourceStatus'/> - </cell> - </row> - <row> - <cell fill='both' columns="2"> - <JLabel id='centralSourcePolicy'/> - </cell> - </row> - <row> - <cell fill='both' columns="2"> - <JLabel id='centralSourceInfoLabel'/> - </cell> - </row> - </Table> - - <!-- importer le référentiel a partir d'un serveur distant --> - <Table id='IMPORT_SERVER_STORAGE' fill="both" - constraints='"IMPORT_SERVER_STORAGE"'> - <row> - <cell> - <JLabel - text='observe.storage.importServerStorageReferentiel.config'/> - </cell> - </row> - <row> - <cell weightx='1' fill='both'> - <JLabel id='centralSourceServerLabel'/> - </cell> - <cell> - <JButton id='configureCentralSourceServer' - onActionPerformed='getHandler().obtainServerConnexion(this)'/> - </cell> - <cell anchor='east'> - <JLabel id='centralSourceServerStatus'/> - </cell> - </row> - <row> - <cell fill='both' columns="2"> - <JLabel id='centralSourceServerPolicy'/> - </cell> - </row> - <row> - <cell fill='both' columns="2"> - <JLabel id='centralSourceServerInfoLabel'/> - </cell> - </row> - </Table> - - </JPanel> - </cell> - </row> - </Table> - </JPanel> - -</StorageTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ConfigUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ConfigUI.jaxx deleted file mode 100644 index 1366d30..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ConfigUI.jaxx +++ /dev/null @@ -1,293 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<!-- ***************************************** --> -<!-- L'écran de configuration de la source --> -<!-- ***************************************** --> - -<StorageTabUI> - - <import> - fr.ird.observe.ui.storage.StorageStep - fr.ird.observe.db.constants.ConnexionStatus - fr.ird.observe.db.constants.DbMode; - - java.awt.Color - java.awt.Dimension - - java.io.File - - javax.swing.border.LineBorder - javax.swing.text.html.HTMLEditorKit - - static org.nuiton.i18n.I18n.n - </import> - - <StorageStep id='step' initializer='StorageStep.CONFIG'/> - - <fr.ird.observe.ui.storage.StorageUIModel id='model'/> - - <CardLayout id='configLayout'/> - - <script><![CDATA[ -@Override -public void init() { - getHandler().initUI(this); -} -]]> - </script> - - <JPanel id='content' layout='{new BorderLayout()}'> - <Table fill='both' weightx='1' constraints='BorderLayout.CENTER'> - <row> - <cell anchor='north'> - <JPanel id='configContent'> - - <!-- configurer creation base locale a partir d'une sauvegarde --> - <Table id='IMPORT_EXTERNAL_DUMP' - constraints='"IMPORT_EXTERNAL_DUMP"'> - <row> - <cell> - <JLabel text='observe.storage.importExternalDump.config'/> - </cell> - </row> - <row weighty='1'> - <cell weightx='1' fill="horizontal"> - <JTextField id="dumpFile" - onKeyReleased='getModel().setDumpFile(new File(((JTextField)event.getSource()).getText()))'/> - </cell> - <cell anchor="east"> - <JButton id="fileChooserAction" - onActionPerformed="getHandler().chooseDumpFile(this)"/> - </cell> - </row> - </Table> - - <!-- configurer creation base locale et import referentiel depuis base distante --> - <!--Table id='IMPORT_LOCAL_STORAGE' - constraints='"IMPORT_LOCAL_STORAGE"' - _description='n("observe.storage.importLocalStorage.description")'> - <row> - <cell> - <JLabel text='observe.storage.importLocalStorage.config'/> - </cell> - </row> - <row weighty='1'> - <cell weightx='1' fill="horizontal"> - <JTextField text='{model.getLocalStorageFile()+""}' - onKeyReleased='getModel().setLocalStorageFile(new File(((JTextField)event.getSource()).getText()))'/> - </cell> - <cell anchor="east"> - <JButton actionIcon='fileChooser' onActionPerformed="chooseLocalStorageFile()"/> - </cell> - </row> - </Table--> - - <!-- configurer creation base locale et import referentiel depuis base distante --> - <Table id='IMPORT_REMOTE_STORAGE' - fill="both" - constraints='"IMPORT_REMOTE_STORAGE"'> - <row> - <cell> - <JLabel text='observe.storage.importRemoteStorage.config'/> - </cell> - </row> - <row> - <cell weighty='1' weightx='1'> - <JPanel id='IMPORT_REMOTE_STORAGE_content'/> - </cell> - </row> - - </Table> - - <!-- configurer creation base locale et import referentiel depuis un server distant --> - <Table id='IMPORT_SERVER_STORAGE' - fill="both" - constraints='"IMPORT_SERVER_STORAGE"'> - <row> - <cell> - <JLabel text='observe.storage.importServerStorage.config'/> - </cell> - </row> - <row> - <cell weighty='1' weightx='1'> - <JPanel id='IMPORT_SERVER_STORAGE_content'/> - </cell> - </row> - - </Table> - - <!-- configurer connexion a base distante --> - <Table id='USE_REMOTE' - constraints='"USE_REMOTE"' fill='both'> - <row> - <cell> - <JLabel text='observe.storage.useRemoteStorage.config'/> - </cell> - </row> - <row> - <cell weighty='1' weightx='1'> - <JPanel id='USE_REMOTE_content' - minimumSize='{new Dimension(20,300)}'/> - </cell> - </row> - </Table> - - <!-- configurer connexion au server base distante --> - <Table id='USE_SERVER' - constraints='"USE_SERVER"' fill='both'> - <row> - <cell> - <JLabel text='observe.storage.useServerStorage.config'/> - </cell> - </row> - <row> - <cell weighty='1' weightx='1'> - <JPanel id='USE_SERVER_content' - minimumSize='{new Dimension(20,300)}'/> - </cell> - </row> - </Table> - - <JPanel constraints='"$$hideme$$"' visible='false'> - <JPanel id='remoteConfig'> - <Table constraints='BorderLayout.CENTER' - fill="both"> - <row> - <cell anchor='west'> - <JLabel text='observe.storage.remote.url'/> - </cell> - <cell weightx='1' fill="both" anchor='east'> - <JTextField id="remoteUrl" - onKeyReleased='getModel().setRemoteUrl(((JTextField)event.getSource()).getText())'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel text='observe.storage.remote.login'/> - </cell> - <cell weightx='1' fill="both" anchor='east'> - <JTextField id="remoteLogin" - onKeyReleased='getModel().setRemoteLogin(((JTextField)event.getSource()).getText())'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel text='observe.storage.remote.password'/> - </cell> - <cell weightx='1' fill="both" anchor='east'> - <JPasswordField id="remotePassword" - onKeyReleased='getModel().setRemotePassword(((JPasswordField)event.getSource()).getPassword())'/> - </cell> - </row> - <row> - <cell anchor='west'> - <JLabel id="serverDataBaseLabel" - text='observe.storage.server.dataBase'/> - </cell> - <cell weightx='1' fill="both" anchor='east'> - <JTextField id="serverDataBase" - onKeyReleased='getModel().setServerDatabase(((JTextField)event.getSource()).getText())'/> - </cell> - </row> - <row> - <cell columns='2'> - <JCheckBox id="remoteUseSsl" - onActionPerformed='getModel().setUseSsl(((JCheckBox)event.getSource()).isSelected())'/> - </cell> - </row> - <!--row weighty='1'--> - <!--row> - <cell columns='2'> - <Table insets='0'> - <row> - <cell weightx='1' - fill="horizontal"> - <JTextField - id="remoteSslCertificatFile" - onKeyReleased='getModel().setSslCertificatFile(new File(((JTextField)event.getSource()).getText()))'/> - </cell> - <cell anchor="east"> - <JButton - id="remoteSslCertificatFileChooseaction" - onActionPerformed="getHandler().chooseSslCertificatFile(this)"/> - </cell> - </row> - </Table> - </cell> - </row--> - <!--row> - <cell columns='2'> - <Table insets='0'> - <row> - <cell anchor='west'> - <JLabel text='observe.storage.remote.ssl.password'/> - </cell> - <cell weightx='1' fill="both" anchor='east'> - <JPasswordField id="remoteSslCertificatPassword" - onKeyReleased='getModel().setSslCertificatPassword(((JPasswordField)event.getSource()).getPassword())'/> - </cell> - </row> - </Table> - </cell> - </row--> - - <!-- sauver dans la configuration --> - <row> - <cell columns='2'> - <JCheckBox id="storeRemoteConfig" - onActionPerformed='getModel().setStoreRemoteConfig(((JCheckBox)event.getSource()).isSelected())'/> - </cell> - </row> - <!-- tester la connexion --> - <row> - <cell columns='2'> - <JButton id="testRemoteAction" - onActionPerformed='getModel().testRemote()'/> - </cell> - </row> - </Table> - <!-- résumé du test de connexion --> - <Table constraints='BorderLayout.SOUTH' fill='both' - insets='0'> - <row> - <cell weightx='1' weighty='1'> - <JScrollPane id="connexionStatusPanel"> - <JTextPane id='connexionStatus'/> - </JScrollPane> - </cell> - </row> - <row> - <cell> - <JLabel id="connexionStatusLabel"/> - </cell> - </row> - </Table> - </JPanel> - </JPanel> - </JPanel> - </cell> - </row> - </Table> - </JPanel> - -</StorageTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ConfirmUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ConfirmUI.jaxx deleted file mode 100644 index 8ec59e7..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/ConfirmUI.jaxx +++ /dev/null @@ -1,51 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<!-- ************************--> -<!-- L'écran de confirmation --> -<!-- ************************--> - -<StorageTabUI> - - <import> - fr.ird.observe.ui.storage.StorageStep - </import> - - <StorageStep id='step' initializer='StorageStep.CONFIRM'/> - - <fr.ird.observe.ui.storage.StorageUIModel id='model'/> - - <script><![CDATA[ -@Override -public void init() { - getHandler().initUI(this); -} -]]> - </script> - - <JPanel id='content'> - <JScrollPane id="resumePane" constraints='BorderLayout.CENTER'> - <JTextPane id='resume'/> - </JScrollPane> - </JPanel> - -</StorageTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/DataSelectionModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/DataSelectionModel.java deleted file mode 100644 index 9f60fa0..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/DataSelectionModel.java +++ /dev/null @@ -1,566 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.storage.tabs; - -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.AbstractReference; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.DataReferenceSet; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.referential.ProgramDtos; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialDtos; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.services.service.longline.TripLonglineService; -import fr.ird.observe.services.service.seine.TripSeineService; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - -/** - * Un modèle pour représenter la sélection de données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class DataSelectionModel implements Serializable { - - public static void populate(DataSelectionModel model, ObserveSwingDataSource source) { - - Preconditions.checkState(source.isOpen()); - - Map<ReferentialReference<ProgramDto>, List<DataReference>> datas = Maps.newHashMap(); - - TripSeineService tripSeineService = source.newTripSeineService(); - TripLonglineService tripLonglineService = source.newTripLonglineService(); - - Set<ReferentialReference<ProgramDto>> programSet = source.getReferentialReferences(ProgramDto.class); - - for (ReferentialReference<ProgramDto> program : programSet) { - - List<DataReference> referenceDtos = Lists.newArrayList(); - - if (ProgramDtos.isProgramSeine(program)) { - - DataReferenceSet<TripSeineDto> tripSeineRef = tripSeineService.getTripSeineByProgram(program.getId()); - referenceDtos.addAll(tripSeineRef.getReferences()); - - } else if (ProgramDtos.isProgramLongline(program)) { - - DataReferenceSet<TripLonglineDto> tripLonglineRef = tripLonglineService.getTripLonglineByProgram(program.getId()); - referenceDtos.addAll(tripLonglineRef.getReferences()); - - } - - populate(program, referenceDtos, datas); - - } - model.setDatas(datas); - - } - - protected static void populate(ReferentialReference<ProgramDto> program, - List<DataReference> trips, - Map<ReferentialReference<ProgramDto>, List<DataReference>> datas) { - - if (!trips.isEmpty()) { - - datas.put(program, trips); - if (log.isDebugEnabled()) { - log.debug("Add program " + program.getPropertyValue(ProgramDto.PROPERTY_LABEL1) + " with " + trips.size() + " trip(s)."); - } - - - } - - } - - public static final String PROPERTY_USE_REFERENTIEL = "useReferentiel"; - - public static final String PROPERTY_USE_DATA = "useData"; - - public static final String PROPERTY_USE_OPEN_DATA = "useOpenData"; - - public static final String PROPERTY_SELECTED_DATA = "selectedData"; - - public static final String PROPERTY_SELECTED_REFERENTIEL = "selectedReferentiel"; - - public static final String PROPERTY_DATAS = "datas"; - - /** Logger */ - private static final Log log = LogFactory.getLog(DataSelectionModel.class); - - private static final long serialVersionUID = 2L; - - /** un drapeau pour selectionner ou non les donnees observers */ - protected boolean useData; - - /** un drapeau pour selectionner ou non des donnees observers ouvertes */ - protected boolean useOpenData; - - /** un drapeau pour selectionner ou non des donnees observer */ - protected boolean useReferentiel; - - /** la liste des programs utilisables (qui ont des marees) */ - protected transient Map<ReferentialReference<ProgramDto>, List<DataReference>> datas; - - /** la liste des marees selectionnee */ - protected transient Set<DataReference> selectedData; - - /** la liste des referentiels possibles */ - protected final Set<Class<? extends ReferentialDto>> referentiel; - - /** la liste des referentiels selectionnes */ - protected final Set<Class<? extends ReferentialDto>> selectedReferentiel; - - /** nb marees */ - protected int nbTrips; - - /** nb referentiels */ - protected final int nbReferentiels; - - protected final PropertyChangeSupport pcs; - - public void populate() { - throw new UnsupportedOperationException(); - } - - public DataSelectionModel() { - pcs = new PropertyChangeSupport(this); - referentiel = Sets.newHashSet(ReferentialDtos.REFERENCE_DTOS); - selectedReferentiel = Sets.newHashSet(); - nbReferentiels = referentiel.size(); - } - - public boolean isUseReferentiel() { - return useReferentiel; - } - - public boolean isUseData() { - return useData; - } - - public boolean isUseOpenData() { - return useOpenData; - } - - public boolean isEmpty() { - if (isUseReferentiel()) { - if (!isReferentielEmpty()) { - return false; - } - } - if (isUseData()) { - if (!isDataEmpty()) { - return false; - } - } - return true; - } - - - public boolean isReferentielEmpty() { - return selectedReferentiel.isEmpty(); - } - - public boolean isReferentielFull() { - return selectedReferentiel.size() == nbReferentiels; - } - - public boolean isDataEmpty() { - return selectedData == null || selectedData.isEmpty(); - } - - public boolean isDataFull() { - return selectedData != null && selectedData.size() == nbTrips; - } - - public int selectDataSize() { - return selectedData == null ? 0 : selectedData.size(); - } - - public Set<Class<? extends ReferentialDto>> getSelectedReferentiel() { - return selectedReferentiel; - } - - public Map<ReferentialReference<ProgramDto>, List<DataReference>> getDatas() { - if (datas == null) { - datas = Maps.newHashMap(); - } - return datas; - } - - public boolean containsData(ReferentialReference<ProgramDto> program, DataReference trip) { - List<DataReference> datas = getDatas(program.getId()); - return datas!=null && datas.contains(trip); - } - - public Set<DataReference> getSelectedData() { - if (selectedData == null) { - selectedData = Sets.newHashSet(); - } - return selectedData; - } - - public Map<ReferentialReference<ProgramDto>, List<DataReference>> getSelectedDataByProgram() { - if (datas == null || selectedData == null || selectedData.isEmpty()) { - return Collections.emptyMap(); - } - Map<ReferentialReference<ProgramDto>, List<DataReference>> result = Maps.newHashMap(); - - for (DataReference referenceDto : selectedData) { - - // on recherche son program - for (ReferentialReference<ProgramDto> p : datas.keySet()) { - if (datas.get(p).contains(referenceDto)) { - List<DataReference> referenceDtos = result.get(p); - if (referenceDtos == null) { - referenceDtos = Lists.newArrayList(); - result.put(p, referenceDtos); - } - referenceDtos.add(referenceDto); - break; - } - } - } - return result; - } - - public List<ReferentialReference<ProgramDto>> getSelectedProgram() { - if (datas == null || selectedData == null || selectedData.isEmpty()) { - return Collections.emptyList(); - } - - Set<ReferentialReference<ProgramDto>> result = Sets.newHashSet(); - - for (DataReference referenceDto : selectedData) { - - // on recherche son program - for (ReferentialReference<ProgramDto> p : datas.keySet()) { - if (datas.get(p).contains(referenceDto)) { - result.add(p); - break; - } - } - } - - return result.stream().collect(Collectors.toList()); - } - - public List<DataReference> getSelectedTripsByProgram(ReferentialReference<ProgramDto> program) { - if (datas == null || selectedData == null || selectedData.isEmpty()) { - return Collections.emptyList(); - } - - List<DataReference> result = datas.get(program).stream() - .filter(trip -> selectedData.contains(trip)) - .collect(Collectors.toList()); - - return result; - } - - - public boolean isSelectedData(AbstractReference<?> referenceDto) { - - boolean result; - - if (ProgramDto.class.isAssignableFrom(referenceDto.getType())) { - - List<DataReference> trips = datas.get(referenceDto); - result = CollectionUtils.isNotEmpty(trips); - - if (result) { - for (DataReference trip : trips) { - if (!getSelectedData().contains(trip)) { - - // au moins une marée non sélectionnée - - result = false; - } - } - } - } else { - - // recherche directe sur les ids de marees - result = getSelectedData().contains(referenceDto); - - } - - // ne devrait pas arrivée - return result; - - } - - public boolean isSelectedReferentiel(Class<?> type) { - checkReferentielType(type); - return getSelectedReferentiel().contains(type); - } - - public void setUseReferentiel(boolean useReferentiel) { - this.useReferentiel = useReferentiel; - firePropertyChange(PROPERTY_USE_REFERENTIEL, useReferentiel); - } - - public void setUseData(boolean useData) { - this.useData = useData; - firePropertyChange(PROPERTY_USE_DATA, useData); - } - - public void setUseOpenData(boolean useOpenData) { - this.useOpenData = useOpenData; - firePropertyChange(PROPERTY_USE_OPEN_DATA, useOpenData); - } - - public void addSelectedReferentiel(Class<? extends ReferentialDto> type) { - checkReferentielType(type); - if (log.isDebugEnabled()) { - log.debug("Add referentiel type " + type); - } - getSelectedReferentiel().add(type); - firePropertyChange(PROPERTY_SELECTED_REFERENTIEL, selectedReferentiel); - } - - public void addAllSelectedReferentiel() { - getSelectedReferentiel().addAll(referentiel); - firePropertyChange(PROPERTY_SELECTED_REFERENTIEL, selectedReferentiel); - } - - public void removeSelectedReferentiel(Class<?> type) { - checkReferentielType(type); - if (log.isDebugEnabled()) { - log.debug("remove referentiel type " + type); - } - getSelectedReferentiel().remove(type); - firePropertyChange(PROPERTY_SELECTED_REFERENTIEL, selectedReferentiel); - } - - public void removeAll() { - getSelectedReferentiel().clear(); - getSelectedData().clear(); - firePropertyChange(PROPERTY_SELECTED_REFERENTIEL, selectedReferentiel); - firePropertyChange(PROPERTY_SELECTED_DATA, selectedData); - } - - public void removeAllSelectedReferentiel() { - getSelectedReferentiel().clear(); - firePropertyChange(PROPERTY_SELECTED_REFERENTIEL, selectedReferentiel); - } - - public boolean isReferentielSelectAll(Collection<Class<? extends ReferentialDto>> classes) { - return selectedReferentiel.containsAll(classes); - } - - public void removeAllReferentiel(Collection<Class<? extends ReferentialDto>> classes) { - selectedReferentiel.removeAll(classes); - firePropertyChange(PROPERTY_SELECTED_REFERENTIEL, selectedReferentiel); - } - - public void addAllReferentiel(Collection<Class<? extends ReferentialDto>> classes) { - selectedReferentiel.addAll(classes); - firePropertyChange(PROPERTY_SELECTED_REFERENTIEL, selectedReferentiel); - } - - public void setDatas(Map<ReferentialReference<ProgramDto>, List<DataReference>> datas) { - this.datas = datas; - - // on compte le count de marées totale - int nbTrips = 0; - if (datas != null) { - for (List<DataReference> marees : datas.values()) { - nbTrips += marees.size(); - } - } - this.nbTrips = nbTrips; - - if (log.isDebugEnabled()) { - log.debug("Nb program registred : " + (datas == null ? 0 : datas.size())); - log.debug("Nb trip registred : " + this.nbTrips); - } - firePropertyChange(PROPERTY_DATAS, datas); - } - - public void addSelectedData(AbstractReference referenceDto) { - - if (ProgramDto.class.isAssignableFrom(referenceDto.getType())) { - - // ajout de toutes les marées du program - - if (log.isDebugEnabled()) { - log.debug("Add all trips of program " + referenceDto.getId()); - } - getSelectedData().addAll(datas.get(referenceDto)); - - } else { - // ajout d'une marée - if (log.isDebugEnabled()) { - log.debug("Add Trip " + referenceDto.getId()); - } - getSelectedData().add((DataReference) referenceDto); - } - firePropertyChange(PROPERTY_SELECTED_DATA, selectedData); - } - - public void addAllSelectedData() { - if (log.isDebugEnabled()) { - log.debug("All all data."); - } - for (List<DataReference> p : datas.values()) { - getSelectedData().addAll(p); - } - firePropertyChange(PROPERTY_SELECTED_DATA, selectedData); - } - - public void removeSelectedData(AbstractReference referenceDto) { - - if (ProgramDto.class.isAssignableFrom(referenceDto.getType())) { - - // ajout de toutes les marées du program - - if (log.isDebugEnabled()) { - log.debug("Remove all marees of program " + referenceDto); - } - getSelectedData().removeAll(datas.get(referenceDto)); - } else { - - // ajout d'une marée - if (log.isDebugEnabled()) { - log.debug("Remove maree " + referenceDto); - } - getSelectedData().remove(referenceDto); - } - firePropertyChange(PROPERTY_SELECTED_DATA, selectedData); - } - - public void removeAllSelectedData() { - if (selectedData != null) { - selectedData.clear(); - } - firePropertyChange(PROPERTY_SELECTED_DATA, selectedData); - } - - public void addPropertyChangeListener(PropertyChangeListener listener) { - pcs.addPropertyChangeListener(listener); - } - - public void addPropertyChangeListener(String propertyName, - PropertyChangeListener listener) { - pcs.addPropertyChangeListener(propertyName, listener); - } - - public void removePropertyChangeListener(PropertyChangeListener listener) { - pcs.removePropertyChangeListener(listener); - } - - public void removePropertyChangeListener(String propertyName, - PropertyChangeListener listener) { - pcs.removePropertyChangeListener(propertyName, listener); - } - - protected void firePropertyChange(String propertyName, Object newValue) { - pcs.firePropertyChange(propertyName, null, newValue); - } - - protected void firePropertyChange(String propertyName, - Object oldValue, - Object newValue) { - pcs.firePropertyChange(propertyName, oldValue, newValue); - } - - protected void checkReferentielType(Class<?> type) { - if (!referentiel.contains(type)) { - throw new IllegalArgumentException( - "given <" + type + "> is not in referentiel universe : " + - referentiel); - } - } - - public void destroy() { - removeAll(); - // suppression de tous les listeners - PropertyChangeListener[] listeners = pcs.getPropertyChangeListeners(); - for (PropertyChangeListener l : listeners) { - removePropertyChangeListener(l); - } - } - - @Override - protected void finalize() throws Throwable { - super.finalize(); - destroy(); - } - - public List<DataReference> getDatas(String programId) { - Optional<ReferentialReference<ProgramDto>> programRefOptional = getDatas().keySet().stream().filter(ReferentialReference.newIdPredicate(programId)).findFirst(); - - List<DataReference> result; - - if (programRefOptional.isPresent()) { - - result = getDatas().get(programRefOptional.get()); - - } else { - - result = Collections.emptyList(); - - } - - return result; - } - - public void addData(ReferentialReference<ProgramDto> program, DataReference trip) { - if (!getDatas().containsKey(program)) { - getDatas().put(program, new ArrayList<>()); - } - getDatas(program.getId()).add(trip); - firePropertyChange(PROPERTY_DATAS, getDatas()); - } - - public Set<ReferentialReference<ProgramDto>> getPrograms() { - return getDatas().keySet(); - } - - public void removeTrip(ReferentialReference<ProgramDto> program, DataReference trip) { - List<DataReference> trips = getDatas(program.getId()); - trips.remove(trip); - if (trips.isEmpty()) { - getDatas().remove(program); - } - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/RolesTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/RolesTableModel.java deleted file mode 100644 index 0d320d8..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/RolesTableModel.java +++ /dev/null @@ -1,190 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.storage.tabs; - - -import com.google.common.collect.Lists; -import fr.ird.observe.services.dto.ObserveDbUserDto; -import fr.ird.observe.services.dto.ObserveDbUserDtos; -import fr.ird.observe.services.dto.constants.ObserveDbRole; - -import javax.swing.table.AbstractTableModel; -import java.util.Collections; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; - -/** - * Le modèle pour la tableau dans l'export GPS qui contient les activités et les - * points gps calculés via le fichier gps importé. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class RolesTableModel extends AbstractTableModel { - - private static final long serialVersionUID = 1L; - - public static final String[] COLUMN_NAMES = { - n("observe.security.role"), - n("observe.security.unused"), - n("observe.security.referentiel"), - n("observe.security.utilisateur"), - n("observe.security.technicien") - }; - - public static final String[] COLUMN_NAME_TIPS = { - n("observe.security.role.tip"), - n("observe.security.unused.tip"), - n("observe.security.referentiel.tip"), - n("observe.security.utilisateur.tip"), - n("observe.security.technicien.tip") - }; - - protected static final Class<?>[] COLUMN_CLASSES = { - String.class, - Boolean.class, - Boolean.class, - Boolean.class, - Boolean.class - }; - - protected SecurityModel model; - - protected List<ObserveDbUserDto> roles; - - public RolesTableModel() { - } - - @Override - public boolean isCellEditable(int rowIndex, int columnIndex) { - // seule la première colonne n'est pas éditable (on ne peut pas - // changer le lastName d'un role) - return columnIndex > 0; - } - - - /** - * Initialise le modèle. - * - * @param model le modèle de sécurité attaché - */ - public void init(SecurityModel model) { - - this.model = model; - this.roles = Lists.newArrayList(model.getUsersWithoutAdministrator()); - Collections.sort(this.roles, ObserveDbUserDtos.getUserDtoComparator()); - fireTableDataChanged(); - } - - public void clear() { - model = null; - roles = null; - fireTableDataChanged(); - } - - @Override - public int getRowCount() { - return roles == null ? 0 : roles.size(); - } - - @Override - public int getColumnCount() { - return COLUMN_CLASSES.length; - } - - @Override - public Object getValueAt(int rowIndex, int columnIndex) { - Object value = null; - - ObserveDbUserDto user = getUser(rowIndex); - if (user != null) { - - switch (columnIndex) { - case 0: - value = user.getName(); - break; - case 1: - value = ObserveDbRole.UNUSED.equals(user.getRole()); - break; - case 2: - value = ObserveDbRole.REFERENTIAL.equals(user.getRole()); - break; - case 3: - value = ObserveDbRole.USER.equals(user.getRole()); - break; - case 4: - value = ObserveDbRole.TECHNICAL.equals(user.getRole()); - break; - default: - throw new IllegalStateException( - "can not get value for row " + rowIndex + - ", col " + columnIndex); - } - } - return value; - } - - @Override - public void setValueAt(Object aValue, int rowIndex, int columnIndex) { - - if (columnIndex == 0) { - - // pas possible - return; - } - - Boolean value = (Boolean) aValue; - ObserveDbUserDto userDto = getUser(rowIndex); - - ObserveDbRole role; - - if (!value) { - role = null; - } else { - switch (columnIndex) { - case 2: - role = ObserveDbRole.REFERENTIAL; - break; - case 3: - role = ObserveDbRole.USER; - break; - case 4: - role = ObserveDbRole.TECHNICAL; - break; - default: - role = ObserveDbRole.UNUSED; - } - } - - model.setRole(userDto, role, true); - - // toute la ligne (sauf le role change) - fireTableRowsUpdated(rowIndex, rowIndex); - } - - protected ObserveDbUserDto getUser(int rowIndex) { - ObserveDbUserDto user = roles == null ? null : roles.get(rowIndex); - return user; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/RolesUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/RolesUI.jaxx deleted file mode 100644 index 1df8560..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/RolesUI.jaxx +++ /dev/null @@ -1,72 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<!-- *************************************** --> -<!-- L'écran de sauvegarde de la base locale --> -<!-- *************************************** --> - -<StorageTabUI> - - <import> - fr.ird.observe.ui.storage.tabs.SecurityModel - fr.ird.observe.ui.storage.StorageStep - fr.ird.observe.ui.storage.StorageUIModel - </import> - - <StorageStep id='step' initializer='StorageStep.ROLES'/> - - <StorageUIModel id='model'/> - - <SecurityModel id='securityModel' - initializer='model.getSecurityModel()'/> - - <!-- les roles récupérés depuis la base distante --> - <RolesTableModel id='rolesModel'/> - - <script><![CDATA[ - -@Override -public void init() { - getHandler().initUI(this); -} - -public String updateAdministrateur(String role) { - return t("observe.storage.security.administrateur", role); -} -]]> - </script> - - <JPanel id='content'> - - <!-- le lastName du role administrateur --> - <JPanel id='administrateurPanel' constraints='BorderLayout.NORTH'> - <JLabel id='administrateur' constraints='BorderLayout.NORTH'/> - </JPanel> - - <!-- la liste des roles --> - <JScrollPane id='rolesPane' constraints='BorderLayout.CENTER'> - <JTable id='roles'/> - </JScrollPane> - - </JPanel> - -</StorageTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/SecurityModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/SecurityModel.java deleted file mode 100644 index 5298392..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/SecurityModel.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.storage.tabs; - -import com.google.common.collect.Sets; -import fr.ird.observe.services.dto.ObserveDbUserDto; -import fr.ird.observe.services.dto.ObserveDbUserDtos; -import fr.ird.observe.services.dto.constants.ObserveDbRole; - -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.io.Serializable; -import java.util.Collection; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -/** - * Le modèle la sécurité à appliquer sur une base postgres - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class SecurityModel implements Serializable { - - public static final String PROPERTY_ADMINISTRATEUR = "administrateur"; - - public static final String PROPERTY_ROLE = "role"; - - public static final String PROPERTY_ASSIGNED = "assigned"; - - private static final long serialVersionUID = 1L; - - protected ObserveDbUserDto administrateur; - - protected final Set<ObserveDbUserDto> users; - - protected final PropertyChangeSupport pcs = new PropertyChangeSupport(this); - - public SecurityModel() { - users = Sets.newHashSet(); - } - - public ObserveDbUserDto getAdministrateur() { - return administrateur; - } - - public Set<ObserveDbUserDto> getUsersByRole(ObserveDbRole role) { - return users.stream() - .filter(ObserveDbUserDtos.newRolePredicate(role)) - .collect(Collectors.toSet()); - } - - public List<String> getUserNamesByRole(ObserveDbRole role) { - return users.stream() - .filter(ObserveDbUserDtos.newRolePredicate(role)) - .map(ObserveDbUserDtos.NAME_FUNCTION) - .collect(Collectors.toList()); - } - - public List<String> getDataUserNames() { - return getUserNamesByRole(ObserveDbRole.USER); - } - - public List<String> getReferentialUserNames() { - return getUserNamesByRole(ObserveDbRole.REFERENTIAL); - } - - public List<String> getTechnicalUserNames() { - return getUserNamesByRole(ObserveDbRole.TECHNICAL); - } - - public List<String> getUnusedUserNames() { - return getUserNamesByRole(ObserveDbRole.UNUSED); - } - - public Set<ObserveDbUserDto> getUsers() { - return Sets.newHashSet(users); - } - - public Set<ObserveDbUserDto> getUsersWithoutAdministrator() { - Predicate<ObserveDbUserDto> predicate = ObserveDbUserDtos.newRolePredicate(ObserveDbRole.ADMINISTRATOR); - return users.stream().filter(u -> !predicate.test(u)).collect(Collectors.toSet()); - } - - public boolean isRole(ObserveDbRole r, ObserveDbUserDto user) { - return r.equals(user.getRole()); - } - - public void init(Collection<ObserveDbUserDto> users) { - this.users.clear(); - this.users.addAll(users); - - Optional<ObserveDbUserDto> optionalAdministrator = users.stream().filter(ObserveDbUserDtos.newRolePredicate(ObserveDbRole.ADMINISTRATOR)).findFirst(); - if (optionalAdministrator.isPresent()) { - this.administrateur = optionalAdministrator.get(); - } else { - throw new IllegalStateException("No administrator found"); - } - firePropertyChange(PROPERTY_ROLE, null, getUsers()); - firePropertyChange(PROPERTY_ADMINISTRATEUR, null, getAdministrateur()); - firePropertyChange(PROPERTY_ASSIGNED, null, getAssigned()); - } - - public void setRole(ObserveDbUserDto user, ObserveDbRole role, boolean fire) { - user.setRole(role); - if (fire) { - if (role != null) { - firePropertyChange(role.name(), null, getUsersByRole(role)); - } - firePropertyChange(PROPERTY_ASSIGNED, null, getAssigned()); - } - } - - public void setRole(Iterable<ObserveDbUserDto> users, ObserveDbRole role) { - for (ObserveDbUserDto user : users) { - setRole(user, role, false); - } - firePropertyChange(role.name(), null, getUsersByRole(role)); - firePropertyChange(PROPERTY_ASSIGNED, null, getAssigned()); - } - - public int getAssigned() { - int countNotAssigned = (int) users.stream().filter(ObserveDbUserDtos.newRolePredicate(null)).count(); - int count = users.size() - countNotAssigned; - return count; - } - - public void addPropertyChangeListener(PropertyChangeListener listener) { - pcs.addPropertyChangeListener(listener); - } - - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { - pcs.addPropertyChangeListener(propertyName, listener); - } - - public void removePropertyChangeListener(PropertyChangeListener listener) { - pcs.removePropertyChangeListener(listener); - } - - public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { - pcs.removePropertyChangeListener(propertyName, listener); - } - - protected void firePropertyChange(String propertyName, Object oldValue, Object newValue) { - pcs.firePropertyChange(propertyName, oldValue, newValue); - } - - protected void firePropertyChange(String propertyName, Object newValue) { - firePropertyChange(propertyName, null, newValue); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/SelectDataUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/SelectDataUI.jaxx deleted file mode 100644 index 02679ae..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/SelectDataUI.jaxx +++ /dev/null @@ -1,65 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<!-- *******************************************--> -<!-- L'écran de sélection des données à traiter --> -<!-- *******************************************--> - -<StorageTabUI> - - <import> - fr.ird.observe.db.ObserveSwingDataSource - fr.ird.observe.ui.storage.StorageStep - fr.ird.observe.ui.tree.DataSelectionTreeSelectionModel - fr.ird.observe.ui.tree.DataSelectionTreeCellRenderer - </import> - - <StorageStep id='step' initializer='StorageStep.SELECT_DATA'/> - - <fr.ird.observe.ui.storage.StorageUIModel id='model'/> - - <DataSelectionTreeSelectionModel id='selectionModel'/> - - <script><![CDATA[ -@Override -public void init() { - getHandler().initUI(this); -} - -public void initTree(ObserveSwingDataSource dataSource) { - getHandler().initTree(this, dataSource); -} -]]> - </script> - - <JPanel id='content'> - - <JScrollPane id='selectedTreePane' constraints='BorderLayout.CENTER'> - - <!-- arbre de selection des exports --> - <JTree id='selectTree'/> - - </JScrollPane> - </JPanel> - - -</StorageTabUI> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/StorageTabUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/StorageTabUI.jaxx deleted file mode 100644 index d3b5799..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/StorageTabUI.jaxx +++ /dev/null @@ -1,96 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<!-- **************************** --> -<!-- La base des contenu d'onglet --> -<!-- **************************** --> - -<JPanel id="tabPanel" - abstract='true' - implements='jaxx.runtime.swing.wizard.WizardStepUI<StorageStep, StorageUIModel>'> - - <import> - fr.ird.observe.ui.UIHelper - fr.ird.observe.ui.storage.StorageStep - fr.ird.observe.ui.storage.StorageUIModel - - java.awt.Color - - javax.swing.JLabel - javax.swing.border.LineBorder - - static org.nuiton.i18n.I18n.t - static org.nuiton.i18n.I18n.n - </import> - - <StorageTabUIHandler id='handler'/> - - <StorageUIModel id='model' - initializer='getContextValue(StorageUIModel.class)'/> - - <script><![CDATA[ - -public abstract StorageStep getStep(); - -public abstract void init(); - -public void destroy() { - description.setText(""); - UIHelper.destroy(this); -} - -@Override -protected void finalize() throws Throwable { - super.finalize(); - destroy(); -} - -protected void setDescriptionText(String text) { - description.setText(text); -} - -protected String getProgressString(int currentStep, int nbStep) { - StorageStep step = getStep(); - String txt = ""; - if (step != null) { - txt = n("observe.storage.step.label"); - txt = t(txt, currentStep + 1, nbStep, t(step.getLabel())); - } - return txt; -} -]]> - </script> - - <!-- titre --> - <JPanel layout='{new BorderLayout()}' constraints='BorderLayout.NORTH'> - <JProgressBar id='progress' constraints='BorderLayout.CENTER'/> - </JPanel> - - <!-- content --> - <JPanel id='content' constraints='BorderLayout.CENTER'/> - - <!-- description --> - <JScrollPane id="descriptionPane" constraints='BorderLayout.SOUTH'> - <JTextArea id='description'/> - </JScrollPane> - -</JPanel> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/StorageTabUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/StorageTabUIHandler.java deleted file mode 100644 index 5321444..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/storage/tabs/StorageTabUIHandler.java +++ /dev/null @@ -1,491 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.storage.tabs; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.ObserveTextGenerator; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.db.constants.ConnexionStatus; -import fr.ird.observe.db.constants.CreationMode; -import fr.ird.observe.db.constants.DbMode; -import fr.ird.observe.services.configuration.ObserveDataSourceInformation; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.storage.StorageStep; -import fr.ird.observe.ui.storage.StorageUILauncher; -import fr.ird.observe.ui.storage.StorageUIModel; -import fr.ird.observe.ui.tree.DataSelectionTreeSelectionModel; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import jaxx.runtime.swing.editor.MyDefaultCellEditor; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.Icon; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JRadioButton; -import javax.swing.JTable; -import javax.swing.JTree; -import javax.swing.table.DefaultTableCellRenderer; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Window; -import java.beans.PropertyChangeListener; -import java.io.File; -import java.util.Date; - -import static org.nuiton.i18n.I18n.t; - -/** - * Le controleur comun à tous les onglets. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class StorageTabUIHandler { - - private static final Log log = LogFactory.getLog(StorageTabUIHandler.class); - - public boolean updateCreationModeLayout(ChooseDbModeUI ui, - boolean visible, - JRadioButton button) { - JPanel panel = ui.getUseCreateMode(); - if (visible) { - for (Component c : panel.getComponents()) { - if (button.equals(c)) { - // button already in - return true; - } - } - - panel.add(button); - } else { - for (Component c : panel.getComponents()) { - if (button.equals(c)) { - // button still in - panel.remove(c); - return false; - } - } - } - return visible; - } - - public void initUI(final ChooseDbModeUI ui) { - - PropertyChangeListener listener = evt -> { - StorageUIModel model = (StorageUIModel) evt.getSource(); - - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ObserveTextGenerator textGenerator = applicationContext.getTextGenerator(); - String txt = textGenerator.getLoadDataSourceResume(model); - ui.getResume().setText(txt); - }; - StorageUIModel model = ui.getModel(); - model.addPropertyChangeListener(StorageUIModel.DB_MODE_PROPERTY_NAME, listener); - model.addPropertyChangeListener(StorageUIModel.CREATION_MODE_PROPERTY_NAME, listener); - ui.setDescriptionText(t(ui.getStep().getDescription())); - } - - public void initUI(final ConfigUI ui) { - - PropertyChangeListener listener = evt -> { - StorageUIModel model = (StorageUIModel) evt.getSource(); - String propertyName = evt.getPropertyName(); - if (StorageUIModel.CREATION_MODE_PROPERTY_NAME.equals(propertyName) || - StorageUIModel.DB_MODE_PROPERTY_NAME.equals(propertyName)) { - String id = null; - if (model.getDbMode() == DbMode.USE_REMOTE) { - id = DbMode.USE_REMOTE.name(); - } else if (model.getDbMode() == DbMode.USE_SERVER) { - id = DbMode.USE_SERVER.name(); - } else { - if (model.getCreationMode() != null) { - id = model.getCreationMode().name(); - } - } - if (id != null) { - refreshConfig(ui, id); - } - } - }; - ui.getModel().addPropertyChangeListener(listener); - } - - public void initUI(final ConfigReferentielUI ui) { - if (ui.getStep() != null) { - ui.setDescriptionText(t(ui.getStep().getDescription())); - - PropertyChangeListener listener = evt -> { - String propertyName = evt.getPropertyName(); - if (StorageUIModel.REFERENTIEL_IMPORT_MODE_PROPERTY_NAME.equals(propertyName)) { - CreationMode id = (CreationMode) evt.getNewValue(); - refreshConfig(ui, id.name()); - } - }; - ui.getModel().addPropertyChangeListener(listener); - ui.getModel().setReferentielImportMode(CreationMode.IMPORT_EXTERNAL_DUMP); - } - } - - public void initUI(final ConfigDataUI ui) { - if (ui.getStep() != null) { - ui.setDescriptionText(t(ui.getStep().getDescription())); - - PropertyChangeListener listener = evt -> { - String propertyName = evt.getPropertyName(); - if (StorageUIModel.DATA_IMPORT_MODE_PROPERTY_NAME.equals(propertyName)) { - CreationMode id = (CreationMode) evt.getNewValue(); - - if (id != null) { - refreshConfig(ui, id.name()); - - } - - } - }; - ui.getModel().addPropertyChangeListener(listener); - ui.getModel().setDataImportMode(CreationMode.EMPTY); - } - } - - public void initUI(final RolesUI ui) { - if (ui.getStep() != null) { - ui.setDescriptionText(t(ui.getStep().getDescription())); - } - - ui.getSecurityModel().addPropertyChangeListener(evt -> { - if (log.isDebugEnabled()) { - log.debug("Security model changed [" + evt.getPropertyName() + "] <" + evt.getOldValue() + " : " + evt.getNewValue() + ">"); - } - ui.getModel().validate(); - }); - - JTable table = ui.getRoles(); - table.setRowHeight(24); - - UIHelper.fixTableColumnWidth(table, 1, 100); - UIHelper.fixTableColumnWidth(table, 2, 100); - UIHelper.fixTableColumnWidth(table, 3, 100); - UIHelper.fixTableColumnWidth(table, 4, 100); - - DefaultTableCellRenderer renderer = new DefaultTableCellRenderer(); - - UIHelper.setI18nTableHeaderRenderer( - table, - RolesTableModel.COLUMN_NAMES[0], - RolesTableModel.COLUMN_NAME_TIPS[0], - RolesTableModel.COLUMN_NAMES[1], - RolesTableModel.COLUMN_NAME_TIPS[1], - RolesTableModel.COLUMN_NAMES[2], - RolesTableModel.COLUMN_NAME_TIPS[2], - RolesTableModel.COLUMN_NAMES[3], - RolesTableModel.COLUMN_NAME_TIPS[3], - RolesTableModel.COLUMN_NAMES[4], - RolesTableModel.COLUMN_NAME_TIPS[4] - ); - - UIHelper.setTableColumnRenderer(table, 0, UIHelper.newStringTableCellRenderer(renderer, 50, true)); - UIHelper.setTableColumnRenderer(table, 1, UIHelper.newBooleanTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 2, UIHelper.newBooleanTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 3, UIHelper.newBooleanTableCellRenderer(renderer)); - UIHelper.setTableColumnRenderer(table, 4, UIHelper.newBooleanTableCellRenderer(renderer)); - - UIHelper.setTableColumnEditor(table, 1, MyDefaultCellEditor.newBooleanEditor()); - UIHelper.setTableColumnEditor(table, 2, MyDefaultCellEditor.newBooleanEditor()); - UIHelper.setTableColumnEditor(table, 3, MyDefaultCellEditor.newBooleanEditor()); - UIHelper.setTableColumnEditor(table, 4, MyDefaultCellEditor.newBooleanEditor()); - - } - - public void initUI(SelectDataUI ui) { - if (ui.getStep() != null) { - ui.setDescriptionText(t(ui.getStep().getDescription())); - } - - // customize tree selection colors - UIHelper.initUI(ui.getSelectedTreePane(), ui.getSelectTree()); - } - - public void initUI(BackupUI ui) { - if (ui.getStep() != null) { - ui.setDescriptionText(t(ui.getStep().getDescription())); - } - } - - public void initUI(ConfirmUI ui) { - if (ui.getStep() != null) { - ui.setDescriptionText(t(ui.getStep().getDescription())); - } - } - - public void chooseBackupFile(BackupUI ui) { - File f = UIHelper.chooseDirectory( - ui, - t("observe.title.choose.db.dump.directory"), - t("observe.action.choose.db.dump.directory"), - new File(ui.getDirectoryText().getText()) - ); - changeDirectory(ui, f); - } - - public void changeDirectory(BackupUI ui, File f) { - ui.getModel().setBackupFile(new File(f, ui.getFilenameText().getText())); - } - - public void changeFilename(BackupUI ui, String filename) { - ui.getModel().setBackupFile(new File(ui.getDirectoryText().getText(), filename)); - } - - public void refreshConfig(ConfigUI ui, String configId) { - JComponent c = (JComponent) ui.getObjectById(configId); - if (c != null) { - if (log.isDebugEnabled()) { - log.debug(configId); - } - ui.configLayout.show(ui.configContent, configId); - String text = (String) c.getClientProperty("description"); - ui.setDescriptionText(t(text)); - if (c.equals(ui.IMPORT_REMOTE_STORAGE)) { - ui.IMPORT_REMOTE_STORAGE_content.add(ui.remoteConfig, BorderLayout.CENTER); - } else if (c.equals(ui.IMPORT_SERVER_STORAGE)) { - ui.IMPORT_SERVER_STORAGE_content.add(ui.remoteConfig, BorderLayout.CENTER); - } else if (c.equals(ui.USE_REMOTE)) { - ui.USE_REMOTE_content.add(ui.remoteConfig, BorderLayout.CENTER); - } else if (c.equals(ui.USE_SERVER)) { - ui.USE_SERVER_content.add(ui.remoteConfig, BorderLayout.CENTER); - } - } - } - - public void refreshConfig(ConfigReferentielUI ui, String configId) { - JComponent c = (JComponent) ui.getObjectById(configId); - if (c != null) { - if (log.isDebugEnabled()) { - log.debug(configId); - } - ui.configLayout.show(ui.configContent, configId); - } - } - - public void refreshConfig(ConfigDataUI ui, String configId) { - JComponent c = (JComponent) ui.getObjectById(configId); - if (c != null) { - if (log.isDebugEnabled()) { - log.debug(configId); - } - ui.configLayout.show(ui.configContent, configId); - } - } - - public Icon updateConnexionStatutIcon(ConfigUI ui, ConnexionStatus status) { - Icon icon = (Icon) ui.getConnexionStatus().getClientProperty(status.name().toLowerCase() + "Icon"); - return icon; - } - - public Color updateConnexionStatutColor(ConfigUI ui, ConnexionStatus status) { - Color color = (Color) ui.getConnexionStatus().getClientProperty(status.name().toLowerCase() + "Color"); - return color; - } - - public String updateConnexionStatutText(ConfigUI ui, ConnexionStatus status) { - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ObserveTextGenerator textGenerator = applicationContext.getTextGenerator(); - String text = textGenerator.getConnexionTestResultMessage(ui.getModel()); - return text; - } - - public void chooseDumpFile(ConfigUI ui) { - File f = UIHelper.chooseFile( - ui, - t("observe.title.choose.db.dump"), - t("observe.action.choose.db.dump"), - ui.getModel().getDumpFile(), - "^.+\\.sql\\.gz$", - t("observe.action.choose.db.dump.description")); - ui.getModel().setDumpFile(f); - } - - public void chooseDumpFile(ConfigReferentielUI ui) { - File f = UIHelper.chooseFile( - ui, - t("observe.title.choose.db.dump"), - t("observe.action.choose.db.dump"), - ui.getModel().getDumpFile(), - "^.+\\.sql\\.gz$", - t("observe.action.choose.db.dump.description")); - ui.getCentralSourceModel().setDumpFile(f); - ui.getModel().validate(); - } - - public void chooseDumpFile(ConfigDataUI ui) { - File f = UIHelper.chooseFile( - ui, - t("observe.title.choose.db.dump"), - t("observe.action.choose.db.dump"), - ui.getModel().getDumpFile(), - "^.+\\.sql\\.gz$", - t("observe.action.choose.db.dump.description")); - ui.getCentralSourceModel().setDumpFile(f); - ui.getModel().validate(); - } - -// public void chooseSslCertificatFile(ConfigUI ui) { -// File f = UIHelper.chooseFile( -// ui, -// t("observe.title.choose.ssl.cert"), -// t("observe.action.choose.ssl.cert"), -// ui.getModel().getSslCertificatFile(), -// "^.+\\.jks$", -// t("observe.action.choose.ssl.cert.description")); -// ui.getModel().setSslCertificatFile(f); -// } - - public void initTree(SelectDataUI ui, ObserveSwingDataSource source) { - StorageUIModel model = ui.getModel(); - if (model.isUseSelectData()) { - - DataSelectionModel dataModel = model.getSelectDataModel(); - ObserveTreeHelper helper = new ObserveTreeHelper(); - JTree tree = ui.selectTree; - helper.setUI(tree, false, null); - - tree.setModel(helper.createModel(ui, dataModel, source)); - DataSelectionTreeSelectionModel selectionModel = - ui.getSelectionModel(); - selectionModel.initUI(tree); - selectionModel.setDataModel(dataModel); - } - } - - protected String updateInternalDumpModeLabel(ChooseDbModeUI ui, - boolean dumpExist) { - File f = ObserveSwingApplicationContext.get().getConfig().getInitialDbDump(); - String text; - if (f.exists()) { - text = t("observe.storage.internalDump.last.modified", new Date(f.lastModified())); - } else { - text = t("observe.storage.internalDump.not.exist"); - } - return t(CreationMode.IMPORT_INTERNAL_DUMP.getLabel()) + text; - } - - protected String updateCanMigrateLabel(ChooseDbModeUI ui, - boolean canMigrate) { - String text = t("observe.storage.action.canMigrate", ui.getModel().getModelVersion()); - return text; - } - - public void obtainRemoteConnexion(ConfigReferentielUI ui) { - StorageUIModel sourceModel = ui.getCentralSourceModel(); - StorageUILauncher.obtainRemoteConnexion( - ui.getDelegateContext(), - ui.getParentContainer(Window.class), - sourceModel - ); - - sourceModel.validate(StorageStep.CONFIG); - - ui.getModel().validate(); - } - - public void obtainServerConnexion(ConfigReferentielUI ui) { - StorageUIModel sourceModel = ui.getCentralSourceModel(); - StorageUILauncher.obtainServerConnexion( - ui.getDelegateContext(), - ui.getParentContainer(Window.class), - sourceModel - ); - - sourceModel.validate(StorageStep.CONFIG); - - ui.getModel().validate(); - } - - public void obtainRemoteConnexion(ConfigDataUI ui) { - StorageUIModel sourceModel = ui.getCentralSourceModel(); - StorageUILauncher.obtainRemoteConnexion( - ui.getDelegateContext(), - ui.getParentContainer(Window.class), - sourceModel - ); - - sourceModel.validate(StorageStep.CONFIG); - - ui.getModel().validate(); - } - - - public void obtainServerConnexion(ConfigDataUI ui) { - StorageUIModel sourceModel = ui.getCentralSourceModel(); - StorageUILauncher.obtainServerConnexion( - ui.getDelegateContext(), - ui.getParentContainer(Window.class), - sourceModel - ); - - sourceModel.validate(StorageStep.CONFIG); - - ui.getModel().validate(); - } - - public String updateStorageLabel(StorageUIModel service, - boolean serviceValid, - JLabel label, - boolean remote) { - String text; - if (serviceValid && remote == service.isRemote()) { - - // on recupere le label du service - text = service.getLabel(); - } else { - - // aucun service configuré - text = t((String) label.getClientProperty("no")); - } - return text; - } - - protected String updateDataSourcePolicy(StorageUIModel sourceModel, - boolean valid, - boolean remote) { - String text = null; - if (valid && remote == sourceModel.isRemote()) { - ObserveDataSourceInformation dataSourceInformation = sourceModel.getDataSourceInformation(); - - if (dataSourceInformation != null) { - - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ObserveTextGenerator textGenerator = applicationContext.getTextGenerator(); - text = textGenerator.getDataSourcePolicy(dataSourceInformation); - } - - } else { - - text = t("observe.common.storage.not.valid"); - - } - - return text; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/AbstractObserveTreeCellRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/AbstractObserveTreeCellRenderer.java deleted file mode 100644 index a265191..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/AbstractObserveTreeCellRenderer.java +++ /dev/null @@ -1,432 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.tree; - -import com.google.common.base.Preconditions; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.OpenableDto; -import fr.ird.observe.services.dto.longline.ActivityLonglineDto; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.ui.content.impl.seine.FloatingObjectUI; -import fr.ird.observe.ui.content.impl.seine.SetSeineUI; -import fr.ird.observe.ui.content.open.impl.longline.ActivityLonglineUI; -import fr.ird.observe.ui.content.open.impl.longline.TripLonglineUI; -import fr.ird.observe.ui.content.open.impl.seine.ActivitySeineUI; -import fr.ird.observe.ui.content.open.impl.seine.RouteUI; -import fr.ird.observe.ui.content.open.impl.seine.TripSeineUI; -import jaxx.runtime.swing.nav.tree.AbstractNavTreeCellRenderer; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.decorator.Decorator; - -import javax.swing.Icon; -import javax.swing.UIManager; -import javax.swing.tree.DefaultTreeModel; -import java.awt.Color; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -import static org.nuiton.i18n.I18n.t; - -/** - * Le renderer abstrait (qui a toutes les methodes qui aident) pour implanter de - * vrai renderer pour les différents cas d'utilisation de l'abre de navigation. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.2 - */ -public abstract class AbstractObserveTreeCellRenderer extends AbstractNavTreeCellRenderer<DefaultTreeModel, ObserveNode> { - - /** Logger */ - protected static final Log log = - LogFactory.getLog(AbstractObserveTreeCellRenderer.class); - - /** la liste des ui qui peuvent être en mode création */ - public static final List<Class<?>> CREATION_UI = - Collections.unmodifiableList( - Arrays.<Class<?>>asList( - TripSeineUI.class, - RouteUI.class, - ActivitySeineUI.class, - FloatingObjectUI.class, - SetSeineUI.class, - TripLonglineUI.class, - ActivityLonglineUI.class) - ); - - private static final long serialVersionUID = 1L; - - /** la couleur des noeuds fermés */ - protected Color closeColor; - - /** la couleur des noeuds de données ouverts */ - protected Color openColor; - - /** la couleur pour indiquer que la données est non valide ou non sauvée */ - protected Color redColor; - - /** service de décoration */ - protected transient DecoratorService decoratorService; - - public DecoratorService getDecoratorService() { - if (decoratorService == null) { - - // on récupère le service commun - decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); - } - return decoratorService; - } - - @Override - public ObserveDataProvider getDataProvider() { - ObserveDataProvider provider = (ObserveDataProvider) - super.getDataProvider(); - if (provider == null) { - ObserveSwingDataSource source = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); - if (source != null) { - provider = new ObserveDataProvider(source); - setDataProvider(provider); - } - } - return provider; - } - - public AbstractObserveTreeCellRenderer() { - init(); - } - - protected void init() { - closeColor = Color.LIGHT_GRAY; - openColor = getForeground(); - redColor = Color.RED; - } - - /** - * Positionne dans le renderer delege l'icone a utiliser. - * - * @param node le noeud passé au renderer - */ - public void setIcon(ObserveNode node) { - Icon icon = getNavigationIcon(node); - setDefaultIcons(icon); - } - - /** - * Récupère l'icon adequate pour le noeud donnes. - * - * @param node le noeud passé au renderer - * @return l'icone du noeud (ou null si non trouve) - */ - public Icon getNavigationIcon(ObserveNode node) { - Icon icon = getNavigationIcon(node, null); - return icon; - - } - - @Override - public Color getBackgroundSelectionColor() { - return null; - } - - @Override - public Color getBackgroundNonSelectionColor() { - // Fixes http://forge.codelutin.com/issues/830 for jdk 7 - return Color.WHITE; - } - - /** - * Récupère l'icon adequate pour le noeud donnes. - * - * @param node le noeud passé au renderer - * @param suffix un suffix a ajouter a la clef qui identifie l'icone - * @return l'icone du noeud (ou null si non trouve) - */ - public Icon getNavigationIcon(ObserveNode node, String suffix) { - if (node == null || node.isRoot()) { - return null; - } - if (suffix == null) { - suffix = ""; - } - - Icon icon; - - if (node.isReferentielNode()) { - - // referentiel root node - - if (node.isStringNode()) { - icon = UIManager.getIcon("navigation.referentiel" + suffix); - } else { - icon = UIManager.getIcon("navigation.sub.referentiel" + suffix); - } - return icon; - } - - if (!node.isStringNode()) { - - // on est sur un noeud de donnees, rien a calculer - String path = "navigation." + node.getInternalClass().getName() + suffix; - icon = UIManager.getIcon(path); - return icon; - } - - // dernier cas, on est sur un noeud intermediaire sans donnee - // on doit se baser sur le container node - - ObserveNode containerNode = node.getContainerNode(); - - Class<?> containerClass = containerNode.getInternalClass(); - String path; - if (TripSeineDto.class.equals(containerClass)) { - // remonte sur une maree : donc routes - path = RouteDto.class.getName(); - } else if (TripLonglineDto.class.equals(containerClass)) { - // remonte sur une maree : donc activités - path = ActivityLonglineDto.class.getName(); - } else if (RouteDto.class.equals(containerClass)) { - // remonte sur une route : donc activitys - path = ActivitySeineDto.class.getName(); - } -// else if (ActivitySeine.class.equals(containerClass)) { -// // remonte sur une activity : donc observedSystem -// path = ObservedSystemDto.class.getName(); -// } - else { - // dans le cas d'un sub, il n'y a pas de suffixe possible - suffix = ""; - path = containerClass.getName() + ".sub"; - } - icon = UIManager.getIcon("navigation." + path + suffix); - return icon; - } - - public void setDefaultIcons(Icon icon) { - if (icon == null) { - // the icon is not customized for this node - setOpenIcon(getDefaultOpenIcon()); - setClosedIcon(getDefaultClosedIcon()); - setLeafIcon(getDefaultLeafIcon()); - } else { - // replace all possible icons for this node - setOpenIcon(icon); - setClosedIcon(icon); - setLeafIcon(icon); - } - } - - protected String computeNodeText(ObserveNode node) { - - if (node.isStringNode()) { - String text = t(node.getId()); - return text; - } - - Class<?> beanType = node.getInternalClass(); - - if (node.isReferentielNode()) { - - String text = t(DecoratorService.getEntityLabel(ObserveTreeHelper.TREE_NODE_PREFIX, beanType)); - return text; - } - - // noeud de donnée - - String id = node.getId(); - - if (id == null) { - - // noeud d'un objet en cours de création - - String text = t(node.getContext()); - return text; - } - - // noeud de donnée connue en base - - if (getDataProvider() == null) { - // data provider non utilisable - String text = "No data provider opened to render " + id; - return text; - } - - if (node instanceof SetLonglineNode) { - String text = t("observe.tree.setLongline"); - return text; - } - - if (node instanceof SetSeineNode) { - String text = t("observe.tree.setSeine"); - return text; - } - - if (node instanceof DataReferenceNodeSupport) { - DataReferenceNodeSupport<?> entityNodeSupport = (DataReferenceNodeSupport) node; - - DataReference entity = entityNodeSupport.getEntity(); - - Preconditions.checkNotNull(entity, "L'entité doit être chargée dans le noeud: " + node); - - Decorator<?> decorator = getDecoratorService().getDataReferenceDecorator((Class) beanType); - String text = decorator.toString(entity); - - return text; - } - - if (node instanceof ReferentialReferenceNodeSupport) { - ReferentialReferenceNodeSupport<?> entityNodeSupport = (ReferentialReferenceNodeSupport) node; - - ReferentialReference entity = entityNodeSupport.getEntity(); - - Preconditions.checkNotNull(entity, "L'entité doit être chargée dans le noeud: " + node); - - Decorator<?> decorator = getDecoratorService().getReferentialReferenceDecorator((Class) beanType); - String text = decorator.toString(entity); - - return text; - } - - throw new IllegalStateException("Don't know how to render node: " + node); - - } - - public Color getNavigationTextColor(ObserveNode node) { - - if (node == null) { - return openColor; - } - - if (node.isRoot() || node.isReferentielNode()) { - return openColor; - } - - // le noeud pointe sur un objet ouvert - - Class<?> contentClass = node.getInternalClass(); - ObserveNode parentNode = node.getParent(); - Class<?> parentContentClass = parentNode == null ? null : parentNode.getInternalClass(); - - if (log.isTraceEnabled()) { - log.trace("[" + node + "] Content class to use : " + contentClass); - log.trace("[" + node + "] Parent Content class to use : " + parentContentClass); - } - DataContext dataContext = ObserveSwingApplicationContext.get().getDataContext(); - String nodeId = node.getId(); - - if (ProgramDto.class.equals(contentClass)) { - - // on grise le program si aucune marée ouverte sur ce programme - String p = dataContext.getOpenProgramId(); - if (p != null && p.equals(nodeId)) { - return openColor; - } - return closeColor; - } - - boolean nodeIsOpen = isOpenNode(node); - - if (!nodeIsOpen) { - if (log.isDebugEnabled()) { - log.debug("[" + node + "] is not open, use closeColor"); - } - // l'objet pointé n'est pas ouvert - return closeColor; - } - - if (CREATION_UI.contains(contentClass)) { - - // un noeud de creation - if (nodeId == null) { - // mode creation - return redColor; - } - return openColor; - } - - return openColor; - } - - public boolean isOpenNode(ObserveNode node) { - - if (node.isRoot() || node.isReferentielNode()) { - return false; - } - - boolean nodeIsOpen = false; - - ObserveNode openableNode; - openableNode = getFirstOpenableNode(node); - if (log.isDebugEnabled()) { - log.debug("openable node " + - Arrays.toString(openableNode.getPath()) + " for " + - Arrays.toString(node.getPath())); - } - if (openableNode != null) { - Boolean open = openableNode.isOpen(); - nodeIsOpen = open != null && open; - } - - return nodeIsOpen; - } - - /** - * @param value the value which should be a node - * @return the cast {@link ObserveNode}, or {@code null} if - * value is null. - */ - public static ObserveNode getNode(Object value) { - ObserveNode node = null; - if (value instanceof ObserveNode) { - node = (ObserveNode) value; - } - return node; - } - - public ObserveNode getFirstOpenableNode(ObserveNode node) { - - if (OpenableDto.class.isAssignableFrom(node.getInternalClass())) { - return node; - } - - if (ProgramDto.class.isAssignableFrom(node.getInternalClass())) { - return node; - } - - // this is not a openable node, go to parent node - ObserveNode parentNode = node.getParent(); - if (parentNode != null) { - return getFirstOpenableNode(parentNode); - } - return null; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/AbstrctReferenceNodeSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/AbstrctReferenceNodeSupport.java deleted file mode 100644 index 9a6b94f..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/AbstrctReferenceNodeSupport.java +++ /dev/null @@ -1,115 +0,0 @@ -package fr.ird.observe.ui.tree; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.AbstractReference; -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.ui.tree.loadors.AbstractNodeChildLoador; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Created on 4/9/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 4.0 - */ -public abstract class AbstrctReferenceNodeSupport<E extends IdDto, R extends AbstractReference<E>> extends ObserveNode { - - /** Logger. */ - private static final Log log = LogFactory.getLog(AbstrctReferenceNodeSupport.class); - - private static final long serialVersionUID = 1L; - - /** - * Pour cacher l'entité attachée au noeud. - * Elle pourra être directement injectée pour éviter de la recharger (lors de la création d'un modèle initiale). - * - * @since 4.0 - */ - protected transient R entity; - - protected boolean reloadEntity; - - protected abstract R fetchEntity(); - - protected AbstrctReferenceNodeSupport(Class<E> internalClass, R entity) { - this(internalClass, entity, null); - } - - protected AbstrctReferenceNodeSupport(Class<E> type, R entity, AbstractNodeChildLoador<?, ?> childLoador) { - this(type, entity, null, childLoador); - } - - protected AbstrctReferenceNodeSupport(Class<E> type, R entity, String context, AbstractNodeChildLoador<?, ?> childLoador) { - super(type, entity.getId(), context, childLoador, false); - setEntity(entity); - } - - @Override - public void setDirty(boolean dirty) { - super.setDirty(dirty); - - if (dirty && reloadEntity) { - entity = null; - } - - } - - public R getEntity() { - return entity; - } - - public void setEntity(R entity) { - this.entity = entity; - } - - - protected void loadEntity(ObserveDataProvider oProvider) { - - //FIXME -// if (oProvider.getSelectionModel() != null) { -// -// if (log.isDebugEnabled()) { -// log.debug("try to get entity from selectionModel " + internalClass + " : " + id); -// } -// entity = (ReferenceDto<E>) oProvider.getSelectionModel().getEntityCache(id); -// } - - if (entity == null) { - - if (log.isInfoEnabled()) { - log.info("will load entity " + internalClass.getSimpleName() + " : " + id); - } - - entity = fetchEntity(); - - } - - } - - public void setReloadEntity(boolean reloadEntity) { - this.reloadEntity = reloadEntity; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ActivityLonglineNode.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ActivityLonglineNode.java deleted file mode 100644 index 434a5c6..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ActivityLonglineNode.java +++ /dev/null @@ -1,52 +0,0 @@ -package fr.ird.observe.ui.tree; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.longline.ActivityLonglineDto; -import fr.ird.observe.services.service.longline.ActivityLonglineService; -import fr.ird.observe.ui.tree.loadors.ActivityLonglineNodeChildLoador; - -/** - * Created on 4/9/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 4.0 - */ -public class ActivityLonglineNode extends DataReferenceNodeSupport<ActivityLonglineDto> { - - private static final long serialVersionUID = 1L; - - public ActivityLonglineNode(DataReference<ActivityLonglineDto> entity) { - super(ActivityLonglineDto.class, entity, ObserveTreeHelper.getChildLoador(ActivityLonglineNodeChildLoador.class)); - } - - @Override - protected DataReference<ActivityLonglineDto> fetchEntity() { - ActivityLonglineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivityLonglineService(); - DataReference<ActivityLonglineDto> referenceDto = service.loadReferenceToRead(getId()); - return referenceDto; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ActivitySeineNode.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ActivitySeineNode.java deleted file mode 100644 index b1d4d7a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ActivitySeineNode.java +++ /dev/null @@ -1,52 +0,0 @@ -package fr.ird.observe.ui.tree; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.services.service.seine.ActivitySeineService; -import fr.ird.observe.ui.tree.loadors.ActivitySeineNodeChildLoador; - -/** - * Created on 4/9/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 4.0 - */ -public class ActivitySeineNode extends DataReferenceNodeSupport<ActivitySeineDto> { - - private static final long serialVersionUID = 1L; - - public ActivitySeineNode(DataReference<ActivitySeineDto> entity) { - super(ActivitySeineDto.class, entity, ObserveTreeHelper.getChildLoador(ActivitySeineNodeChildLoador.class)); - } - - @Override - protected DataReference<ActivitySeineDto> fetchEntity() { - ActivitySeineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivitySeineService(); - DataReference<ActivitySeineDto> referenceDto = service.loadReferenceToRead(getId()); - return referenceDto; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/DataReferenceNodeSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/DataReferenceNodeSupport.java deleted file mode 100644 index a9aec72..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/DataReferenceNodeSupport.java +++ /dev/null @@ -1,97 +0,0 @@ -package fr.ird.observe.ui.tree; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveOpenDataManager; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.DataDto; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.OpenableDto; -import fr.ird.observe.ui.tree.loadors.AbstractNodeChildLoador; -import jaxx.runtime.swing.nav.NavBridge; -import jaxx.runtime.swing.nav.NavDataProvider; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.tree.DefaultTreeModel; - -/** - * Created on 4/9/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 4.0 - */ -public abstract class DataReferenceNodeSupport<E extends DataDto> extends AbstrctReferenceNodeSupport<E, DataReference<E>> { - - /** Logger. */ - private static final Log log = LogFactory.getLog(DataReferenceNodeSupport.class); - - private static final long serialVersionUID = 1L; - - protected DataReferenceNodeSupport(Class<E> internalClass, DataReference<E> entity) { - super(internalClass, entity, null); - } - - protected DataReferenceNodeSupport(Class<E> type, DataReference<E> entity, AbstractNodeChildLoador<?, ?> childLoador) { - super(type, entity, null, childLoador); - } - - protected DataReferenceNodeSupport(Class<E> type, DataReference<E> entity, String context, AbstractNodeChildLoador<?, ?> childLoador) { - super(type, entity, context, childLoador); - } - - @Override - public void populateNode(NavBridge<DefaultTreeModel, ObserveNode> bridge, - NavDataProvider provider, - boolean populateChilds) { - - - try { - super.populateNode(bridge, provider, populateChilds); - } finally { - reloadEntity = false; - } - - if (provider != null && id != null) { - - if (entity == null) { - - loadEntity((ObserveDataProvider) provider); - - } - - if (OpenableDto.class.isAssignableFrom(entity.getType())) { - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ObserveOpenDataManager openDataManager = applicationContext.getOpenDataManager(); - open = openDataManager.isOpen(entity.getId()); - if (log.isDebugEnabled()) { - log.debug("Set open: " + open + " for entity: " + id); - } - - } - - } - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/DataSelectionTreeCellRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/DataSelectionTreeCellRenderer.java deleted file mode 100644 index 5e3c121..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/DataSelectionTreeCellRenderer.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.tree; - -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JComponent; -import javax.swing.JTree; -import java.awt.Color; -import java.awt.Component; -import java.util.List; - -import static org.nuiton.i18n.I18n.t; - -/** - * Le renderer pour décorer l'arbre de sélection des données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.2 - */ -public class DataSelectionTreeCellRenderer extends AbstractObserveTreeCellRenderer { - - /** Logger */ - private static final Log log = LogFactory.getLog(DataSelectionTreeCellRenderer.class); - - private static final long serialVersionUID = 1L; - - protected List<DataReference<?>> existingTrips; - - public List<DataReference<?>> getExistingTrips() { - return existingTrips; - } - - public void setExistingTrips(List<DataReference<?>> existingTrips) { - this.existingTrips = existingTrips; - } - - public DataSelectionTreeCellRenderer() { - } - - @Override - protected void init() { - super.init(); - setBackgroundNonSelectionColor(null); - setBackgroundSelectionColor(null); - setBackground(null); - - setTextNonSelectionColor(Color.BLACK); - setTextSelectionColor(Color.BLUE); - } - - @Override - public Component getTreeCellRendererComponent( - JTree tree, - Object value, - boolean sel, - boolean expanded, - boolean leaf, - int row, - boolean hasFocus) { - - // get the icon to set for the node - ObserveNode node = getNode(value); - - if (node == null) { - return super.getTreeCellRendererComponent( - tree, - value, - sel, - expanded, - leaf, - row, - hasFocus - ); - } - setIcon(node); - - String text = getNodeText(node); - if (log.isDebugEnabled()) { - text += " (" + row + ')'; - log.debug("repaint node " + text + " (selected:" + sel + - ") for node " + node.getId()); - } - - boolean exist = false; - - if (TripSeineDto.class.equals(node.getInternalClass())) { - - if (existingTrips != null) { - - if (existingTrips.contains(((TripSeineNode) node).getEntity())) { - text = t("observe.comon.exist.on.remote", text); - exist = true; - } - } - } - Component comp = super.getTreeCellRendererComponent( - tree, - text, - sel, - expanded, - leaf, - row, - hasFocus - ); - - //FIXME-TC20100316 can not display tooltiptext... -// delegate.setToolTipText(text); - if (exist) { - text = t("observe.message.warning.will.be.delete", text); - } - ((JComponent) comp).setToolTipText(text); - return comp; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/DataSelectionTreeSelectionModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/DataSelectionTreeSelectionModel.java deleted file mode 100644 index 389aabb..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/DataSelectionTreeSelectionModel.java +++ /dev/null @@ -1,706 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.tree; - -import com.google.common.collect.Sets; -import fr.ird.observe.services.dto.AbstractReference; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.ui.storage.tabs.DataSelectionModel; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JTree; -import javax.swing.event.EventListenerList; -import javax.swing.event.TreeSelectionEvent; -import javax.swing.event.TreeSelectionListener; -import javax.swing.tree.RowMapper; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.List; -import java.util.Set; - -/** - * Modèle de sélection dans un arbre de navigation prévu pour sélectionner des - * données. - * - * La sélection se fait en cliquant (reclic pour supprimer). - * - * Si on sélectionne un program, alors ses marée sont aussi sélectionnées. - * - * Un program est sélectionné uniquement si toutes ses marées le sont. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.2 - */ -public class DataSelectionTreeSelectionModel implements TreeSelectionModel, PropertyChangeListener, Serializable { - - /** Logger */ - private static final Log log = - LogFactory.getLog(DataSelectionTreeSelectionModel.class); - - private static final long serialVersionUID = -1L; - - protected DataSelectionModel dataModel; - - /** - * Paths that are currently selected. Will be null if nothing is currently - * selected. - */ - protected TreePath[] selection; - - /** Event listener list. */ - protected final EventListenerList listenerList = new EventListenerList(); - - /** Last path that was added. */ - protected TreePath leadPath; - - /** Index of the lead path in selection. */ - protected int leadIndex; - - /** Lead row. */ - protected int leadRow; - - protected int minSelectionRow; - - protected int maxSelectionRow; - - protected int[] selectionRows; - - /** Provides a row for a given path. */ - transient protected RowMapper rowMapper; - - protected Set<TreePath> universe; - - private PropertyChangeSupport changeSupport; - - private static final PropertyChangeListener[] - EMPTY_PROPERTY_CHANGE_LISTENERS = new PropertyChangeListener[]{}; - - public void initUI(JTree tree) { - clearSelection(); - if (universe != null) { - universe.clear(); - } - // expand tree - int i = 0; - while (i < tree.getRowCount()) { - tree.expandRow(i++); - } - // build universe of path : position of path in universe is - // exactly the row of the path - int count = tree.getRowCount(); - universe = new HashSet<>(count); - for (i = 0; i < count; i++) { - TreePath path = tree.getPathForRow(i); - universe.add(path); - if (log.isDebugEnabled()) { - log.debug("init path : " + path.getLastPathComponent()); - } - } - } - - public void setDataModel(DataSelectionModel dataModel) { - DataSelectionModel oldModel = this.dataModel; - if (oldModel != null) { - oldModel.removePropertyChangeListener(this); - oldModel.destroy(); - //TODO Should destroy all other listeners ? - //TODO this means model is dead... - } - this.dataModel = dataModel; - if (dataModel != null) { - this.dataModel.addPropertyChangeListener(this); - } - updateModel(); - } - - @Override - public void setSelectionMode(int mode) { - // pas utilise - } - - @Override - public int getSelectionMode() { - return DISCONTIGUOUS_TREE_SELECTION; - } - - @Override - public void setSelectionPath(TreePath path) { - if (dataModel == null) { - return; - } - Object o = path.getLastPathComponent(); - ObserveNode node = AbstractObserveTreeCellRenderer.getNode(o); - if (node == null) { - return; - } - Class<?> internalClass = node.getInternalClass(); - - boolean referentiel = node.isReferentielNode(); - - if (!universe.contains(path)) { - // new path - universe.add(path); - if (log.isDebugEnabled()) { - log.debug("add new path to universe " + - path.getLastPathComponent()); - } - if (!referentiel && ProgramDto.class.equals(internalClass)) { - if (log.isDebugEnabled()) { - log.debug("Adding program childs path (" + - node.getChildCount() + ")"); - } - // on ajoute toutes les marees du program - Enumeration<?> childs = node.children(); - while (childs.hasMoreElements()) { - Object o1 = childs.nextElement(); - TreePath path1 = path.pathByAddingChild(o1); - if (!universe.contains(path1)) { - if (log.isDebugEnabled()) { - log.debug("adding path for node " + o1); - } - universe.add(path1); - } - } - } - if (TripSeineDto.class.equals(internalClass)) { - TreePath parentPath = path.getParentPath(); - - if (!universe.contains(parentPath)) { - // on ajoute son parent (et tous ses freres) - universe.add(parentPath); - ObserveNode parentNode = node.getParent(); - if (log.isDebugEnabled()) { - log.debug("Adding program with his childs (" + - parentNode.getChildCount() + ")"); - } - Enumeration<?> childs = parentNode.children(); - while (childs.hasMoreElements()) { - Object o1 = childs.nextElement(); - TreePath path1 = parentPath.pathByAddingChild(o1); - if (!universe.contains(path1)) { - if (log.isDebugEnabled()) { - log.debug("adding path for node " + o1); - } - universe.add(path1); - } - } - } - } - } - - boolean pathSelected = isPathSelected(path); - - if (log.isDebugEnabled()) { - log.debug("node " + node + ", path selected ? " + pathSelected); - } - - if (referentiel && node.isStringNode()) { - - Set<Class<? extends ReferentialDto>> subClasses = Sets.newHashSet(); - - for (Enumeration<ObserveNode> children = node.children(); children.hasMoreElements(); ) { - subClasses.add((Class<? extends ReferentialDto>) children.nextElement().getInternalClass()); - } - - if (pathSelected) { - if (log.isDebugEnabled()) { - log.debug("Will remove all referentiels on " + node); - } - dataModel.removeAllReferentiel(subClasses); - } else { - if (log.isDebugEnabled()) { - log.debug("Will add all referentiels on " + node); - } - dataModel.addAllReferentiel(subClasses); - } - return; - } - - if (referentiel) { - - if (pathSelected) { - if (log.isDebugEnabled()) { - log.debug("Will remove referentiel " + internalClass + " to model"); - } - dataModel.removeSelectedReferentiel(internalClass); - } else { - if (log.isDebugEnabled()) { - log.debug("Will add referentiel " + internalClass + " to model"); - } - dataModel.addSelectedReferentiel((Class<? extends ReferentialDto>) internalClass); - } - return; - } - - if (node instanceof AbstrctReferenceNodeSupport) { - AbstractReference dto = ((AbstrctReferenceNodeSupport) node).getEntity(); - if (log.isDebugEnabled()) { - log.debug("bean " + dto.getId()); - } - if (pathSelected) { - if (log.isDebugEnabled()) { - log.debug("Already add ? remove it."); - } - removeFromDataModel(dto); - } else { - if (log.isDebugEnabled()) { - log.debug("Will add selection to model"); - } - addToDataModel(dto); - } - } - } - - @Override - public void setSelectionPaths(TreePath[] paths) { - // do nothing - } - - @Override - public void addSelectionPath(TreePath path) { - // do nothing - } - - @Override - public void addSelectionPaths(TreePath[] paths) { - // do nothing - } - - @Override - public void removeSelectionPath(TreePath path) { - // do nothing - } - - @Override - public void removeSelectionPaths(TreePath[] paths) { - // do nothing - } - - @Override - public TreePath getSelectionPath() { - return selection == null ? null : selection[0]; - } - - @Override - public TreePath[] getSelectionPaths() { - return selection; - } - - @Override - public int getSelectionCount() { - return selection == null ? 0 : selection.length; - } - - @Override - public boolean isPathSelected(TreePath path) { - if (dataModel == null) { - return false; - } - Object o = path.getLastPathComponent(); - ObserveNode node = AbstractObserveTreeCellRenderer.getNode(o); - if (node != null) { - - Class<?> internalClass = node.getInternalClass(); - if (node.isReferentielNode() && node.isStringNode()) { - Set<Class<? extends ReferentialDto>> subClasses = Sets.newHashSet(); - - for (Enumeration<ObserveNode> children = node.children(); children.hasMoreElements(); ) { - subClasses.add((Class<? extends ReferentialDto>) children.nextElement().getInternalClass()); - } - - boolean result = dataModel.isReferentielSelectAll(subClasses); - if (log.isTraceEnabled()) { - log.trace("selectModel use full referentiel " + - internalClass + " ? " + result); - } - return result; - } - if (node.isReferentielNode()) { - boolean result = dataModel.isSelectedReferentiel(internalClass); - if (log.isTraceEnabled()) { - log.trace("selectModel use referentiel " + - internalClass + " ? " + result); - } - return result; - } - - if (log.isTraceEnabled()) { - log.trace("begin data node " + node); - } - - if (node instanceof AbstrctReferenceNodeSupport) { - boolean result = dataModel.isSelectedData(((AbstrctReferenceNodeSupport) node).getEntity()); - if (log.isTraceEnabled()) { - log.trace("selectModel contains the program ? " + result); - } - return result; - } - - - } - return false; - } - - @Override - public boolean isSelectionEmpty() { - return selection == null || selection.length == 0; - } - - @Override - public void clearSelection() { - if (dataModel == null) { - return; - } - selection = null; - dataModel.removeAll(); - } - - @Override - public RowMapper getRowMapper() { - return rowMapper; - } - - @Override - public void setRowMapper(RowMapper newMapper) { - rowMapper = newMapper; - } - - @Override - public int[] getSelectionRows() { - // on doit recalcule cette valeur a chaque fois - //This is currently rather expensive.Needs - // to be better support from ListSelectionModel to speed this up. - return selectionRows; - } - - @Override - public int getMinSelectionRow() { - return minSelectionRow; - } - - @Override - public int getMaxSelectionRow() { - return maxSelectionRow; - } - - @Override - public int getLeadSelectionRow() { - return leadRow; - } - - @Override - public TreePath getLeadSelectionPath() { - return leadPath; - } - - @Override - public boolean isRowSelected(int row) { - if (!isSelectionEmpty()) { - for (int i : selectionRows) { - if (row == i) { - return true; - } - } - } - return false; - } - - @Override - public void resetRowSelection() { - if (log.isDebugEnabled()) { - log.debug("start rebuild row values..."); - } - leadRow = minSelectionRow = maxSelectionRow = -1; - selectionRows = null; - if (rowMapper == null || selection == null || selection.length == 0) { - return; - } - - int[] rows = rowMapper.getRowsForPaths(selection); - - if (rows != null) { - int invisCount = 0; - - for (int counter = rows.length - 1; counter >= 0; counter--) { - if (rows[counter] == -1) { - invisCount++; - } - } - if (invisCount > 0) { - if (invisCount == rows.length) { - rows = null; - } else { - int[] tempRows = new int[rows.length - invisCount]; - - for (int counter = rows.length - 1, visCounter = 0; - counter >= 0; counter--) { - if (rows[counter] != -1) { - tempRows[visCounter++] = rows[counter]; - } - } - rows = tempRows; - } - } - } - - selectionRows = rows; - - if (isSelectionEmpty()) { - leadPath = null; - leadIndex = -1; - leadRow = -1; - } else { - leadPath = selection[0]; - leadIndex = 0; - leadRow = selectionRows[0]; - } - - int selectionLength = selectionRows.length; - - minSelectionRow = -1; - maxSelectionRow = 0; - for (int i = 0; i < selectionLength; i++) { - int row = selectionRows[i]; - if (row > maxSelectionRow) { - maxSelectionRow = row; - } - if (row < minSelectionRow) { - minSelectionRow = row; - } - } - } - - /** - * Adds x to the list of listeners that are notified each time the set of - * selected TreePaths changes. - * - * @param x the new listener to be added - */ - @Override - public void addTreeSelectionListener(TreeSelectionListener x) { - listenerList.add(TreeSelectionListener.class, x); - } - - /** - * Removes x from the list of listeners that are notified each time the set - * of selected TreePaths changes. - * - * @param x the listener to remove - */ - @Override - public void removeTreeSelectionListener(TreeSelectionListener x) { - listenerList.remove(TreeSelectionListener.class, x); - } - - /** - * Returns an array of all the tree selection listeners registered on this - * model. - * - * @return all of this model's {@code TreeSelectionListener}s or an - * empty array if no tree selection listeners are currently - * registered - * @see #addTreeSelectionListener - * @see #removeTreeSelectionListener - * @since 1.4 - */ - public TreeSelectionListener[] getTreeSelectionListeners() { - return listenerList.getListeners(TreeSelectionListener.class); - } - - /** - * Adds a PropertyChangeListener to the listener list. The listener is - * registered for all properties. - * - * A PropertyChangeEvent will get fired when the selection mode changes. - * - * @param listener the PropertyChangeListener to be added - */ - @Override - public void addPropertyChangeListener(PropertyChangeListener listener) { - if (changeSupport == null) { - changeSupport = new PropertyChangeSupport(this); - } - changeSupport.addPropertyChangeListener(listener); - } - - /** - * Removes a PropertyChangeListener from the listener list. This removes a - * PropertyChangeListener that was registered for all properties. - * - * @param listener the PropertyChangeListener to be removed - */ - - @Override - public void removePropertyChangeListener(PropertyChangeListener listener) { - if (changeSupport == null) { - return; - } - changeSupport.removePropertyChangeListener(listener); - } - - /** - * Returns an array of all the property change listeners registered on this - * {@code DefaultTreeSelectionModel}. - * - * @return all of this model's {@code PropertyChangeListener}s or an - * empty array if no property change listeners are currently - * registered - * @see #addPropertyChangeListener - * @see #removePropertyChangeListener - * @since 1.4 - */ - public PropertyChangeListener[] getPropertyChangeListeners() { - if (changeSupport == null) { - return EMPTY_PROPERTY_CHANGE_LISTENERS; - } - return changeSupport.getPropertyChangeListeners(); - } - - protected void fireValueChanged(TreeSelectionEvent e) { - // Guaranteed to return a non-null array - Object[] listeners = listenerList.getListenerList(); - // TreeSelectionEvent e = null; - // Process the listeners last to first, notifying - // those that are interested in this event - for (int i = listeners.length - 2; i >= 0; i -= 2) { - if (TreeSelectionListener.class.equals(listeners[i])) { - // Lazily create the event: - // if (e == null) - // e = new ListSelectionEvent(this, firstIndex, lastIndex); - ((TreeSelectionListener) listeners[i + 1]).valueChanged(e); - } - } - } - - protected void addToDataModel(AbstractReference dto) { - - if (log.isTraceEnabled()) { - log.trace("selectModel add " + dto.getId()); - } - dataModel.addSelectedData(dto); - - } - - protected void removeFromDataModel(AbstractReference dto) { - if (log.isTraceEnabled()) { - log.trace("selectModel remove " + dto.getId()); - } - dataModel.removeSelectedData(dto); - } - - @Override - public void propertyChange(PropertyChangeEvent evt) { - String propertyName = evt.getPropertyName(); - if (DataSelectionModel.PROPERTY_SELECTED_DATA.equals(propertyName) || - DataSelectionModel.PROPERTY_SELECTED_REFERENTIEL.equals(propertyName)) { - // la selection a changee - Object value = evt.getNewValue(); - if (log.isDebugEnabled()) { - log.debug("selection data changed " + value); - } - } - updateModel(); - } - - protected void updateModel() { - if (rowMapper == null || universe == null) { - return; - } - - // recalcule de la selection - - List<TreePath> oldSelection = isSelectionEmpty() ? - Collections.emptyList() : - Arrays.asList(selection); - - List<TreePath> newSelection = new ArrayList<>(); - - for (TreePath p : universe) { - if (isPathSelected(p)) { - newSelection.add(p); - } - } - - int selectionLength = newSelection.size(); - - selection = newSelection.toArray(new TreePath[selectionLength]); - - // calcul du leadPath - - TreePath oldLeadPath = leadPath; - - if (isSelectionEmpty()) { - leadPath = null; - leadIndex = -1; - } else { - leadPath = selectionLength > 0 ? selection[0] : null; - leadIndex = 0; - } - - if (log.isDebugEnabled()) { - log.debug("new selection length = " + selectionLength); - } - - // recalcule des donnees de rows - resetRowSelection(); - - if (log.isDebugEnabled()) { - log.debug("new selection length = " + - (selectionRows == null ? 0 : selectionRows.length)); - if (log.isDebugEnabled()) { - log.debug("selected rows = " + Arrays.toString(selectionRows)); - } - } - - // calcule des paths qui ont changés - List<TreePath> obsoleteSelection = new ArrayList<>(oldSelection); - obsoleteSelection.removeAll(newSelection); - - List<TreePath> changedPaths = new ArrayList<>(oldSelection); - changedPaths.addAll(newSelection); - - TreePath[] treePaths = changedPaths.toArray(new TreePath[changedPaths.size()]); - - // notification des modifications sur la selection - TreeSelectionEvent event = new TreeSelectionEvent( - this, - treePaths, - new boolean[treePaths.length], - oldLeadPath, - leadPath - ); - fireValueChanged(event); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/FloatingObjectSeineNode.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/FloatingObjectSeineNode.java deleted file mode 100644 index 3efaa61..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/FloatingObjectSeineNode.java +++ /dev/null @@ -1,52 +0,0 @@ -package fr.ird.observe.ui.tree; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.seine.FloatingObjectDto; -import fr.ird.observe.services.service.seine.FloatingObjectService; -import fr.ird.observe.ui.tree.loadors.FloatingObjectNodeChildLoador; - -/** - * Created on 4/9/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 4.0 - */ -public class FloatingObjectSeineNode extends DataReferenceNodeSupport<FloatingObjectDto> { - - private static final long serialVersionUID = 1L; - - public FloatingObjectSeineNode(DataReference<FloatingObjectDto> entity) { - super(FloatingObjectDto.class, entity, ObserveTreeHelper.getChildLoador(FloatingObjectNodeChildLoador.class)); - } - - @Override - protected DataReference<FloatingObjectDto> fetchEntity() { - FloatingObjectService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newFloatingObjectService(); - DataReference<FloatingObjectDto> referenceDto = service.loadReferenceToRead(getId()); - return referenceDto; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/NavigationTreeCellRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/NavigationTreeCellRenderer.java deleted file mode 100644 index 69a630e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/NavigationTreeCellRenderer.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.tree; - -import javax.swing.JComponent; -import javax.swing.JTree; -import javax.swing.tree.DefaultTreeModel; -import java.awt.Color; -import java.awt.Component; - -/** - * Un renderer pour modifier l'apparence des noeuds de l'arbre de navigation. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class NavigationTreeCellRenderer extends AbstractObserveTreeCellRenderer { - - private static final long serialVersionUID = 1L; - - public NavigationTreeCellRenderer() { - } - - @Override - public Component getTreeCellRendererComponent(JTree tree, - Object value, - boolean sel, - boolean expanded, - boolean leaf, - int row, - boolean hasFocus) { - - if (!(tree.getModel() instanceof DefaultTreeModel)) { - Component rendererComponent; - rendererComponent = super.getTreeCellRendererComponent( - tree, - value, - sel, - expanded, - leaf, - row, - hasFocus - ); - return rendererComponent; - } - - // get the icon to set for the node - ObserveNode node = getNode(value); - - setIcon(node); - - if (!sel) { - - Color color = getNavigationTextColor(node); - if (log.isTraceEnabled()) { - log.trace("===" + color + " for node " + - node.getInternalClass() + " - " + node.getId()); - } - setTextNonSelectionColor(color); - } - - String text = getNodeText(node); - if (log.isTraceEnabled()) { - log.trace("===" + text + " for node " + - node.getInternalClass() + " - " + node.getId()); - } - Component comp = super.getTreeCellRendererComponent( - tree, - text, - sel, - expanded, - leaf, - row, - hasFocus - ); - ((JComponent) comp).setToolTipText(text); - return comp; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/NavigationTreeSelectionModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/NavigationTreeSelectionModel.java deleted file mode 100644 index 28c198e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/NavigationTreeSelectionModel.java +++ /dev/null @@ -1,118 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.tree; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.ui.UIHelper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.tree.DefaultTreeSelectionModel; -import javax.swing.tree.TreePath; - -/** - * Le modèle de sélection de l'abre de navigation. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class NavigationTreeSelectionModel extends DefaultTreeSelectionModel { - - /** Logger */ - static private final Log log = - LogFactory.getLog(NavigationTreeSelectionModel.class); - - private static final long serialVersionUID = 1L; - - @Override - public void addSelectionPath(TreePath newPath) { - TreePath oldPath = getSelectionPath(); - if (log.isDebugEnabled()) { - log.debug(">------------------------------------------------------------------------------"); - log.debug("Try to change selection"); - log.debug("old path " + oldPath); - log.debug("new path " + newPath); - } - boolean canChange = beforeSelectionPath(oldPath, newPath); - if (log.isDebugEnabled()) { - log.debug("Can change path ? " + canChange); - log.debug("<------------------------------------------------------------------------------"); - } - if (!canChange) { - return; - } - - // ok can safely select the new path - if (log.isTraceEnabled()) { - log.trace("will select path " + newPath); - } - super.addSelectionPath(newPath); - } - - @Override - public void setSelectionPath(TreePath newPath) { - TreePath oldPath = getSelectionPath(); - if (log.isDebugEnabled()) { - log.debug(">------------------------------------------------------------------------------"); - log.debug("Try to change selection"); - log.debug("old path " + oldPath); - log.debug("new path " + newPath); - } - boolean canChange = beforeSelectionPath(oldPath, newPath); - if (log.isDebugEnabled()) { - log.debug("Can change path ? " + canChange); - log.debug("<------------------------------------------------------------------------------"); - } - if (!canChange) { - return; - } - - // ok can safely select the new path - if (log.isTraceEnabled()) { - log.trace("will select path " + newPath); - } - try { - super.setSelectionPath(newPath); - } catch (Exception e) { - UIHelper.handlingError(e); - } - } - - protected boolean beforeSelectionPath(TreePath oldPath, TreePath newPath) { - - boolean canChange = true; - - if (newPath.equals(oldPath)) { - // stay on same node, can skip - if (log.isDebugEnabled()) { - log.debug("skip stay on path " + newPath); - } - canChange = false; - } - - if (canChange && !isSelectionEmpty()) { - canChange = ObserveSwingApplicationContext.get().getContentUIManager().closeSelectedContentUI(); - } - - return canChange; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ObserveDataProvider.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ObserveDataProvider.java deleted file mode 100644 index 9a21479..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ObserveDataProvider.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.tree; - -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.ui.storage.tabs.DataSelectionModel; -import jaxx.runtime.swing.nav.NavDataProvider; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Provider de données pour les noeuds des arbres. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ObserveDataProvider implements NavDataProvider { - - /** Logger */ - static private final Log log = LogFactory.getLog(ObserveDataProvider.class); - - protected ObserveSwingDataSource dataSource; - - protected DataSelectionModel selectionModel; - - private boolean creating; - - public ObserveDataProvider(ObserveSwingDataSource dataSource) { - this.dataSource = dataSource; - } - - public void setSource(ObserveSwingDataSource dataSource) { - this.dataSource = dataSource; - } - - public void setSelectionModel(DataSelectionModel selectionModel) { - if (log.isDebugEnabled()) { - log.debug("Set selection model : " + selectionModel); - } - this.selectionModel = selectionModel; - } - - @Override - public boolean isEnabled() { - return dataSource != null && dataSource.isOpen() || selectionModel != null; - } - - public ObserveSwingDataSource getDataSource() { - return dataSource; - } - - public DataSelectionModel getSelectionModel() { - return selectionModel; - } - - public boolean isCreating() { - return creating; - } - - public void setCreating(boolean creating) { - this.creating = creating; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ObserveNavigationTreeShowPopupAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ObserveNavigationTreeShowPopupAction.java deleted file mode 100644 index e102fca..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ObserveNavigationTreeShowPopupAction.java +++ /dev/null @@ -1,392 +0,0 @@ -package fr.ird.observe.ui.tree; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.base.Preconditions; -import com.google.common.collect.ImmutableMap; -import fr.ird.observe.ObserveOpenDataManager; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.ui.content.ContentUI; -import fr.ird.observe.ui.content.open.ContentOpenableUI; -import fr.ird.observe.ui.tree.menu.MoveActivityLonglineNodeMenuPopulator; -import fr.ird.observe.ui.tree.menu.MoveActivitySeineNodeMenuPopulator; -import fr.ird.observe.ui.tree.menu.MoveNodeMenuPopulator; -import fr.ird.observe.ui.tree.menu.MoveRouteNodeMenuPopulator; -import fr.ird.observe.ui.tree.menu.MoveTripNodeMenuPopulator; -import fr.ird.observe.ui.util.DecoratedNodeEntity; -import jaxx.runtime.SwingUtil; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JButton; -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.JTree; -import javax.swing.MenuElement; -import javax.swing.SwingUtilities; -import javax.swing.tree.TreePath; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Created on 1/8/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.11 - */ -public class ObserveNavigationTreeShowPopupAction { - - /** Logger. */ - private static final Log log = LogFactory.getLog(ObserveNavigationTreeShowPopupAction.class); - - private static final String TRIP_MENU_ITEMS = "trip"; - private static final String ROUTE_MENU_ITEMS = "route"; - private static final String ACTIVITY_SEINE_MENU_ITEMS = "activitySeine"; - private static final String ACTIVITY_LONGLINE_MENU_ITEMS = "activityLongline"; - - static { - n("observe.navigationMenu.move.trip"); - n("observe.navigationMenu.move.route"); - n("observe.navigationMenu.move.activitySeine"); - n("observe.navigationMenu.move.activityLongline"); - } - - private final ObserveTreeHelper treeHelper; - - private final JScrollPane pane; - - private final JPopupMenu popup; - - private final JTree tree; - - private final JMenuItem noAction; - private final JMenuItem openAction; - private final JMenuItem closeAction; - private final JMenuItem moveAction; - private final JMenuItem deleteAction; - - private final ImmutableMap<String, MoveNodeMenuPopulator> moveNodeDataByNodeType; - - public ObserveNavigationTreeShowPopupAction(final ObserveTreeHelper treeHelper, JScrollPane pane, JPopupMenu popup) { - - this.treeHelper = treeHelper; - this.pane = pane; - this.popup = popup; - this.tree = treeHelper.getUI(); - - JMenuItem noActionComponent = null; - // trip menus - JMenuItem moveComponent = null; - JMenuItem openActionComponent = null; - JMenuItem closeActionComponent = null; - JMenuItem deleteActionComponent = null; - - for (MenuElement menuElement : popup.getSubElements()) { - - if (menuElement.getComponent().getName().equals("navigationNoAction")) { - noActionComponent = (JMenuItem) menuElement.getComponent(); - } - if (menuElement.getComponent().getName().equals("navigationMoveAction")) { - moveComponent = (JMenuItem) menuElement.getComponent(); - } - if (menuElement.getComponent().getName().equals("navigationOpenAction")) { - openActionComponent = (JMenuItem) menuElement.getComponent(); - } - if (menuElement.getComponent().getName().equals("navigationCloseAction")) { - closeActionComponent = (JMenuItem) menuElement.getComponent(); - } - if (menuElement.getComponent().getName().equals("navigationDeleteAction")) { - deleteActionComponent = (JMenuItem) menuElement.getComponent(); - } - } - - this.noAction = noActionComponent; - this.openAction = openActionComponent; - this.closeAction = closeActionComponent; - this.moveAction = moveComponent; - this.deleteAction = deleteActionComponent; - - moveNodeDataByNodeType = ImmutableMap.of(TRIP_MENU_ITEMS, new MoveTripNodeMenuPopulator(), - ROUTE_MENU_ITEMS, new MoveRouteNodeMenuPopulator(), - ACTIVITY_SEINE_MENU_ITEMS, new MoveActivitySeineNodeMenuPopulator(), - ACTIVITY_LONGLINE_MENU_ITEMS, new MoveActivityLonglineNodeMenuPopulator()); - - KeyAdapter keyAdapter = new KeyAdapter() { - @Override - public void keyPressed(KeyEvent e) { - if (tree.isEnabled()) { - openNodeMenu(e); - } - } - }; - tree.addKeyListener(keyAdapter); - pane.addKeyListener(keyAdapter); - - MouseAdapter mouseAdapter = new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (tree.isEnabled()) { - autoSelectNodeInTree(e); - } - } - }; - tree.addMouseListener(mouseAdapter); - pane.addMouseListener(mouseAdapter); - } - - protected void autoSelectNodeInTree(MouseEvent e) { - - boolean rightClick = SwingUtilities.isRightMouseButton(e); - - if (rightClick) { - - // get the coordinates of the mouse click - Point p = e.getPoint(); - - int closestRowForLocation = tree.getClosestRowForLocation(e.getX(), e.getY()); - - int rowToSelect = -1; - - if (isRowSelected(closestRowForLocation)) { - - rowToSelect = closestRowForLocation; - } - - if (rowToSelect == -1) { - - // try to change selection - - TreePath pathForRow = tree.getPathForRow(closestRowForLocation); - tree.setSelectionPath(pathForRow); - - if (isRowSelected(closestRowForLocation)) { - - rowToSelect = closestRowForLocation; - } - - } - - if (rowToSelect != -1) { - - showPopup(rowToSelect, p); - - } - - } - } - - public void openNodeMenu(KeyEvent e) { - - if (e.getKeyCode() == KeyEvent.VK_CONTEXT_MENU && !tree.isSelectionEmpty()) { - - // get the lowest selected row - int lowestRow = getLowestSelectedRowCount(); - - // get the selected column - Rectangle r = tree.getRowBounds(lowestRow); - - // get the point in the middle lower of the cell - Point p = new Point(r.x + r.width / 2, r.y + r.height); - - if (log.isDebugEnabled()) { - log.debug("Row " + lowestRow + " found t point [" + p + "]"); - } - - showPopup(lowestRow, p); - - } - } - - protected void showPopup(int row, Point p) { - - if (log.isInfoEnabled()) { - log.info("Will show popup from row: " + row); - } - - ObserveNode selectedNode = (ObserveNode) tree.getPathForRow(row).getLastPathComponent(); - - if (log.isInfoEnabled()) { - log.info("Found selected node: " + selectedNode); - } - - beforeOpenPopup(selectedNode); - - popup.show(tree, p.x, p.y); - - } - - protected void beforeOpenPopup(ObserveNode selectedNode) { - - // clean popup - popup.removeAll(); - - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - DataContext dataContext = applicationContext.getDataContext(); - ContentUI<?> selectedContentUI = applicationContext.getContentUIManager().getSelectedContentUI(); - ObserveOpenDataManager openDataManager = applicationContext.getOpenDataManager(); - - boolean closeActionEnabled = false; - - if (selectedContentUI instanceof ContentOpenableUI) { - JButton closeButton = ((ContentOpenableUI) selectedContentUI).getClose(); - closeActionEnabled = closeButton.isEnabled(); - } - - if (selectedNode.isTripNode()) { - - beforeOpenMenu(selectedNode, TRIP_MENU_ITEMS); - - openAction.setEnabled(!dataContext.isOpenTrip()); - closeAction.setEnabled(closeActionEnabled); - - } else if (selectedNode.isRouteNode()) { - - beforeOpenMenu(selectedNode, ROUTE_MENU_ITEMS); - - openAction.setEnabled(openDataManager.canOpenRoute(dataContext.getSelectedTripSeineId())); - closeAction.setEnabled(closeActionEnabled); - - } else if (selectedNode.isActivitySeineNode()) { - - beforeOpenMenu(selectedNode, ACTIVITY_SEINE_MENU_ITEMS); - - openAction.setEnabled(openDataManager.canOpenActivitySeine(dataContext.getSelectedRouteId())); - closeAction.setEnabled(closeActionEnabled); - - } else if (selectedNode.isActivityLonglineNode()) { - - beforeOpenMenu(selectedNode, ACTIVITY_LONGLINE_MENU_ITEMS); - - openAction.setEnabled(openDataManager.canOpenActivityLongline(dataContext.getSelectedTripLonglineId())); - closeAction.setEnabled(closeActionEnabled); - - } else { - - popup.add(noAction); - } - } - - protected void beforeOpenMenu(ObserveNode selectedNode, String nodeType) { - if (log.isInfoEnabled()) { - log.info("Will load popup for " + nodeType + " node."); - } - - MoveNodeMenuPopulator moveNodeData = moveNodeDataByNodeType.get(nodeType); - - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - - if (selectedNode.isOpen()) { - - closeAction.putClientProperty("ui", applicationContext.getContentUIManager().getSelectedContentUI()); - popup.add(closeAction); - - - } else { - - openAction.putClientProperty("ui", applicationContext.getContentUIManager().getSelectedContentUI()); - popup.add(openAction); - - } - - moveAction.setText(t("observe.navigationMenu.move." + nodeType)); - moveAction.setToolTipText(t("observe.navigationMenu.move." + nodeType)); - moveAction.setIcon(SwingUtil.getUIManagerActionIcon("move-" + nodeType)); - popup.add(moveAction); - - moveAction.removeAll(); - - // get the available program for the trip - - String id = selectedNode.getId(); - - ObserveSwingDataSource dataSource = treeHelper.getDataProvider().getDataSource(); - - List<DecoratedNodeEntity> possibleParentNodes = moveNodeData.getPossibleParentNodes(selectedNode, treeHelper); - - for (DecoratedNodeEntity possibleParent : possibleParentNodes) { - - String possibleParentId = possibleParent.getId(); - JMenuItem item = new JMenuItem(possibleParent.toString()); - item.setName(possibleParentId); - - - item.addActionListener(moveNodeData.createChangeActionListener(treeHelper, - dataSource, - id, - possibleParentId)); - - moveAction.add(item); - } - - deleteAction.putClientProperty("ui", applicationContext.getContentUIManager().getSelectedContentUI()); - deleteAction.setEnabled(selectedNode.isOpen()); - popup.add(deleteAction); - } - - protected boolean isRowSelected(int requiredRow) { - - boolean result = false; - - int[] selectedRows = tree.getSelectionRows(); - if (selectedRows != null) { - for (int selectedRow : selectedRows) { - if (requiredRow == selectedRow) { - - // match - result = true; - break; - } - } - } - - return result; - - } - - protected int getLowestSelectedRowCount() { - - Preconditions.checkState(!tree.isSelectionEmpty()); - - int[] selectedRows = tree.getSelectionRows(); - int lowestRow = -1; - if (selectedRows != null) { - for (int row : selectedRows) { - lowestRow = Math.max(lowestRow, row); - } - } - return lowestRow; - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ObserveNode.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ObserveNode.java deleted file mode 100644 index 2c71c57..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ObserveNode.java +++ /dev/null @@ -1,119 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.tree; - -import fr.ird.observe.services.dto.OpenableDto; -import fr.ird.observe.services.dto.longline.ActivityLonglineDto; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import jaxx.runtime.swing.nav.tree.NavTreeNode; -import jaxx.runtime.swing.nav.tree.NavTreeNodeChildLoador; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Le modèle d'une noeud. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ObserveNode extends NavTreeNode<ObserveNode> { - - /** Logger */ - static private final Log log = LogFactory.getLog(ObserveNode.class); - - public static long count; - - private static final long serialVersionUID = 1L; - - /** un drapeau pour savoir si le noeud fait parti du referentiel */ - protected final boolean referentiel; - - /** - * Un etat pour savoir si l'objet (de donnee) encapsule est ouvert. - * - * <b>Note:</b> Il faut que l'objet soit de type {@link OpenableDto}. - */ - protected Boolean open; - - public ObserveNode(String id, boolean referentiel) { - this(String.class, id, null, null, referentiel); - } - - public ObserveNode(Class<?> internalClass, - String id, - boolean referentiel) { - this(internalClass, id, null, null, referentiel); - } - - public ObserveNode(Class<?> internalClass, - String id, - NavTreeNodeChildLoador<?, ?, ObserveNode> childLoador, - boolean referentiel) { - this(internalClass, id, null, childLoador, referentiel); - } - - public ObserveNode(Class<?> internalClass, - String id, - String context, - NavTreeNodeChildLoador<?, ?, ObserveNode> childLoador, - boolean referentiel) { - super(internalClass, id, context, childLoador); - this.referentiel = referentiel; - count++; - if (log.isDebugEnabled()) { - log.debug("Creates a new node [" + count + "] " + this); - } - } - - public boolean isDataNode() { - return !referentiel; - } - - public boolean isReferentielNode() { - return referentiel; - } - - public Boolean isOpen() { - return open; - } - - public boolean isTripNode() { - return isDataNode() && - (TripSeineDto.class.isAssignableFrom(internalClass) - || TripLonglineDto.class.isAssignableFrom(internalClass)); - } - - public boolean isRouteNode() { - return isDataNode() && RouteDto.class.isAssignableFrom(internalClass); - } - - public boolean isActivitySeineNode() { - return isDataNode() && ActivitySeineDto.class.isAssignableFrom(internalClass); - } - - public boolean isActivityLonglineNode() { - return isDataNode() && ActivityLonglineDto.class.isAssignableFrom(internalClass); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ObserveTreeBridge.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ObserveTreeBridge.java deleted file mode 100644 index 72f53df..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ObserveTreeBridge.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2011 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.tree; - -import jaxx.runtime.swing.nav.tree.NavTreeBridge; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JTree; -import javax.swing.tree.TreeNode; -import javax.swing.tree.TreePath; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; - -/** - * Bridge specialise pour reduire le count de chargements de noeuds non visibles. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 2.0 - */ -public class ObserveTreeBridge extends NavTreeBridge<ObserveNode> { - - /** Logger. */ - static private final Log log = LogFactory.getLog(ObserveTreeBridge.class); - - protected JTree ui; - - protected final List<String> pathToSelect; - - public ObserveTreeBridge() { - pathToSelect = new ArrayList<>(); - } - - public void setUi(JTree ui) { - this.ui = ui; - } - - @Override - public boolean canLoadChild(ObserveNode node) { - - ObserveNode root = getRoot(); - if (node.equals(root)) { - - // always allow to load childs from level 0 - return true; - } - ObserveNode parent = node.getParent(); - if (parent.equals(root)) { - - // always allow to load childs from level 0 - return true; - } - - TreeNode[] pathToRoot = getPathToRoot(node); - TreePath path = new TreePath(pathToRoot); - if (CollectionUtils.isNotEmpty(pathToSelect)) { - - // select mode is on - if (log.isDebugEnabled()) { - log.debug("There is a selected path, try to use it for " + node); - } - String nodeId = node.getId(); - - ObserveNode containerNode; - if (nodeId.startsWith(ObserveTreeHelper.TREE_NODE_PREFIX)) { - containerNode = node.getParent(); - } else { - containerNode = node; - } - - String containerNodeId = containerNode.getId(); - if (log.isDebugEnabled()) { - log.debug("Test if data node is in path ? " + - containerNodeId + " : " + - pathToSelect.contains(containerNodeId)); - } - - if (pathToSelect.contains(containerNodeId)) { - - // ok on the good way... - return true; - } - - // not on a good way, skip loading of childs... - return false; - } - - if (ui == null) { - if (log.isDebugEnabled()) { - log.debug("No ui in bridge!!!"); - } - - // no ui, and no path to select : so no need to restrict - return true; - } - - boolean visible = ui.isVisible(path); - - if (!visible) { - - // only visible node can be loaded - return false; - } - - TreePath selected = ui.getSelectionPath(); - if (!path.equals(selected)) { - - // only selected node can be loaded - return false; - } - - // ok childs can be loaded - return true; - } - - public void setPathToSelect(String... pathToSelect) { - this.pathToSelect.clear(); - this.pathToSelect.addAll(Arrays.asList(pathToSelect)); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ObserveTreeHelper.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ObserveTreeHelper.java deleted file mode 100644 index 6485a06..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ObserveTreeHelper.java +++ /dev/null @@ -1,669 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.tree; - -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.services.dto.constants.ReferentialLocale; -import fr.ird.observe.services.dto.longline.ActivityLonglineDto; -import fr.ird.observe.services.dto.longline.SetLonglineDto; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.dto.reference.ReferenceBinderEngine; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.services.dto.seine.FloatingObjectDto; -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.services.dto.seine.SetSeineDto; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.ui.ObserveMainUI; -import fr.ird.observe.ui.storage.tabs.DataSelectionModel; -import fr.ird.observe.ui.tree.loadors.AbstractNodeChildLoador; -import fr.ird.observe.ui.tree.loadors.ActivityLonglineNodeChildLoador; -import fr.ird.observe.ui.tree.loadors.ActivityLonglinesNodeChildLoador; -import fr.ird.observe.ui.tree.loadors.ActivitySeineNodeChildLoador; -import fr.ird.observe.ui.tree.loadors.ActivitySeinesNodeChildLoador; -import fr.ird.observe.ui.tree.loadors.ProgramLonglineNodeChildLoador; -import fr.ird.observe.ui.tree.loadors.ProgramSeineNodeChildLoador; -import fr.ird.observe.ui.tree.loadors.RootNodeChildLoador; -import fr.ird.observe.ui.tree.loadors.RoutesNodeChildLoador; -import jaxx.runtime.JAXXContext; -import jaxx.runtime.swing.nav.NavDataProvider; -import jaxx.runtime.swing.nav.tree.NavTreeHelper; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JTree; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreeCellRenderer; -import javax.swing.tree.TreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; -import java.util.Arrays; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; -import java.util.Set; - -import static org.nuiton.i18n.I18n.n; - -/** - * Class utilitaire pour la bestion de l'arbre de navigation. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ObserveTreeHelper extends NavTreeHelper<ObserveNode> { - - public static final String TREE_NODE_PREFIX = "observe.tree."; - - /** Logger. */ - static private final Log log = LogFactory.getLog(ObserveTreeHelper.class); - - private boolean createUnsaved; - - public static ObserveNode createStringNode(String context) { - - ObserveNode result = createStringNode(context, null); - return result; - - } - - public static <L extends AbstractNodeChildLoador> ObserveNode createStringNode(String context, Class<L> loadorType) { - - L childLoador = loadorType == null ? null : ObserveTreeHelper.getChildLoador(loadorType); - - String propertyLabel = DecoratorService.getPropertyLabel(TREE_NODE_PREFIX, context); - ObserveNode result = new ObserveNode(String.class, - propertyLabel, - context, - childLoador, - false); - return result; - - } - - public static void sortPrograms(List<ReferentialReference<ProgramDto>> data) { - Collections.sort(data, new Comparator<ReferentialReference<ProgramDto>>() { - - ReferentialReferenceDecorator<ProgramDto> decorator = ObserveSwingApplicationContext.get().getDecoratorService().getReferentialReferenceDecorator(ProgramDto.class); - - @Override - public int compare(ReferentialReference<ProgramDto> o1, ReferentialReference<ProgramDto> o2) { - - - return this.decorator.toString(o1).compareTo(this.decorator.toString(o2)); - } - }); - } - - public ObserveTreeHelper() { - super(new ObserveTreeBridge()); - } - - public NavigationTreeSelectionModel newNavigationSelectionModel() { - NavigationTreeSelectionModel model = new NavigationTreeSelectionModel(); - model.setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); - return model; - } - - public AbstractObserveTreeCellRenderer getTreeCellRenderer() { - JTree t = getUI(); - if (t == null) { - return null; - } - TreeCellRenderer r = t.getCellRenderer(); - return (AbstractObserveTreeCellRenderer) - (r instanceof AbstractObserveTreeCellRenderer ? r : null); - } - - public TreeModel createEmptyModel() { - - setDataSource(null); - - ObserveNode node = - new ObserveNode(n("observe.message.db.none.loaded"), false); - - DefaultTreeModel model = createModel(node); - return model; - } - - public TreeModel createModel(ObserveSwingDataSource source) { - - setDataSource(source); - - ObserveDataProvider provider = getDataProvider(); - provider.setCreating(true); - - try { - - RootNodeChildLoador loador = new RootNodeChildLoador(source.canReadData(), true); - ObserveNode node = new ObserveNode(String.class, "Root node", null, loador, false); - - DefaultTreeModel model = createModel(node); - node.populateChilds(getBridge(), provider); - return model; - - } finally { - - provider.setCreating(false); - - } - } - - public DefaultTreeModel createModel(JAXXContext context, - DataSelectionModel dataModel, - ObserveSwingDataSource source) { - - setDataSource(source); - context.setContextValue(dataModel); - - if (log.isDebugEnabled()) { - log.debug("create tree model " + this); - } - - ObserveDataProvider provider = getDataProvider(); - provider.setSelectionModel(dataModel); - provider.setCreating(true); - - if (getTreeCellRenderer() != null) { - getTreeCellRenderer().setDataProvider(provider); - } - - try { - - RootNodeChildLoador loador = getChildLoador(RootNodeChildLoador.class); - loador.setAddData(dataModel.isUseData()); - loador.setAddReferentiel(dataModel.isUseReferentiel()); - ObserveNode node = new ObserveNode(String.class, "Root node", loador, false); - - DefaultTreeModel model = createModel(node); - loadAllNodes(node, provider); - return model; - - } finally { - - provider.setCreating(false); - - } - - } - - /** - * Charge dans l'ui un nouveau modèle de navigation. - * - * <b>Note:</b> cette méthode doit être appelée après tout rechargement de - * modèle de naivgation. - * - * @param source la source de données - */ - public void loadNavigationUI(ObserveSwingDataSource source) { - - ObserveNode.count = 0; - - // propagate ui in observe bridge to control which nodes can be loads - // from ui state - getBridge().setUi(getUI()); - - // build navigation model - createModel(source); - - // select initial node - selectInitialNode(); - - getUI().setVisible(true); - } - - /** - * Nettoye des ui tout ce qui concerne un modèle de navigation. - * - * <b>Note:</b> cette méthode doit être appelée avant tout rechargement de - * modèle de naivgation. - * - * @param mainUI l'ui principale - */ - public void cleanNavigationUI(ObserveMainUI mainUI) { - - // invalidate provider - setDataSource(null); - - // reset content uis - mainUI.getContentLayout().reset(mainUI.getContent()); - - // clean messages - mainUI.getContextValue(SwingValidatorMessageTableModel.class).clear(); - - // clean tree model - - JTree tree = getUI(); - - // remove tree from bridge to disable propagation of any node - getBridge().setUi(null); - - ObserveNode root = getBridge().getRoot(); - root.removeAllChildren(); - createEmptyModel(); - - // no tree navigation view - tree.setVisible(false); - } - - public void selectOpenNode(Class<?> type) { - - DataContext context = ObserveSwingApplicationContext.get().getDataContext(); - - String[] ids = context.getOpenIds(type); - - if (log.isDebugEnabled()) { - log.debug("using open ids = " + Arrays.toString(ids)); - } - if (ids == null) { - - // rien n'est ouvert, rien à selectionner - return; - } - - selectNode(ids); - } - - /** - * Sélectionne le noeud dans l'arbre de navigation. - * - * <b>Note:</b> cette méthode doit être appelée après un rechargement du - * modèle de navigation. - * - */ - public void selectInitialNode() { - - if (log.isDebugEnabled()) { - log.debug("Will select initial node..."); - } - DataContext context = ObserveSwingApplicationContext.get().getDataContext(); - - String[] path; - - JTree tree = getUI(); - - List<String> selectedIds = ObserveSwingApplicationContext.get().getNodesToReselect(); - if (CollectionUtils.isNotEmpty(selectedIds)) { - if (log.isDebugEnabled()) { - log.debug("will select previous ids " + selectedIds); - } - path = selectedIds.toArray(new String[selectedIds.size()]); - } else { - - // on trouve le meilleur noeud a selectionner. - - String id = context.getHigherOpenId(); - - if (id != null) { - - // on se positionne sur la donnée la plus haute ouverte - path = context.getOpenIds(); - if (log.isDebugEnabled()) { - log.debug("will select open ids " + Arrays.toString(path)); - } - } else { - - // on selectionne le premier noeud de $root - - ObserveNode node = (ObserveNode) tree.getModel().getRoot(); - if (!node.isLeaf()) { - node = node.getFirstChild(); - } - path = new String[]{node.getId()}; - if (log.isDebugEnabled()) { - log.debug("will select first program " + Arrays.toString(path)); - } - } - } - - if (log.isDebugEnabled()) { - log.debug("Selected path : " + Arrays.toString(path)); - } - - try { - - selectNode(path); - } finally { - - // nettoyage du context - ObserveSwingApplicationContext.get().setNodesToReselect(null); - } - - // navigation tree should acquire focus - tree.requestFocus(); - } - - @Override - public void selectNode(String... path) { - long count = ObserveNode.count; - if (log.isDebugEnabled()) { - log.debug("Will select path : " + Arrays.toString(path)); - } - getBridge().setPathToSelect(path); - try { - super.selectNode(path); - } finally { - getBridge().setPathToSelect(); - if (log.isInfoEnabled()) { - log.info("Creates " + (ObserveNode.count - count) + " nodes to select path " + Arrays.toString(path)); - } - } - } - - public ObserveNode addUnsavedNode(ObserveNode parentNode, Class<?> type) { - - // noeud en mode creation - String label = DecoratorService.getEntityLabel(TREE_NODE_PREFIX, type) + ".unsaved"; - ObserveNode result = new ObserveNode(type, null, label, null, false); - insertNode(parentNode, result); - - // refresh parent node (render of parent can have changed) - refreshNode(parentNode, true); - - // Fix bug (if no child in parent node, it will not expand...) - getUI().fireTreeExpanded(new TreePath(result.getPath())); - - createUnsaved = true; - - try { - // Select new node - selectNode(result); - } finally { - createUnsaved = false; - } - - return result; - } - - public <E extends IdDto> ObserveNode addOpenable(ObserveNode parentNode, E bean) { - - ReferenceBinderEngine referenceBinderEngine = ObserveSwingApplicationContext.get().getReferenceBinderEngine(); - ReferentialLocale referentialLocale = ObserveSwingApplicationContext.get().getDecoratorService().getReferentialLocale(); - if (bean instanceof TripSeineDto) { - - DataReference<TripSeineDto> ref = referenceBinderEngine.transformDataDtoToReference(referentialLocale, (TripSeineDto) bean); - return addTripSeine(parentNode, ref); - - } else if (bean instanceof TripLonglineDto) { - - DataReference<TripLonglineDto> ref = referenceBinderEngine.transformDataDtoToReference(referentialLocale, (TripLonglineDto) bean); - return addTripLongline(parentNode, ref); - - } else if (bean instanceof RouteDto) { - - DataReference<RouteDto> ref = referenceBinderEngine.transformDataDtoToReference(referentialLocale, (RouteDto) bean); - return addRoute(parentNode, ref); - - } else if (bean instanceof ActivitySeineDto) { - - DataReference<ActivitySeineDto> ref = referenceBinderEngine.transformDataDtoToReference(referentialLocale, (ActivitySeineDto) bean); - return addActivitySeine(parentNode, ref); - - } else if (bean instanceof ActivityLonglineDto) { - - DataReference<ActivityLonglineDto> ref = referenceBinderEngine.transformDataDtoToReference(referentialLocale, (ActivityLonglineDto) bean); - return addActivityLongline(parentNode, ref); - - } - throw new IllegalStateException("Can not come here!"); - } - - public ObserveNode addTripSeine(ObserveNode parentNode, DataReference<TripSeineDto> bean) { - ProgramSeineNodeChildLoador loador = - getChildLoador(ProgramSeineNodeChildLoador.class); - ObserveNode result = loador.createNode(bean, dataProvider); - insertNode(parentNode, result); - return result; - } - - public ObserveNode addTripLongline(ObserveNode parentNode, DataReference<TripLonglineDto> bean) { - ProgramLonglineNodeChildLoador loador = - getChildLoador(ProgramLonglineNodeChildLoador.class); - ObserveNode result = loador.createNode(bean, dataProvider); - insertNode(parentNode, result); - return result; - } - - public ObserveNode addSimpleTrip(ObserveNode parentNode, DataReference<?> bean) { - ObserveNode result; - - if (bean.getType().isAssignableFrom(TripSeineDto.class)) { - - ProgramSeineNodeChildLoador loador = getChildLoador(ProgramSeineNodeChildLoador.class); - boolean addChilds = loador.isAddChilds(); - loador.setAddChilds(false); - try { - result = loador.createNode((DataReference<TripSeineDto>) bean, dataProvider); - insertNode(parentNode, result); - } finally { - loador.setAddChilds(addChilds); - } - } else { - - ProgramLonglineNodeChildLoador loador = getChildLoador(ProgramLonglineNodeChildLoador.class); - boolean addChilds = loador.isAddChilds(); - loador.setAddChilds(false); - try { - result = loador.createNode((DataReference<TripLonglineDto>) bean, dataProvider); - insertNode(parentNode, result); - } finally { - loador.setAddChilds(addChilds); - } - } - return result; - } - - public ObserveNode addRoute(ObserveNode parentNode, DataReference<RouteDto> bean) { - RoutesNodeChildLoador loador = - getChildLoador(RoutesNodeChildLoador.class); - ObserveNode result = loador.createNode(bean, dataProvider); - insertNode(parentNode, result); - return result; - } - - public ObserveNode addActivitySeine(ObserveNode parentNode, DataReference<ActivitySeineDto> bean) { - ActivitySeinesNodeChildLoador loador = - getChildLoador(ActivitySeinesNodeChildLoador.class); - ObserveNode result = loador.createNode(bean, dataProvider); - insertNode(parentNode, result); - return result; - } - - public ObserveNode addActivityLongline(ObserveNode parentNode, DataReference<ActivityLonglineDto> bean) { - ActivityLonglinesNodeChildLoador loador = - getChildLoador(ActivityLonglinesNodeChildLoador.class); - ObserveNode result = loador.createNode(bean, dataProvider); - insertNode(parentNode, result); - return result; - } - - public ObserveNode addFloatingObject(ObserveNode parentNode, DataReference<FloatingObjectDto> bean) { - ActivitySeineNodeChildLoador loador = - getChildLoador(ActivitySeineNodeChildLoador.class); - ObserveNode result = loador.createNode(bean, dataProvider); - insertNode(parentNode, result); - return result; - } - - public ObserveNode addSetSeine(ObserveNode parentNode, DataReference<SetSeineDto> bean) { - ActivitySeineNodeChildLoador loador = - getChildLoador(ActivitySeineNodeChildLoador.class); - ObserveNode result = loador.createSetNode(bean); - insertNode(parentNode, result); - return result; - } - - public ObserveNode addSetLongline(ObserveNode parentNode, DataReference<SetLonglineDto> bean) { - ActivityLonglineNodeChildLoador loador = - getChildLoador(ActivityLonglineNodeChildLoador.class); - ObserveNode result = loador.createSetNode(bean); - insertNode(parentNode, result); - return result; - } - - public ObserveNode addProgram(ReferentialReference<ProgramDto> bean) { - - Set<ReferentialReference<ProgramDto>> programs = getDataProvider().getDataSource().getReferentialReferences(ProgramDto.class); - List<ReferentialReference<ProgramDto>> data = Lists.newArrayList(programs); - int newIndex = 0; - if (CollectionUtils.isNotEmpty(data)) { - sortPrograms(data); -// Programs.sort(data); - newIndex = data.indexOf(bean); - } - RootNodeChildLoador loador = getChildLoador(RootNodeChildLoador.class); - ObserveNode result = loador.createNode(bean, dataProvider); - insertNode(getRootNode(), result, newIndex); - return result; - } - - public void removeProgram(String programId) { - ObserveNode rootNode = getRootNode(); - ObserveNode result = rootNode.getChild(programId, getBridge(), dataProvider); - Preconditions.checkNotNull(result, "Could not find program node with id: " + programId); - removeNode(result); - } - - public void updateProgram(ProgramDto bean) { - ObserveNode rootNode = getRootNode(); - ObserveNode result = rootNode.getChild(bean.getId(), getBridge(), dataProvider); - Preconditions.checkNotNull(result, "Could not find program node with id: " + bean.getId()); - reloadNode(result, false); - refreshNode(result, false); - } - - public ObserveNode addProgram(Set<ReferentialReference<ProgramDto>> existingPrograms, ReferentialReference<ProgramDto> bean) { - - List<ReferentialReference<ProgramDto>> data = Lists.newArrayList(existingPrograms); - data.add(bean); - int newIndex = 0; - if (CollectionUtils.isNotEmpty(data)) { - sortPrograms(data); - newIndex = data.indexOf(bean); - } - RootNodeChildLoador loador = getChildLoador(RootNodeChildLoador.class); - ObserveNode result = loador.createNode(bean, dataProvider); - insertNode(getRootNode(), result, newIndex); - return result; - } - - public void removeTrip(ReferentialReference<ProgramDto> program, DataReference trip) { - - ObserveNode rootNode = getRootNode(); - ObserveNode programNode = rootNode.getChild(program.getId(), getBridge(), dataProvider); - Preconditions.checkNotNull(programNode, "Could not find program node with id: " + program); - ObserveNode tripNode = programNode.getChild(trip.getId(), getBridge(), dataProvider); - Preconditions.checkNotNull(tripNode, "Could not find program node with id: " + trip); - removeNode(tripNode); - - if (programNode.isLeaf()) { - removeProgram(program.getId()); - } - } - - public void reloadSelectedNode(boolean refreshFromParent, boolean refreshChilds) { - ObserveNode node = getSelectedNode(); - ((AbstrctReferenceNodeSupport) node).setReloadEntity(true); - - if (refreshFromParent) { - node = node.getParent(); - } - refreshNode(node, refreshChilds); - } - - public void reloadNode(ObserveNode node, boolean refreshChilds) { - ((AbstrctReferenceNodeSupport) node).setReloadEntity(true); - refreshNode(node, refreshChilds); - } - - public boolean isCreateUnsaved() { - return createUnsaved; - } - - @Override - protected ObserveDataProvider getDataProvider() { - ObserveDataProvider provider = (ObserveDataProvider) super.getDataProvider(); - if (provider == null) { - ObserveSwingDataSource source = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); - if (source != null) { - provider = new ObserveDataProvider(source); - setDataProvider(provider); - } - } - return provider; - } - - @Override - protected ObserveTreeBridge getBridge() { - return (ObserveTreeBridge) super.getBridge(); - } - - void setDataSource(ObserveSwingDataSource source) { - NavDataProvider provider = null; - if (source != null) { - provider = new ObserveDataProvider(source); - } - setDataProvider(provider); - } - - public void reloadNodeSubTree(ObserveNode node, boolean expandNode) { - Preconditions.checkNotNull(node, "node is null, we can not reload its structure"); - ObserveTreeBridge bridge = getBridge(); - - // 1. Let's clear node structure - while (node.getChildCount() > 0) { - removeNode(node.getFirstChild()); - } - - // 2. We add the node and its parent to the select path in order to force the call to the child loadors when populating the node. - // see fr.ird.observe.ui.tree.ObserveTreeBridge.canLoadChild - bridge.setPathToSelect(node.getId(), node.getParent().getId()); - - try { - - // 3. Let's re-generate node's children by populating the node : this will call the child loaders. - node.populateNode(bridge, getDataProvider(), true); - - } finally { - // Clean the path to select - bridge.setPathToSelect(); - } - - if (expandNode) { - - // Fix bug (if no child in parent node, it will not expand...) - getUI().fireTreeExpanded(new TreePath(node.getPath())); - - } - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ProgramLonglineNode.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ProgramLonglineNode.java deleted file mode 100644 index 9aaaf86..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ProgramLonglineNode.java +++ /dev/null @@ -1,57 +0,0 @@ -package fr.ird.observe.ui.tree; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.constants.GearType; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.service.ReferentialService; -import fr.ird.observe.ui.tree.loadors.ProgramLonglineNodeChildLoador; - -/** - * Created on 4/9/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 4.0 - */ -public class ProgramLonglineNode extends ReferentialReferenceNodeSupport<ProgramDto> { - - private static final long serialVersionUID = 1L; - - public ProgramLonglineNode(ReferentialReference<ProgramDto> entity) { - super(ProgramDto.class, - entity, - ((GearType) entity.getPropertyValue(ProgramDto.PROPERTY_GEAR_TYPE)).name(), - ObserveTreeHelper.getChildLoador(ProgramLonglineNodeChildLoador.class)); - // FIXME kmorin 20151012 pkoi refaire un setEntity alors qu'il est fait dans le super ? - setEntity(entity); - } - - @Override - protected ReferentialReference<ProgramDto> fetchEntity() { - ReferentialService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newReferentialService(); - ReferentialReference<ProgramDto> referenceDto = service.loadReference(ProgramDto.class, getId()); - return referenceDto; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ProgramSeineNode.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ProgramSeineNode.java deleted file mode 100644 index 94cff73..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ProgramSeineNode.java +++ /dev/null @@ -1,56 +0,0 @@ -package fr.ird.observe.ui.tree; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.constants.GearType; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.services.service.ReferentialService; -import fr.ird.observe.ui.tree.loadors.ProgramSeineNodeChildLoador; - -/** - * Created on 4/9/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 4.0 - */ -public class ProgramSeineNode extends ReferentialReferenceNodeSupport<ProgramDto> { - - private static final long serialVersionUID = 1L; - - public ProgramSeineNode(ReferentialReference<ProgramDto> entity) { - super(ProgramDto.class, - entity, - ((GearType) entity.getPropertyValue(ProgramDto.PROPERTY_GEAR_TYPE)).name(), - ObserveTreeHelper.getChildLoador(ProgramSeineNodeChildLoador.class)); - } - - @Override - protected ReferentialReference<ProgramDto> fetchEntity() { - ReferentialService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newReferentialService(); - ReferentialReference<ProgramDto> referenceDto = service.loadReference(ProgramDto.class, getId()); - return referenceDto; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ReferentialReferenceNodeSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ReferentialReferenceNodeSupport.java deleted file mode 100644 index f68d7f2..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/ReferentialReferenceNodeSupport.java +++ /dev/null @@ -1,84 +0,0 @@ -package fr.ird.observe.ui.tree; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.tree.loadors.AbstractNodeChildLoador; -import jaxx.runtime.swing.nav.NavBridge; -import jaxx.runtime.swing.nav.NavDataProvider; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.tree.DefaultTreeModel; - -/** - * Created on 4/9/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 4.0 - */ -public abstract class ReferentialReferenceNodeSupport<E extends ReferentialDto> extends AbstrctReferenceNodeSupport<E, ReferentialReference<E>> { - - /** Logger. */ - private static final Log log = LogFactory.getLog(ReferentialReferenceNodeSupport.class); - - private static final long serialVersionUID = 1L; - - protected ReferentialReferenceNodeSupport(Class<E> internalClass, ReferentialReference<E> entity) { - super(internalClass, entity, null); - } - - protected ReferentialReferenceNodeSupport(Class<E> type, ReferentialReference<E> entity, AbstractNodeChildLoador<?, ?> childLoador) { - super(type, entity, null, childLoador); - } - - protected ReferentialReferenceNodeSupport(Class<E> type, ReferentialReference<E> entity, String context, AbstractNodeChildLoador<?, ?> childLoador) { - super(type, entity, context, childLoador); - } - - @Override - public void populateNode(NavBridge<DefaultTreeModel, ObserveNode> bridge, - NavDataProvider provider, - boolean populateChilds) { - - - try { - super.populateNode(bridge, provider, populateChilds); - } finally { - reloadEntity = false; - } - - if (provider != null && id != null) { - - if (entity == null) { - - loadEntity((ObserveDataProvider) provider); - - } - - } - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/RouteSeineNode.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/RouteSeineNode.java deleted file mode 100644 index a82a6cd..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/RouteSeineNode.java +++ /dev/null @@ -1,50 +0,0 @@ -package fr.ird.observe.ui.tree; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.services.service.seine.RouteService; - -/** - * Created on 4/9/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 4.0 - */ -public class RouteSeineNode extends DataReferenceNodeSupport<RouteDto> { - - private static final long serialVersionUID = 1L; - - public RouteSeineNode(DataReference<RouteDto> entity) { - super(RouteDto.class, entity); - } - - @Override - protected DataReference<RouteDto> fetchEntity() { - RouteService routeService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newRouteService(); - DataReference<RouteDto> referenceDto = routeService.loadReferenceToRead(getId()); - return referenceDto; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/SetLonglineNode.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/SetLonglineNode.java deleted file mode 100644 index 2cdd402..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/SetLonglineNode.java +++ /dev/null @@ -1,52 +0,0 @@ -package fr.ird.observe.ui.tree; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.longline.SetLonglineDto; -import fr.ird.observe.services.service.longline.SetLonglineService; -import fr.ird.observe.ui.tree.loadors.SetLonglineNodeChildLoador; - -/** - * Created on 4/9/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 4.0 - */ -public class SetLonglineNode extends DataReferenceNodeSupport<SetLonglineDto> { - - private static final long serialVersionUID = 1L; - - public SetLonglineNode(DataReference<SetLonglineDto> entity) { - super(SetLonglineDto.class, entity, ObserveTreeHelper.getChildLoador(SetLonglineNodeChildLoador.class)); - } - - @Override - protected DataReference<SetLonglineDto> fetchEntity() { - SetLonglineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newSetLonglineService(); - DataReference<SetLonglineDto> referenceDto = service.loadReferenceToRead(getId()); - return referenceDto; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/SetSeineNode.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/SetSeineNode.java deleted file mode 100644 index e29da3b..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/SetSeineNode.java +++ /dev/null @@ -1,52 +0,0 @@ -package fr.ird.observe.ui.tree; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.seine.SetSeineDto; -import fr.ird.observe.services.service.seine.SetSeineService; -import fr.ird.observe.ui.tree.loadors.SetSeineNodeChildLoador; - -/** - * Created on 4/9/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 4.0 - */ -public class SetSeineNode extends DataReferenceNodeSupport<SetSeineDto> { - - private static final long serialVersionUID = 1L; - - public SetSeineNode(DataReference<SetSeineDto> entity) { - super(SetSeineDto.class, entity, ObserveTreeHelper.getChildLoador(SetSeineNodeChildLoador.class)); - } - - @Override - protected DataReference<SetSeineDto> fetchEntity() { - SetSeineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newSetSeineService(); - DataReference<SetSeineDto> referenceDto = service.loadReferenceToRead(getId()); - return referenceDto; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/TripLonglineNode.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/TripLonglineNode.java deleted file mode 100644 index afafe9f..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/TripLonglineNode.java +++ /dev/null @@ -1,51 +0,0 @@ -package fr.ird.observe.ui.tree; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.service.longline.TripLonglineService; - -/** - * Created on 4/9/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 4.0 - */ -public class TripLonglineNode extends DataReferenceNodeSupport<TripLonglineDto> { - - private static final long serialVersionUID = 1L; - - public TripLonglineNode(DataReference<TripLonglineDto> entity) { - super(TripLonglineDto.class, entity); - } - - @Override - protected DataReference<TripLonglineDto> fetchEntity() { - TripLonglineService tripLonglineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripLonglineService(); - DataReference<TripLonglineDto> referenceDto = tripLonglineService.loadReferenceToRead(getId()); - return referenceDto; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/TripSeineNode.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/TripSeineNode.java deleted file mode 100644 index d7370cd..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/TripSeineNode.java +++ /dev/null @@ -1,51 +0,0 @@ -package fr.ird.observe.ui.tree; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.services.service.seine.TripSeineService; - -/** - * Created on 4/9/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 4.0 - */ -public class TripSeineNode extends DataReferenceNodeSupport<TripSeineDto> { - - private static final long serialVersionUID = 1L; - - public TripSeineNode(DataReference<TripSeineDto> entity) { - super(TripSeineDto.class, entity); - } - - - @Override - protected DataReference<TripSeineDto> fetchEntity() { - TripSeineService tripSeineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripSeineService(); - DataReference<TripSeineDto> referenceDto = tripSeineService.loadReferenceToRead(getId()); - return referenceDto; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/actions/ChangeActivityRouteActionListener.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/actions/ChangeActivityRouteActionListener.java deleted file mode 100644 index 15c8cff..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/actions/ChangeActivityRouteActionListener.java +++ /dev/null @@ -1,89 +0,0 @@ -package fr.ird.observe.ui.tree.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - - -import fr.ird.observe.ObserveOpenDataManager; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.services.service.seine.ActivitySeineService; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Created on 1/9/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.11 - */ -public class ChangeActivityRouteActionListener extends NodeChangeActionListener { - - /** Logger. */ - private static final Log log = LogFactory.getLog(ChangeActivityRouteActionListener.class); - - public ChangeActivityRouteActionListener(ObserveTreeHelper treeHelper, - ObserveSwingDataSource dataSource, - String activityId, - String routeId) { - super(treeHelper, dataSource, activityId, routeId); - } - - @Override - protected void closeNode(String activityId) { - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ObserveOpenDataManager openDataManager = applicationContext.getOpenDataManager(); - - if (openDataManager.isOpenActivitySeine(activityId)) { - openDataManager.closeActivitySeine(activityId); - } - } - - @Override - protected ObserveNode getParentNode(ObserveNode node) { - return node.getParent().getParent(); - } - - @Override - protected ObserveNode getNewParentNode(ObserveNode grandParentNode, String parentNodeId) { - ObserveNode routeNode = getTreeHelper().getChild(grandParentNode, parentNodeId); - String activitiesNodeId = DecoratorService.getPropertyLabel(ObserveTreeHelper.TREE_NODE_PREFIX, - RouteDto.PROPERTY_ACTIVITY_SEINE); - ObserveNode activities = getTreeHelper().getChild(routeNode, activitiesNodeId); - return activities; - } - - @Override - protected int moveNodeToParent(String nodeId, String parentNodeId, String oldParentNodeId) { - int position; - - ActivitySeineService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivitySeineService(); - position = service.moveActivitySeineToRoute(nodeId, parentNodeId); - - return position; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/actions/ChangeActivityTripActionListener.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/actions/ChangeActivityTripActionListener.java deleted file mode 100644 index d8cc75f..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/actions/ChangeActivityTripActionListener.java +++ /dev/null @@ -1,91 +0,0 @@ -package fr.ird.observe.ui.tree.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - - -import fr.ird.observe.ObserveOpenDataManager; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.service.longline.ActivityLonglineService; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Created on 1/9/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.11 - */ -public class ChangeActivityTripActionListener extends NodeChangeActionListener { - - /** Logger. */ - private static final Log log = LogFactory.getLog(ChangeActivityTripActionListener.class); - - public ChangeActivityTripActionListener(ObserveTreeHelper treeHelper, - ObserveSwingDataSource dataSource, - String activityId, - String tripLonglineId) { - super(treeHelper, dataSource, activityId, tripLonglineId); - } - - @Override - protected void closeNode(String activityId) { - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ObserveOpenDataManager openDataManager = applicationContext.getOpenDataManager(); - - if (openDataManager.isOpenActivityLongline(activityId)) { - openDataManager.closeActivityLongline(activityId); - } - } - - @Override - protected ObserveNode getParentNode(ObserveNode node) { - return node.getParent().getParent(); - } - - @Override - protected ObserveNode getNewParentNode(ObserveNode grandParentNode, String parentNodeId) { - ObserveNode tripLonglineNode = getTreeHelper().getChild(grandParentNode, parentNodeId); - String activitiesNodeId = DecoratorService.getPropertyLabel(ObserveTreeHelper.TREE_NODE_PREFIX, - TripLonglineDto.PROPERTY_ACTIVITY_LONGLINE); - ObserveNode activities = getTreeHelper().getChild(tripLonglineNode, activitiesNodeId); - return activities; - } - - @Override - protected int moveNodeToParent(String nodeId, String parentNodeId, String oldParentNodeId) { - int position; - - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - - ActivityLonglineService service = applicationContext.getMainDataSourceServicesProvider().newActivityLonglineService(); - position = service.moveActivityLonglineToTripLongline(nodeId, parentNodeId); - - return position; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/actions/ChangeRouteTripActionListener.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/actions/ChangeRouteTripActionListener.java deleted file mode 100644 index 69923d8..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/actions/ChangeRouteTripActionListener.java +++ /dev/null @@ -1,88 +0,0 @@ -package fr.ird.observe.ui.tree.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - - -import fr.ird.observe.ObserveOpenDataManager; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.services.service.seine.RouteService; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Created on 1/9/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.11 - */ -public class ChangeRouteTripActionListener extends NodeChangeActionListener { - - /** Logger. */ - private static final Log log = LogFactory.getLog(ChangeRouteTripActionListener.class); - - public ChangeRouteTripActionListener(ObserveTreeHelper treeHelper, - ObserveSwingDataSource dataSource, - String routeId, - String tripId) { - super(treeHelper, dataSource, routeId, tripId); - } - - @Override - protected void closeNode(String routeId) { - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ObserveOpenDataManager openDataManager = applicationContext.getOpenDataManager(); - - if (openDataManager.isOpenRoute(routeId)) { - openDataManager.closeRoute(routeId); - } - } - - @Override - protected ObserveNode getParentNode(ObserveNode node) { - return node.getParent().getParent(); - } - - @Override - protected ObserveNode getNewParentNode(ObserveNode grandParentNode, String parentNodeId) { - ObserveNode tripNode = getTreeHelper().getChild(grandParentNode, parentNodeId); - String routesNodeId = DecoratorService.getPropertyLabel(ObserveTreeHelper.TREE_NODE_PREFIX, - TripSeineDto.PROPERTY_ROUTE); - ObserveNode routesNode = getTreeHelper().getChild(tripNode, routesNodeId); - return routesNode; - } - - @Override - protected int moveNodeToParent(String nodeId, String parentNodeId, String oldParentNodeId) { - int position; - - RouteService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newRouteService(); - position = service.moveRouteToTripSeine(nodeId, parentNodeId); - - return position; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/actions/ChangeTripProgramActionListener.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/actions/ChangeTripProgramActionListener.java deleted file mode 100644 index 95686da..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/actions/ChangeTripProgramActionListener.java +++ /dev/null @@ -1,95 +0,0 @@ -package fr.ird.observe.ui.tree.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - - -import fr.ird.observe.ObserveOpenDataManager; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.ObserveServicesProvider; -import fr.ird.observe.services.dto.IdDtos; -import fr.ird.observe.services.service.longline.TripLonglineService; -import fr.ird.observe.services.service.seine.TripSeineService; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -/** - * Created on 1/9/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.11 - */ -public class ChangeTripProgramActionListener extends NodeChangeActionListener { - - /** Logger. */ - private static final Log log = LogFactory.getLog(ChangeTripProgramActionListener.class); - - public ChangeTripProgramActionListener(ObserveTreeHelper treeHelper, - ObserveSwingDataSource dataSource, - String tripId, - String programId) { - super(treeHelper, dataSource, tripId, programId); - } - - @Override - protected void closeNode(String tripId) { - // Don't do anything : trip should stay open when being transferred - } - - @Override - protected ObserveNode getParentNode(ObserveNode node) { - return node.getParent(); - } - - @Override - protected ObserveNode getNewParentNode(ObserveNode grandParentNode, String parentNodeId) { - return getTreeHelper().getChild(grandParentNode, parentNodeId); - } - - @Override - protected int moveNodeToParent(String nodeId, String parentNodeId, String oldParentNodeId) { - int position; - - ObserveSwingApplicationContext applicationContext = ObserveSwingApplicationContext.get(); - ObserveServicesProvider servicesProvider = applicationContext.getMainDataSourceServicesProvider(); - if (IdDtos.isTripLonglineId(nodeId)) { - TripLonglineService service = servicesProvider.newTripLonglineService(); - position = service.moveTripLonglineToProgram(nodeId, parentNodeId); - - } else { - TripSeineService service = servicesProvider.newTripSeineService(); - position = service.moveTripSeineToProgram(nodeId, parentNodeId); - } - - // Close old program and open new program - ObserveOpenDataManager openDataManager = applicationContext.getOpenDataManager(); - if (openDataManager.isOpen(nodeId)) { - openDataManager.closeProgram(oldParentNodeId); - openDataManager.openProgram(parentNodeId); - } - - return position; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/actions/NodeChangeActionListener.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/actions/NodeChangeActionListener.java deleted file mode 100644 index fd6ce8c..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/actions/NodeChangeActionListener.java +++ /dev/null @@ -1,107 +0,0 @@ -package fr.ird.observe.ui.tree.actions; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - - -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; - -/** - * Created on 1/9/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.11 - */ -public abstract class NodeChangeActionListener implements ActionListener { - - /** Logger. */ - private static final Log log = LogFactory.getLog(NodeChangeActionListener.class); - - private final String nodeId; - - private final String parentNodeId; - - private final ObserveTreeHelper treeHelper; - - private final ObserveSwingDataSource dataSource; - - public NodeChangeActionListener(ObserveTreeHelper treeHelper, - ObserveSwingDataSource dataSource, - String nodeId, - String parentNodeId) { - this.nodeId = nodeId; - this.parentNodeId = parentNodeId; - this.treeHelper = treeHelper; - this.dataSource = dataSource; - } - - @Override - public void actionPerformed(ActionEvent event) { - - ObserveNode node = treeHelper.getSelectedNode(); - ObserveNode oldParentNode = getParentNode(node); - ObserveNode grandParentNode = oldParentNode.getParent(); - ObserveNode newParentNode = getNewParentNode(grandParentNode, parentNodeId); - - closeNode(node.getId()); - - int position = moveNodeToParent(nodeId, parentNodeId, oldParentNode.getId()); - - treeHelper.selectNode(newParentNode); - - treeHelper.removeNode(node); - - ObserveNode newNode = treeHelper.getChild(newParentNode, nodeId); - - if (newNode == null) { - - // create it - if (log.isInfoEnabled()) { - log.info("Insert node: "); - } - treeHelper.insertNode(newParentNode, node, position); - newNode = node; - } - - treeHelper.selectNode(newNode); - - } - - protected ObserveTreeHelper getTreeHelper() { - return treeHelper; - } - - protected abstract void closeNode(String nodeId); - - protected abstract ObserveNode getParentNode(ObserveNode node); - - protected abstract ObserveNode getNewParentNode(ObserveNode grandParentNode, String parentNodeId); - - protected abstract int moveNodeToParent(String nodeId, String parentNodeId, String oldParentNodeId); -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/AbstractDataReferenceChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/AbstractDataReferenceChildLoador.java deleted file mode 100644 index 1fee084..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/AbstractDataReferenceChildLoador.java +++ /dev/null @@ -1,39 +0,0 @@ -package fr.ird.observe.ui.tree.loadors; - -/*- - * #%L - * ObServe :: Application Swing - * %% - * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.DataDto; -import fr.ird.observe.services.dto.DataReference; - -/** - * @author Kevin Morin (Code Lutin) - * @since x.x - */ -public abstract class AbstractDataReferenceChildLoador<O extends DataDto> extends AbstractNodeChildLoador<DataReference<O>, O> { - - private static final long serialVersionUID = 1L; - - protected AbstractDataReferenceChildLoador(Class<O> beanType) { - super(beanType); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/AbstractNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/AbstractNodeChildLoador.java deleted file mode 100644 index 2d0ae76..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/AbstractNodeChildLoador.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.tree.loadors; - -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.ui.storage.tabs.DataSelectionModel; -import fr.ird.observe.ui.tree.ObserveDataProvider; -import fr.ird.observe.ui.tree.ObserveNode; -import jaxx.runtime.swing.nav.NavDataProvider; -import jaxx.runtime.swing.nav.tree.NavTreeNodeChildLoador; - -/** - * Un object pour charger les fils d'un noeud. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public abstract class AbstractNodeChildLoador<T, O> extends NavTreeNodeChildLoador<T, O, ObserveNode> { - - private static final long serialVersionUID = 1L; - - protected AbstractNodeChildLoador(Class<O> beanType) { - super(beanType); - } - - protected ObserveSwingDataSource getDataSource(NavDataProvider dataProvider) { - ObserveDataProvider provider = (ObserveDataProvider) dataProvider; - ObserveSwingDataSource result = provider.getDataSource(); - return result; - } - - protected DataSelectionModel getSelectionModel(NavDataProvider dataProvider) { - ObserveDataProvider provider = (ObserveDataProvider) dataProvider; - DataSelectionModel result = provider.getSelectionModel(); - return result; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ActivityLonglineNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ActivityLonglineNodeChildLoador.java deleted file mode 100644 index 77cf63d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ActivityLonglineNodeChildLoador.java +++ /dev/null @@ -1,121 +0,0 @@ -package fr.ird.observe.ui.tree.loadors; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.longline.ActivityLonglineDto; -import fr.ird.observe.services.dto.longline.ActivityLonglineEncounterDto; -import fr.ird.observe.services.dto.longline.ActivityLonglineSensorUsedDto; -import fr.ird.observe.services.dto.longline.SetLonglineDto; -import fr.ird.observe.ui.tree.ActivityLonglineNode; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.ui.tree.SetLonglineNode; -import jaxx.runtime.swing.nav.NavDataProvider; -import jaxx.runtime.swing.nav.tree.NavTreeBridge; - -import java.util.ArrayList; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; - -/** - * Created on 8/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class ActivityLonglineNodeChildLoador extends AbstractNodeChildLoador<String, String> { - - private static final long serialVersionUID = 1L; - - static { - n("observe.tree.encounter"); - n("observe.tree.sensorUsed"); - n("observe.tree.setLongline"); - } - - public ActivityLonglineNodeChildLoador() { - super(String.class); - } - - @Override - public void loadChilds(NavTreeBridge<ObserveNode> model, - ObserveNode parentNode, - NavDataProvider dataProvider) throws Exception { - - ObserveNode containerNode = parentNode.getContainerNode(); - - if (containerNode == null) { - throw new IllegalStateException("Could not find containerNode of " + parentNode); - } - - { - - DataReference<ActivityLonglineDto> activityLonglineRef = ((ActivityLonglineNode) parentNode).getEntity(); - - DataReference<SetLonglineDto> setLonglineRef = (DataReference<SetLonglineDto>) activityLonglineRef.getPropertyValue(ActivityLonglineDto.PROPERTY_SET_LONGLINE); - if (setLonglineRef != null) { - - // si set present, ajout d'un noeud - ObserveNode child = createSetNode(setLonglineRef); - parentNode.add(child); - - } - } - - // ajout des autres fils avant la calée - super.loadChilds(model, parentNode, dataProvider); - - } - - @Override - public List<String> getData(Class<?> parentClass, - String parentId, - NavDataProvider dataService) { - - List<String> result = new ArrayList<>(); - result.add(ActivityLonglineEncounterDto.PROPERTY_ENCOUNTER); - result.add(ActivityLonglineSensorUsedDto.PROPERTY_SENSOR_USED); - return result; - - } - - @Override - public ObserveNode createNode(String data, NavDataProvider dataProvider) { - - ObserveNode result = ObserveTreeHelper.createStringNode(data); - return result; - - } - - public ObserveNode createSetNode(DataReference<SetLonglineDto> data) { - if (data == null) { - throw new NullPointerException("Ne peut pas ajouter un objet null"); - } - - ObserveNode child = new SetLonglineNode(data); - return child; - - } -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ActivityLonglinesNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ActivityLonglinesNodeChildLoador.java deleted file mode 100644 index ee93203..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ActivityLonglinesNodeChildLoador.java +++ /dev/null @@ -1,73 +0,0 @@ -package fr.ird.observe.ui.tree.loadors; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.DataReferenceSet; -import fr.ird.observe.services.dto.longline.ActivityLonglineDto; -import fr.ird.observe.services.service.longline.ActivityLonglineService; -import fr.ird.observe.ui.tree.ActivityLonglineNode; -import fr.ird.observe.ui.tree.ObserveNode; -import jaxx.runtime.swing.nav.NavDataProvider; - -import java.util.ArrayList; -import java.util.List; - -/** - * Created on 8/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class ActivityLonglinesNodeChildLoador extends AbstractDataReferenceChildLoador<ActivityLonglineDto> { - - private static final long serialVersionUID = 1L; - - public ActivityLonglinesNodeChildLoador() { - super(ActivityLonglineDto.class); - } - - @Override - public List<DataReference<ActivityLonglineDto>> getData(Class<?> parentClass, - String parentId, - NavDataProvider dataProvider) throws Exception { - - ActivityLonglineService activityLonglineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivityLonglineService(); - DataReferenceSet<ActivityLonglineDto> activityLonglineByTripLongline = activityLonglineService.getActivityLonglineByTripLongline(parentId); - - return new ArrayList<>(activityLonglineByTripLongline.getReferences()); - - } - - @Override - public ObserveNode createNode(DataReference<ActivityLonglineDto> data, NavDataProvider dataProvider) { - if (data == null) { - throw new NullPointerException("Ne peut pas ajouter un objet null"); - } - - ObserveNode result = new ActivityLonglineNode(data); - return result; - - } -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ActivitySeineNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ActivitySeineNodeChildLoador.java deleted file mode 100644 index e97e964..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ActivitySeineNodeChildLoador.java +++ /dev/null @@ -1,125 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.tree.loadors; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.DataReferenceSet; -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.services.dto.seine.ActivitySeineObservedSystemDto; -import fr.ird.observe.services.dto.seine.FloatingObjectDto; -import fr.ird.observe.services.dto.seine.SetSeineDto; -import fr.ird.observe.services.service.seine.FloatingObjectService; -import fr.ird.observe.ui.tree.ActivitySeineNode; -import fr.ird.observe.ui.tree.FloatingObjectSeineNode; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.ui.tree.SetSeineNode; -import jaxx.runtime.swing.nav.NavDataProvider; -import jaxx.runtime.swing.nav.tree.NavTreeBridge; - -import java.util.ArrayList; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; - -/** - * Le chargeur des noeuds de marees. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ActivitySeineNodeChildLoador extends AbstractDataReferenceChildLoador<FloatingObjectDto> { - - private static final long serialVersionUID = 1L; - - static { - n("observe.common.observedSystem"); - n("observe.tree.setSeine"); - } - - public ActivitySeineNodeChildLoador() { - super(FloatingObjectDto.class); - } - - @Override - public void loadChilds(NavTreeBridge<ObserveNode> model, - ObserveNode parentNode, - NavDataProvider dataProvider) throws Exception { - - ObserveNode containerNode = parentNode.getContainerNode(); - - if (containerNode == null) { - throw new IllegalStateException( - "Could not find containerNode of " + parentNode); - } - - // Creation d'un node systeme observe - ObserveNode child = ObserveTreeHelper.createStringNode(ActivitySeineObservedSystemDto.PROPERTY_OBSERVED_SYSTEM); - - parentNode.add(child); - - DataReference<ActivitySeineDto> activitySeineRef = ((ActivitySeineNode) parentNode).getEntity(); - DataReference<SetSeineDto> setSeineRef = (DataReference<SetSeineDto>) activitySeineRef.getPropertyValue(ActivitySeineDto.PROPERTY_SET_SEINE); - if (setSeineRef != null) { - - // si set present, ajout d'un noeud - child = createSetNode(setSeineRef); - parentNode.add(child); - } - - // ajout des objets flottants - super.loadChilds(model, parentNode, dataProvider); - } - - public ObserveNode createSetNode(DataReference<SetSeineDto> data) { - if (data == null) { - throw new NullPointerException("Ne peut pas ajouter un objet null"); - } - - SetSeineNode child = new SetSeineNode(data); - return child; - - } - - @Override - public ObserveNode createNode(DataReference<FloatingObjectDto> data, NavDataProvider dataProvider) { - if (data == null) { - throw new NullPointerException("Ne peut pas ajouter un objet null"); - } - - FloatingObjectSeineNode result = new FloatingObjectSeineNode(data); - return result; - - } - - @Override - public List<DataReference<FloatingObjectDto>> getData(Class<?> parentClass, - String parentId, - NavDataProvider dataProvider) throws Exception { - - FloatingObjectService service = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newFloatingObjectService(); - DataReferenceSet<FloatingObjectDto> floatingObjectByActivitySeine = service.getFloatingObjectByActivitySeine(parentId); - return new ArrayList<>(floatingObjectByActivitySeine.getReferences()); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ActivitySeinesNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ActivitySeinesNodeChildLoador.java deleted file mode 100644 index 4c0f312..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ActivitySeinesNodeChildLoador.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.tree.loadors; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.DataReferenceSet; -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.services.service.seine.ActivitySeineService; -import fr.ird.observe.ui.tree.ActivitySeineNode; -import fr.ird.observe.ui.tree.ObserveNode; -import jaxx.runtime.swing.nav.NavDataProvider; - -import java.util.ArrayList; -import java.util.List; - -/** - * Le chargeur des noeuds des activités d'une route. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ActivitySeinesNodeChildLoador extends AbstractDataReferenceChildLoador<ActivitySeineDto> { - - private static final long serialVersionUID = 1L; - - public ActivitySeinesNodeChildLoador() { - super(ActivitySeineDto.class); - } - - @Override - public List<DataReference<ActivitySeineDto>> getData(Class<?> parentClass, - String parentId, - NavDataProvider dataProvider) throws Exception { - - ActivitySeineService activitySeineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newActivitySeineService(); - DataReferenceSet<ActivitySeineDto> activitySeineStubByRoute = activitySeineService.getActivitySeineByRoute(parentId); - return new ArrayList<>(activitySeineStubByRoute.getReferences()); - - } - - @Override - public ObserveNode createNode(DataReference<ActivitySeineDto> data, NavDataProvider dataProvider) { - if (data == null) { - throw new NullPointerException("Ne peut pas ajouter un objet null"); - } - - ActivitySeineNode result = new ActivitySeineNode(data); - return result; - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/FloatingObjectNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/FloatingObjectNodeChildLoador.java deleted file mode 100644 index 68c44bb..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/FloatingObjectNodeChildLoador.java +++ /dev/null @@ -1,77 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.tree.loadors; - - -import fr.ird.observe.services.dto.seine.FloatingObjectDto; -import fr.ird.observe.services.dto.seine.FloatingObjectObservedSpeciesDto; -import fr.ird.observe.services.dto.seine.FloatingObjectSchoolEstimateDto; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import jaxx.runtime.swing.nav.NavDataProvider; - -import java.util.ArrayList; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; - -/** - * Le chargeur des noeuds de marees. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class FloatingObjectNodeChildLoador extends AbstractNodeChildLoador<String, String> { - - private static final long serialVersionUID = 1L; - - public FloatingObjectNodeChildLoador() { - super(String.class); - } - - static { - n("observe.tree.objectOperation"); - n("observe.tree.objectSchoolEstimate"); - n("observe.tree.objectObservedSpecies"); - } - - @Override - public List<String> getData(Class<?> parentClass, - String parentId, - NavDataProvider dataService) { - - List<String> result = new ArrayList<>(); - result.add(FloatingObjectDto.PROPERTY_OBJECT_OPERATION); - result.add(FloatingObjectSchoolEstimateDto.PROPERTY_OBJECT_SCHOOL_ESTIMATE); - result.add(FloatingObjectObservedSpeciesDto.PROPERTY_OBJECT_OBSERVED_SPECIES); - return result; - } - - @Override - public ObserveNode createNode(String data, NavDataProvider dataProvider) { - - ObserveNode result = ObserveTreeHelper.createStringNode(data); - return result; - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ProgramLonglineNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ProgramLonglineNodeChildLoador.java deleted file mode 100644 index e1ce20d..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ProgramLonglineNodeChildLoador.java +++ /dev/null @@ -1,145 +0,0 @@ -package fr.ird.observe.ui.tree.loadors; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.DataReferenceSet; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.service.longline.TripLonglineService; -import fr.ird.observe.ui.storage.tabs.DataSelectionModel; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.ui.tree.TripLonglineNode; -import jaxx.runtime.swing.nav.NavDataProvider; -import jaxx.runtime.swing.nav.tree.NavTreeBridge; - -import java.util.Collection; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; - -/** - * Created on 8/28/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class ProgramLonglineNodeChildLoador extends AbstractNodeChildLoador<DataReference<TripLonglineDto>, TripLonglineDto> { - - private static final long serialVersionUID = 1L; - - static { - n("observe.tree.gearUseFeaturesLongline"); - n("observe.tree.activityLongline"); - } - - public ProgramLonglineNodeChildLoador() { - super(TripLonglineDto.class); - } - - protected boolean addChilds; - - @Override - public void loadChilds(NavTreeBridge<ObserveNode> model, - ObserveNode parentNode, - NavDataProvider dataProvider) throws Exception { - - DataSelectionModel selectionModel = getSelectionModel(dataProvider); - addChilds = selectionModel == null; - - try { - super.loadChilds(model, parentNode, dataProvider); - } finally { - addChilds = true; - } - - } - - @Override - public List<DataReference<TripLonglineDto>> getData(Class<?> parentClass, - String parentId, - NavDataProvider dataProvider) throws Exception { - - DataSelectionModel selectionModel = getSelectionModel(dataProvider); - - List<DataReference<TripLonglineDto>> result; - - if (selectionModel != null) { - - result = Lists.newArrayList((Collection) selectionModel.getDatas(parentId)); - - } else { - - TripLonglineService tripLonglineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripLonglineService(); - DataReferenceSet<TripLonglineDto> tripLonglineByProgram = tripLonglineService.getTripLonglineByProgram(parentId); - - result = Lists.newArrayList(tripLonglineByProgram.getReferences()); - - } - - - return result; - } - - @Override - public ObserveNode createNode(DataReference<TripLonglineDto> data, NavDataProvider dataProvider) { - - if (data == null) { - throw new NullPointerException("Ne peut pas ajouter un objet null"); - } - - ObserveNode result = new TripLonglineNode(data); - - if (addChilds) { - - { - // Add gears - //FIXME - ObserveNode child = ObserveTreeHelper.createStringNode("gearUseFeaturesLongline"); - result.add(child); - } - - { - // Add activities - ObserveNode child = ObserveTreeHelper.createStringNode(TripLonglineDto.PROPERTY_ACTIVITY_LONGLINE, - ActivityLonglinesNodeChildLoador.class); - result.add(child); - } - - } - - return result; - - } - - public void setAddChilds(boolean addChilds) { - this.addChilds = addChilds; - } - - public boolean isAddChilds() { - return addChilds; - } -} - diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ProgramSeineNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ProgramSeineNodeChildLoador.java deleted file mode 100644 index 0add142..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ProgramSeineNodeChildLoador.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.tree.loadors; - -import com.google.common.collect.Lists; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.DataReferenceSet; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.services.service.seine.TripSeineService; -import fr.ird.observe.ui.storage.tabs.DataSelectionModel; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.ui.tree.TripSeineNode; -import jaxx.runtime.swing.nav.NavDataProvider; -import jaxx.runtime.swing.nav.tree.NavTreeBridge; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; - -/** - * Le chargeur des noeuds fils d'un program (les marees du programme). - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ProgramSeineNodeChildLoador extends AbstractNodeChildLoador<DataReference<TripSeineDto>, TripSeineDto> { - - private static final long serialVersionUID = 1L; - - static { - n("observe.tree.gearUseFeaturesSeine"); - n("observe.tree.route"); - } - - public ProgramSeineNodeChildLoador() { - super(TripSeineDto.class); - } - - protected boolean addChilds; - - @Override - public void loadChilds(NavTreeBridge<ObserveNode> model, - ObserveNode parentNode, - NavDataProvider dataProvider) throws Exception { - DataSelectionModel selectionModel = getSelectionModel(dataProvider); - addChilds = selectionModel == null; - - try { - super.loadChilds(model, parentNode, dataProvider); - } finally { - addChilds = true; - } - } - - @Override - public List<DataReference<TripSeineDto>> getData(Class<?> parentClass, - String parentId, - NavDataProvider dataProvider) throws Exception { - - DataSelectionModel selectionModel = getSelectionModel(dataProvider); - - List<DataReference<TripSeineDto>> result; - - if (selectionModel != null) { - - result = Lists.newArrayList((Collection) selectionModel.getDatas(parentId)); - - } else { - - TripSeineService tripSeineService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newTripSeineService(); - DataReferenceSet<TripSeineDto> tripSeineByProgram = tripSeineService.getTripSeineByProgram(parentId); - - result = new ArrayList<>(tripSeineByProgram.getReferences()); - - } - return result; - - } - - @Override - public ObserveNode createNode(DataReference<TripSeineDto> data, NavDataProvider dataProvider) { - - if (data == null) { - throw new NullPointerException("Ne peut pas ajouter un objet null"); - } - - ObserveNode result = new TripSeineNode(data); - - if (addChilds) { - - { - // Add gears - ObserveNode child = ObserveTreeHelper.createStringNode("gearUseFeaturesSeine"); - result.add(child); - } - - { - // Add routes - ObserveNode child = ObserveTreeHelper.createStringNode(TripSeineDto.PROPERTY_ROUTE, RoutesNodeChildLoador.class); - result.add(child); - } - - } - - return result; - - } - - public boolean isAddChilds() { - return addChilds; - } - - public void setAddChilds(boolean addChilds) { - this.addChilds = addChilds; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ReferenceCommonNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ReferenceCommonNodeChildLoador.java deleted file mode 100644 index 4f6e996..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ReferenceCommonNodeChildLoador.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.tree.loadors; - - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialDtos; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.tree.ObserveNode; -import jaxx.runtime.swing.nav.NavDataProvider; - -import java.util.ArrayList; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; - -/** - * Le chargeur des noeuds du referentiel. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ReferenceCommonNodeChildLoador extends AbstractNodeChildLoador<Class, Class> { - - private static final long serialVersionUID = 1L; - - static { - - n("observe.tree.vesselSizeCategory"); - n("observe.tree.country"); - n("observe.tree.harbour"); - n("observe.tree.vesselType"); - n("observe.tree.vessel"); - n("observe.tree.speciesGroup"); - n("observe.tree.species"); - n("observe.tree.sex"); - n("observe.tree.fpaZone"); - n("observe.tree.speciesList"); - n("observe.tree.person"); - n("observe.tree.ocean"); - n("observe.tree.organism"); - n("observe.tree.lengthWeightParameter"); - n("observe.tree.program"); - n("observe.tree.gearCaracteristicType"); - n("observe.tree.gearCaracteristic"); - n("observe.tree.gear"); - - } - - public ReferenceCommonNodeChildLoador() { - super(Class.class); - } - - @Override - public List<Class> getData(Class<?> parentClass, String parentId, NavDataProvider dataProvider) { - - List<Class> result = new ArrayList<>(); - for (Class<? extends ReferentialDto> referenceCommonDto : ReferentialDtos.REFERENCE_COMMON_DTOS) { - result.add(referenceCommonDto); - } - UIHelper.sortReferentiel(result); - return result; - } - - @Override - public ObserveNode createNode(Class data, NavDataProvider dataProvider) { - - ObserveNode result = new ObserveNode( - data, - data.getSimpleName(), - null, - true - ); - return result; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ReferenceLonglineNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ReferenceLonglineNodeChildLoador.java deleted file mode 100644 index b9e8926..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ReferenceLonglineNodeChildLoador.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.tree.loadors; - - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialDtos; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.tree.ObserveNode; -import jaxx.runtime.swing.nav.NavDataProvider; - -import java.util.ArrayList; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; - -/** - * Le chargeur des noeuds du referentiel. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ReferenceLonglineNodeChildLoador extends AbstractNodeChildLoador<Class, Class> { - - private static final long serialVersionUID = 1L; - - static { - n("observe.tree.baitHaulingStatus"); - n("observe.tree.baitSettingStatus"); - n("observe.tree.baitType"); - n("observe.tree.catchFateLongline"); - n("observe.tree.encounterType"); - n("observe.tree.healthness"); - n("observe.tree.hookPosition"); - n("observe.tree.hookSize"); - n("observe.tree.hookType"); - n("observe.tree.itemVerticalPosition"); - n("observe.tree.itemHorizontalPosition"); - n("observe.tree.lightsticksColor"); - n("observe.tree.lightsticksType"); - n("observe.tree.lineType"); - n("observe.tree.maturityStatus"); - n("observe.tree.mitigationType"); - n("observe.tree.sensorBrand"); - n("observe.tree.sensorDataFormat"); - n("observe.tree.sensorType"); - n("observe.tree.settingShape"); - n("observe.tree.sizeMeasureType"); - n("observe.tree.stomacFullness"); - n("observe.tree.tripType"); - n("observe.tree.vesselActivityLongline"); - n("observe.tree.weightMeasureType"); - - } - - public ReferenceLonglineNodeChildLoador() { - super(Class.class); - } - - @Override - public List<Class> getData(Class<?> parentClass, String parentId, NavDataProvider dataProvider) { - - List<Class> result = new ArrayList<>(); - for (Class<? extends ReferentialDto> referenceCommonDto : ReferentialDtos.REFERENCE_LONGLINE_DTOS) { - result.add(referenceCommonDto); - } - UIHelper.sortReferentiel(result); - return result; - } - - @Override - public ObserveNode createNode(Class data, NavDataProvider dataProvider) { - - ObserveNode result = new ObserveNode( - data, - data.getSimpleName(), - null, - true - ); - return result; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ReferenceSeineNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ReferenceSeineNodeChildLoador.java deleted file mode 100644 index 012adca..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/ReferenceSeineNodeChildLoador.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.tree.loadors; - - -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialDtos; -import fr.ird.observe.ui.UIHelper; -import fr.ird.observe.ui.tree.ObserveNode; -import jaxx.runtime.swing.nav.NavDataProvider; - -import java.util.ArrayList; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; - -/** - * Le chargeur des noeuds du referentiel. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ReferenceSeineNodeChildLoador extends AbstractNodeChildLoador<Class, Class> { - - private static final long serialVersionUID = 1L; - - static { - - n("observe.tree.vesselActivitySeine"); - n("observe.tree.surroundingActivity"); - n("observe.tree.reasonForNullSet"); - n("observe.tree.reasonForNoFishing"); - n("observe.tree.speciesFate"); - n("observe.tree.objectFate"); - n("observe.tree.weightCategory"); - n("observe.tree.detectionMode"); - n("observe.tree.transmittingBuoyOperation"); - n("observe.tree.objectOperation"); - n("observe.tree.reasonForDiscard"); - n("observe.tree.speciesStatus"); - n("observe.tree.observedSystem"); - n("observe.tree.transmittingBuoyType"); - n("observe.tree.objectType"); - n("observe.tree.wind"); - - } - - public ReferenceSeineNodeChildLoador() { - super(Class.class); - } - - @Override - public List<Class> getData(Class<?> parentClass, String parentId, NavDataProvider dataProvider) { - - List<Class> result = new ArrayList<>(); - for (Class<? extends ReferentialDto> referenceCommonDto : ReferentialDtos.REFERENCE_SEINE_DTOS) { - result.add(referenceCommonDto); - } - UIHelper.sortReferentiel(result); - return result; - } - - @Override - public ObserveNode createNode(Class data, NavDataProvider dataProvider) { - ObserveNode result = new ObserveNode( - data, - data.getSimpleName(), - null, - true - ); - return result; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/RootNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/RootNodeChildLoador.java deleted file mode 100644 index 7259ef5..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/RootNodeChildLoador.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.tree.loadors; - -import com.google.common.collect.Lists; -import fr.ird.observe.services.dto.constants.GearType; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.ui.storage.tabs.DataSelectionModel; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.ui.tree.ProgramLonglineNode; -import fr.ird.observe.ui.tree.ProgramSeineNode; -import jaxx.runtime.swing.nav.NavDataProvider; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Set; - -import static org.nuiton.i18n.I18n.n; - -/** - * Le chargeur des noeuds fils d'un program (les marees du programme). - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class RootNodeChildLoador extends AbstractNodeChildLoador<ReferentialReference<ProgramDto>, ProgramDto> { - - private static final long serialVersionUID = 1L; - - protected boolean addData; - - protected boolean addReferentiel; - - public RootNodeChildLoador() { - super(ProgramDto.class); - } - - public RootNodeChildLoador(boolean addData, boolean addReferentiel) { - this(); - this.addData = addData; - this.addReferentiel = addReferentiel; - } - - public void setAddData(boolean addData) { - this.addData = addData; - } - - public void setAddReferentiel(boolean addReferentiel) { - this.addReferentiel = addReferentiel; - } - - @Override - public List<ReferentialReference<ProgramDto>> getData(Class<?> parentClass, String parentId, NavDataProvider dataProvider) { - - DataSelectionModel selectionModel = getSelectionModel(dataProvider); - - List<ReferentialReference<ProgramDto>> data = Collections.emptyList(); - - if (addData) { - - if (selectionModel != null) { - data = Lists.newArrayList(selectionModel.getDatas().keySet()); - } else { - Set<ReferentialReference<ProgramDto>> referentialReferenceSet = getDataSource(dataProvider).getReferentialReferences(ProgramDto.class); - data = new ArrayList<>(referentialReferenceSet); - } - - ObserveTreeHelper.sortPrograms(data); - } - - return data; - - } - - @Override - public void addChildNodes(ObserveNode parentNode, List<ReferentialReference<ProgramDto>> datas, NavDataProvider dataProvider) { - super.addChildNodes(parentNode, datas, dataProvider); - if (addReferentiel) { - - { // ajout du referentiel commun - ObserveNode child = new ObserveNode( - String.class, - n("observe.tree.reference.common"), - ObserveTreeHelper.getChildLoador(ReferenceCommonNodeChildLoador.class), - true - ); - parentNode.add(child); - } - { // ajout du referentiel seine - ObserveNode child = new ObserveNode( - String.class, - n("observe.tree.reference.seine"), - ObserveTreeHelper.getChildLoador(ReferenceSeineNodeChildLoador.class), - true - ); - parentNode.add(child); - } - { // ajout du referentiel longline - ObserveNode child = new ObserveNode( - String.class, - n("observe.tree.reference.longline"), - ObserveTreeHelper.getChildLoador(ReferenceLonglineNodeChildLoador.class), - true - ); - parentNode.add(child); - } - - } - } - - @Override - public ObserveNode createNode(ReferentialReference<ProgramDto> data, NavDataProvider dataProvider) { - - GearType gearType = (GearType) data.getPropertyValue(ProgramDto.PROPERTY_GEAR_TYPE); - - ObserveNode result; - - switch (gearType) { - - case seine: - - result = new ProgramSeineNode(data); - break; - - case longline: - - result = new ProgramLonglineNode(data); - break; - - default: - throw new IllegalStateException("The program has a gearType " + gearType + " we can't deal with"); - - } - - return result; - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/RoutesNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/RoutesNodeChildLoador.java deleted file mode 100644 index f74a502..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/RoutesNodeChildLoador.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.tree.loadors; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.DataReferenceSet; -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.services.service.seine.RouteService; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.ui.tree.RouteSeineNode; -import jaxx.runtime.swing.nav.NavDataProvider; - -import java.util.ArrayList; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; - -/** - * Le chargeur des noeuds de routes d'une marée. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class RoutesNodeChildLoador extends AbstractDataReferenceChildLoador<RouteDto> { - - private static final long serialVersionUID = 1L; - - static { - n("observe.tree.activitySeine"); - } - - public RoutesNodeChildLoador() { - super(RouteDto.class); - } - - @Override - public List<DataReference<RouteDto>> getData(Class<?> parentClass, - String parentId, - NavDataProvider dataProvider) throws Exception { - - RouteService routeService = ObserveSwingApplicationContext.get().getMainDataSourceServicesProvider().newRouteService(); - DataReferenceSet<RouteDto> routeByTripSeine = routeService.getRouteByTripSeine(parentId); - - return new ArrayList<>(routeByTripSeine.getReferences()); - } - - - - @Override - public ObserveNode createNode(DataReference<RouteDto> data, NavDataProvider dataProvider) { - - if (data == null) { - throw new NullPointerException("Ne peut pas ajouter un objet null"); - } - - ObserveNode result = new RouteSeineNode(data); - - // Creation d'un node activites - ObserveNode child = ObserveTreeHelper.createStringNode("activitySeine", ActivitySeinesNodeChildLoador.class); - result.add(child); - return result; - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/SetLonglineNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/SetLonglineNodeChildLoador.java deleted file mode 100644 index f83d25f..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/SetLonglineNodeChildLoador.java +++ /dev/null @@ -1,79 +0,0 @@ -package fr.ird.observe.ui.tree.loadors; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - - -import fr.ird.observe.services.dto.longline.SetLonglineCatchDto; -import fr.ird.observe.services.dto.longline.SetLonglineTdrDto; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import jaxx.runtime.swing.nav.NavDataProvider; - -import java.util.ArrayList; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; - -/** - * Created on 8/30/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.7 - */ -public class SetLonglineNodeChildLoador extends AbstractNodeChildLoador<String, String> { - - private static final long serialVersionUID = 1L; - - static { - n("observe.tree.longlineGlobalComposition"); - n("observe.tree.longlineDetailComposition"); - n("observe.tree.catchLongline"); - n("observe.tree.tdr"); - } - - public SetLonglineNodeChildLoador() { - super(String.class); - } - - @Override - public List<String> getData(Class<?> parentClass, - String parentId, - NavDataProvider dataProvider) { - - List<String> result = new ArrayList<>(); - result.add("longlineGlobalComposition"); - result.add("longlineDetailComposition"); - result.add(SetLonglineCatchDto.PROPERTY_CATCH_LONGLINE); - result.add(SetLonglineTdrDto.PROPERTY_TDR); -// - return result; - } - - @Override - public ObserveNode createNode(String data, NavDataProvider dataProvider) { - - ObserveNode result = ObserveTreeHelper.createStringNode(data); - return result; - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/SetSeineNodeChildLoador.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/SetSeineNodeChildLoador.java deleted file mode 100644 index dccb572..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/loadors/SetSeineNodeChildLoador.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.tree.loadors; - - -import fr.ird.observe.services.dto.seine.SetSeineDto; -import fr.ird.observe.services.dto.seine.SetSeineNonTargetCatchDto; -import fr.ird.observe.services.dto.seine.SetSeineSchoolEstimateDto; -import fr.ird.observe.services.dto.seine.SetSeineTargetCatchDto; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import jaxx.runtime.swing.nav.NavDataProvider; - -import java.util.ArrayList; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; - -/** - * Le chargeur des noeuds de marees. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class SetSeineNodeChildLoador extends AbstractNodeChildLoador<String, String> { - - private static final long serialVersionUID = 1L; - - static { - n("observe.tree.schoolEstimate"); - n("observe.tree.targetCatch"); - n("observe.tree.targetDiscarded"); - n("observe.tree.targetSample"); - n("observe.tree.targetSampleCapture"); - n("observe.tree.nonTargetCatch"); - n("observe.tree.nonTargetSample"); - } - - public SetSeineNodeChildLoador() { - super(String.class); - } - - @Override - public List<String> getData(Class<?> parentClass, - String parentId, - NavDataProvider dataProvider) { - - List<String> result = new ArrayList<>(); - result.add(SetSeineSchoolEstimateDto.PROPERTY_SCHOOL_ESTIMATE); - result.add(SetSeineTargetCatchDto.PROPERTY_TARGET_CATCH); - result.add(SetSeineDto.PROPERTY_TARGET_DISCARDED); - result.add("targetSample"); - result.add(SetSeineDto.PROPERTY_TARGET_SAMPLE_CAPTURE); - result.add(SetSeineNonTargetCatchDto.PROPERTY_NON_TARGET_CATCH); - result.add("nonTargetSample"); - return result; - - } - - @Override - public ObserveNode createNode(String data, NavDataProvider dataProvider) { - - ObserveNode result = ObserveTreeHelper.createStringNode(data); - return result; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/menu/MoveActivityLonglineNodeMenuPopulator.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/menu/MoveActivityLonglineNodeMenuPopulator.java deleted file mode 100644 index 8c01d2a..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/menu/MoveActivityLonglineNodeMenuPopulator.java +++ /dev/null @@ -1,85 +0,0 @@ -package fr.ird.observe.ui.tree.menu; - -/*- - * #%L - * ObServe :: Application Swing - * %% - * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.IdDtos; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.ui.tree.TripLonglineNode; -import fr.ird.observe.ui.tree.actions.ChangeActivityTripActionListener; -import fr.ird.observe.ui.tree.actions.NodeChangeActionListener; -import fr.ird.observe.ui.util.DecoratedNodeEntity; -import fr.ird.observe.application.swing.decoration.decorators.DataReferenceDecorator; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Kevin Morin (Code Lutin) - * @since 5.0 - */ -public class MoveActivityLonglineNodeMenuPopulator extends MoveNodeMenuPopulator { - - @Override - public NodeChangeActionListener createChangeActionListener(ObserveTreeHelper treeHelper, - ObserveSwingDataSource dataSource, - String id, - String parentId) { - return new ChangeActivityTripActionListener(treeHelper, dataSource, id, parentId); - } - - @Override - public List<DecoratedNodeEntity> getPossibleParentNodes(ObserveNode activityLonglineNode, ObserveTreeHelper treeHelper) { - - // noeud de marée parent - ObserveNode parentNode = activityLonglineNode.getParent().getParent(); - - // noeud de route de la marée sans le parent actuel - List<DecoratedNodeEntity> possibleParents = new ArrayList<>(); - - // noeud du programme - ObserveNode programNode = parentNode.getParent(); - - DecoratorService decoratorService = treeHelper.getTreeCellRenderer().getDecoratorService(); - DataReferenceDecorator<TripLonglineDto> tripDecorator = decoratorService.getDataReferenceDecorator(TripLonglineDto.class); - - for (int i = 0, n = programNode.getChildCount(); i < n; i++) { - - TripLonglineNode tripNode = (TripLonglineNode) programNode.getChildAt(i); - String tripId = tripNode.getId(); - - // si le noeud de marée n'est pas le même que le parent actuel - // si le noeud est bien un noeud de marée longline - if (!parentNode.equals(tripNode) && IdDtos.isTripLonglineId(tripId)) { - - possibleParents.add(DecoratedNodeEntity.newDecoratedNodeEntity(tripNode, tripDecorator)); - - } - } - - return possibleParents; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/menu/MoveActivitySeineNodeMenuPopulator.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/menu/MoveActivitySeineNodeMenuPopulator.java deleted file mode 100644 index b4f032f..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/menu/MoveActivitySeineNodeMenuPopulator.java +++ /dev/null @@ -1,85 +0,0 @@ -package fr.ird.observe.ui.tree.menu; - -/*- - * #%L - * ObServe :: Application Swing - * %% - * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.IdDtos; -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.ui.tree.RouteSeineNode; -import fr.ird.observe.ui.tree.actions.ChangeActivityRouteActionListener; -import fr.ird.observe.ui.tree.actions.NodeChangeActionListener; -import fr.ird.observe.ui.util.DecoratedNodeEntity; -import fr.ird.observe.application.swing.decoration.decorators.DataReferenceDecorator; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Kevin Morin (Code Lutin) - * @since 5.0 - */ -public class MoveActivitySeineNodeMenuPopulator extends MoveNodeMenuPopulator { - - @Override - public NodeChangeActionListener createChangeActionListener(ObserveTreeHelper treeHelper, - ObserveSwingDataSource dataSource, - String id, - String parentId) { - return new ChangeActivityRouteActionListener(treeHelper, dataSource, id, parentId); - } - - @Override - public List<DecoratedNodeEntity> getPossibleParentNodes(ObserveNode activitySeineNode, ObserveTreeHelper treeHelper) { - - // noeud de route parent - ObserveNode parentNode = activitySeineNode.getParent().getParent(); - - // noeud de route de la marée sans le parent actuel - List<DecoratedNodeEntity> possibleParents = new ArrayList<>(); - - // noeud des routes de la marée - ObserveNode routesNode = parentNode.getParent(); - - DecoratorService decoratorService = treeHelper.getTreeCellRenderer().getDecoratorService(); - DataReferenceDecorator<RouteDto> routeDecorator = decoratorService.getDataReferenceDecorator(RouteDto.class); - - for (int i = 0, n = routesNode.getChildCount(); i < n; i++) { - - RouteSeineNode routeNode = (RouteSeineNode) routesNode.getChildAt(i); - String routeId = routeNode.getId(); - - // si le noeud de marée n'est pas le même que le parent actuel - // si le noeud est bien un noeud de marée seine - if (!parentNode.equals(routeNode) && IdDtos.isRouteId(routeId)) { - - possibleParents.add(DecoratedNodeEntity.newDecoratedNodeEntity(routeNode, routeDecorator)); - - } - } - - return possibleParents; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/menu/MoveNodeMenuPopulator.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/menu/MoveNodeMenuPopulator.java deleted file mode 100644 index 99918e6..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/menu/MoveNodeMenuPopulator.java +++ /dev/null @@ -1,62 +0,0 @@ -package fr.ird.observe.ui.tree.menu; - -/*- - * #%L - * ObServe :: Application Swing - * %% - * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.ui.tree.actions.NodeChangeActionListener; -import fr.ird.observe.ui.util.DecoratedNodeEntity; - -import java.util.List; - -/** - * Objets pour créer les items du menu déplacer dans le menu contextuel de l'arbre - * - * @author Kevin Morin (Code Lutin) - * @since 5.0 - */ -public abstract class MoveNodeMenuPopulator { - - /** - * Crée une action pour déplacer le noeud quand on sélectionne le menu du nouveau parent - * @param treeHelper - * @param dataSource - * @param id - * @param parentId - * @return - */ - public abstract NodeChangeActionListener createChangeActionListener(ObserveTreeHelper treeHelper, - ObserveSwingDataSource dataSource, - String id, - String parentId); - - /** - * Récupère les parents dans lesquels on peut déplacer le noeud sélectionné - * @param node le noeud sélectionné - * @param treeHelper le treehelper - * @return une liste contenant les ids et les libellés des noeuds - */ - public abstract List<DecoratedNodeEntity> getPossibleParentNodes(ObserveNode node, ObserveTreeHelper treeHelper); - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/menu/MoveRouteNodeMenuPopulator.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/menu/MoveRouteNodeMenuPopulator.java deleted file mode 100644 index b224084..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/menu/MoveRouteNodeMenuPopulator.java +++ /dev/null @@ -1,85 +0,0 @@ -package fr.ird.observe.ui.tree.menu; - -/*- - * #%L - * ObServe :: Application Swing - * %% - * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.IdDtos; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.ui.tree.TripSeineNode; -import fr.ird.observe.ui.tree.actions.ChangeRouteTripActionListener; -import fr.ird.observe.ui.tree.actions.NodeChangeActionListener; -import fr.ird.observe.ui.util.DecoratedNodeEntity; -import fr.ird.observe.application.swing.decoration.decorators.DataReferenceDecorator; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Kevin Morin (Code Lutin) - * @since 5.0 - */ -public class MoveRouteNodeMenuPopulator extends MoveNodeMenuPopulator { - - @Override - public NodeChangeActionListener createChangeActionListener(ObserveTreeHelper treeHelper, - ObserveSwingDataSource dataSource, - String id, - String parentId) { - return new ChangeRouteTripActionListener(treeHelper, dataSource, id, parentId); - } - - @Override - public List<DecoratedNodeEntity> getPossibleParentNodes(ObserveNode routeNode, ObserveTreeHelper treeHelper) { - - // noeud de marée parent - ObserveNode parentNode = routeNode.getParent().getParent(); - - // noeud de marée du programme sans le parent actuel - List<DecoratedNodeEntity> possibleParents = new ArrayList<>(); - - // noeud du programme - ObserveNode programNode = parentNode.getParent(); - - DecoratorService decoratorService = treeHelper.getTreeCellRenderer().getDecoratorService(); - DataReferenceDecorator<TripSeineDto> tripDecorator = decoratorService.getDataReferenceDecorator(TripSeineDto.class); - - for (int i = 0, n = programNode.getChildCount(); i < n; i++) { - - TripSeineNode tripNode = (TripSeineNode) programNode.getChildAt(i); - String tripId = tripNode.getId(); - - // si le noeud de marée n'est pas le même que le parent actuel - // si le noeud est bien un noeud de marée seine - if (!parentNode.equals(tripNode) && IdDtos.isTripSeineId(tripId)) { - - possibleParents.add(DecoratedNodeEntity.newDecoratedNodeEntity(tripNode, tripDecorator)); - - } - } - - return possibleParents; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/menu/MoveTripNodeMenuPopulator.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/menu/MoveTripNodeMenuPopulator.java deleted file mode 100644 index f6d9180..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/tree/menu/MoveTripNodeMenuPopulator.java +++ /dev/null @@ -1,105 +0,0 @@ -package fr.ird.observe.ui.tree.menu; - -/*- - * #%L - * ObServe :: Application Swing - * %% - * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.IdDtos; -import fr.ird.observe.services.dto.constants.GearType; -import fr.ird.observe.services.dto.referential.ProgramDto; -import fr.ird.observe.ui.tree.ObserveNode; -import fr.ird.observe.ui.tree.ObserveTreeHelper; -import fr.ird.observe.ui.tree.ProgramLonglineNode; -import fr.ird.observe.ui.tree.ProgramSeineNode; -import fr.ird.observe.ui.tree.actions.ChangeTripProgramActionListener; -import fr.ird.observe.ui.tree.actions.NodeChangeActionListener; -import fr.ird.observe.ui.util.DecoratedNodeEntity; -import fr.ird.observe.application.swing.decoration.decorators.ReferentialReferenceDecorator; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author Kevin Morin (Code Lutin) - * @since 5.0 - */ -public class MoveTripNodeMenuPopulator extends MoveNodeMenuPopulator { - - @Override - public NodeChangeActionListener createChangeActionListener(ObserveTreeHelper treeHelper, - ObserveSwingDataSource dataSource, - String id, - String parentId) { - return new ChangeTripProgramActionListener(treeHelper, dataSource, id, parentId); - } - - @Override - public List<DecoratedNodeEntity> getPossibleParentNodes(ObserveNode tripNode, ObserveTreeHelper treeHelper) { - - // noeud du programme parent - ObserveNode parentNode = tripNode.getParent(); - - // programmes du même type que le noeud de marée, sans le parent actuel - List<DecoratedNodeEntity> possibleParents = new ArrayList<>(); - - // noeud longline ? - GearType gearType = IdDtos.isLonglineId(tripNode.getId()) ? GearType.longline : GearType.seine; - - // racine - ObserveNode rootNode = treeHelper.getRootNode(); - - createPossibleParents(parentNode.getId(), possibleParents, gearType, rootNode); - - return possibleParents; - } - - public static void createPossibleParents(String oldProgramId, List<DecoratedNodeEntity> possibleParents, GearType gearType, ObserveNode rootNode) { - - ReferentialReferenceDecorator<ProgramDto> programDecorator = ObserveSwingApplicationContext.get().getDecoratorService().getReferentialReferenceDecorator(ProgramDto.class); - - for (int i = 0, n = rootNode.getChildCount(); i < n; i++) { - - ObserveNode programNode = rootNode.getChildAt(i); - String programId = programNode.getId(); - - // si le noeud programme n'est pas le même que le parent actuel - // si le noeud est bien un noeud de programme - if (IdDtos.isProgramId(programId) && !oldProgramId.equals(programId)) { - - if (programNode instanceof ProgramSeineNode && GearType.seine == gearType) { - - ProgramSeineNode node = (ProgramSeineNode) programNode; - possibleParents.add(DecoratedNodeEntity.newDecoratedNodeEntity(node, programDecorator)); - - } else if (programNode instanceof ProgramLonglineNode && GearType.longline == gearType) { - - ProgramLonglineNode node = (ProgramLonglineNode) programNode; - possibleParents.add(DecoratedNodeEntity.newDecoratedNodeEntity(node, programDecorator)); - - } - - } - } - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/usage/UsagesUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/usage/UsagesUI.jaxx deleted file mode 100644 index 30d5538..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/usage/UsagesUI.jaxx +++ /dev/null @@ -1,91 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> - -<!-- -Interface graphique pour afficher la liste des usages d'une entitee donnee. ---> -<JPanel id='usagePanel' layout='{new BorderLayout()}'> - - <import> - fr.ird.observe.ObserveSwingApplicationContext - fr.ird.observe.ui.UIHelper - - fr.ird.observe.services.dto.ReferenceMap - - java.awt.Dimension - </import> - - <script><![CDATA[ - -private UsagesUIHandler handler = new UsagesUIHandler(); - -public void init(String message, - String message2, - String message3, - ReferenceMap usages) { - getHandler().initUI(this, message,message2, message3, usages); -} - -public void clean() { - getHandler().cleanUI(this); -} - -protected UsagesUIHandler getHandler() { - return handler; -} - -void $afterCompleteSetup() { - -} - -public void destroy() { - log.info("destroy ui " + getName()); - UIHelper.destroy(this); -} - -@Override -protected void finalize() throws Throwable { - super.finalize(); - destroy(); -} -]]> - </script> - - <JPanel constraints="BorderLayout.NORTH" - layout='{new BorderLayout()}'> - - <JPanel layout='{new BorderLayout()}' constraints="BorderLayout.CENTER"> - <JLabel id="message" constraints="BorderLayout.NORTH"/> - <JLabel id="message2" constraints="BorderLayout.CENTER"/> - <JLabel id="message3" constraints="BorderLayout.SOUTH"/> - </JPanel> - <JPanel constraints="BorderLayout.SOUTH" - minimumSize='{new Dimension(10,30)}'/> - <!--layout='{new BorderLayout()}'--> - <!--<JSeparator constraints="BorderLayout.SOUTH"/>--> - </JPanel> - - <JPanel id="usages" constraints="BorderLayout.CENTER" - layout="{new GridLayout(0, 1)}"/> - - -</JPanel> diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/usage/UsagesUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/usage/UsagesUIHandler.java deleted file mode 100644 index ec2a7e5..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/usage/UsagesUIHandler.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.usage; - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.dto.AbstractReference; -import fr.ird.observe.services.dto.DataDto; -import fr.ird.observe.services.dto.DataReference; -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.services.dto.ReferenceMap; -import fr.ird.observe.services.dto.referential.ReferentialDto; -import fr.ird.observe.services.dto.referential.ReferentialReference; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.decorator.Decorator; - -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JScrollPane; -import java.awt.Dimension; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.stream.Collectors; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * @author Tony Chemit - chemit@codelutin.com - * @since 1.2 - */ -public class UsagesUIHandler { - - /** Logger */ - private static final Log log = LogFactory.getLog(UsagesUIHandler.class); - - /** - * Afficher les usages d'une entite donnee. - * - * @param ui l'ui - * @param message le message a afficher en haut - * @param message2 message supplementaire a afficher en haut - * @param message3 message supplementaire a afficher en haut - * @param usages les utilisations de l'entite donnee - */ - public void initUI(UsagesUI ui, - String message, - String message2, - String message3, - ReferenceMap usages) { - // toujours nettoyer l'ui avant tout - cleanUI(ui); - - ui.getMessage().setText(t(message)); - if (message2 != null) { - ui.getMessage2().setVisible(true); - ui.getMessage2().setText(message2); - } - if (message3 != null) { - ui.getMessage3().setVisible(true); - ui.getMessage3().setText(message3); - } - if (usages.isEmpty()) { - ui.getUsages().add(new JLabel(t("observe.message.no.usage.for.entity"))); - } else { - - for (Map.Entry<Class<? extends IdDto>, Set<? extends AbstractReference>> entry : usages.entrySet()) { - Class dtoType = entry.getKey(); - Set references = entry.getValue(); - String typeTitle = t(DecoratorService.getEntityLabel(dtoType)); - if (DataDto.class.isAssignableFrom(dtoType)) { - addDataReferenceUsages(ui, dtoType, references, typeTitle); - } else { - addReferentialReferenceUsages(ui, dtoType, references, typeTitle); - } - - } - } - } - - public void cleanUI(UsagesUI ui) { - ui.getUsages().removeAll(); - ui.getMessage().setText(null); - ui.getMessage2().setText(null); - ui.getMessage2().setVisible(false); - ui.getMessage3().setText(null); - ui.getMessage3().setVisible(false); - } - - protected <D extends DataDto> void addDataReferenceUsages(UsagesUI ui, - Class<D> dtoType, - Set<DataReference<D>> references, - String typeTitle) { - - int size = references.size(); - String typetitle = n("observe.content.label.usage.data.title"); - typetitle = t(typetitle, typeTitle, size); - - Decorator<?> decorator = ObserveSwingApplicationContext.get().getDecoratorService().getDataReferenceDecorator(dtoType); - Objects.requireNonNull(decorator, "could not find decorator for type " + dtoType); - - List<String> data = new ArrayList<>(size); - data.addAll(references.stream().map(decorator::toString).collect(Collectors.toList())); - - JList<? super String> l = new JList<>(data.toArray()); - - JScrollPane pane = new JScrollPane(); - pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - pane.setMinimumSize(new Dimension(300, 30)); -// pane.setMaximumSize(new Dimension(300, 100)); - pane.setColumnHeaderView(new JLabel(typetitle)); - pane.setViewportView(l); - ui.getUsages().add(pane); - } - - - protected <D extends ReferentialDto> void addReferentialReferenceUsages(UsagesUI ui, - Class<D> dtoType, - Set<ReferentialReference<D>> references, - String typeTitle) { - - int size = references.size(); - String typetitle = n("observe.content.label.usage.referentiel.title"); - typetitle = t(typetitle, typeTitle, size); - - Decorator<?> decorator = ObserveSwingApplicationContext.get().getDecoratorService().getReferentialReferenceDecorator(dtoType); - Objects.requireNonNull(decorator, "could not find decorator for type " + dtoType); - - List<String> data = new ArrayList<>(size); - data.addAll(references.stream().map(decorator::toString).collect(Collectors.toList())); - - JList<? super String> l = new JList<>(data.toArray()); - - JScrollPane pane = new JScrollPane(); - pane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED); - pane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED); - pane.setMinimumSize(new Dimension(300, 30)); -// pane.setMaximumSize(new Dimension(300, 100)); - pane.setColumnHeaderView(new JLabel(typetitle)); - pane.setViewportView(l); - ui.getUsages().add(pane); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/BooleanEditor.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/BooleanEditor.java deleted file mode 100644 index 1f10071..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/BooleanEditor.java +++ /dev/null @@ -1,180 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.util; - - -import org.apache.commons.lang3.StringUtils; - -import javax.swing.JComboBox; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * Un éditeur de {@link Boolean} avec trois valeurs possibles : - * <ul> - * <li>{@code Null}</li> - * <li>{@code false}</li> - * <li>{@code true}</li> - * </ul> - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.5 - */ -public class BooleanEditor extends JComboBox { - - private static final long serialVersionUID = 1L; - - public enum Value { - NULL(n("observe.common.boolean.null"), null), - FALSE(n("observe.common.boolean.false"), false), - TRUE(n("observe.common.boolean.true"), true); - - private final String defaultLibelle; - - private final Boolean booleanValue; - - Value(String defaultLibelle, Boolean booleanValue) { - this.defaultLibelle = defaultLibelle; - this.booleanValue = booleanValue; - } - - public Boolean getBooleanValue() { - return booleanValue; - } - - public String getDefaultLibelle() { - return defaultLibelle; - } - - public static Value valueOf(Boolean value) { - Value result = null; - for (Value v : values()) { - if (v.getBooleanValue() == value) { - result = v; - break; - } - } - return result; - } - } - - protected static class ValueEntry { - - protected final Value value; - - protected final String text; - - ValueEntry(Value value, String text) { - this.value = value; - this.text = text; - } - - public Value getValue() { - return value; - } - - public String getText() { - return text; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - ValueEntry that = (ValueEntry) o; - - if (!text.equals(that.text)) return false; - return value == that.value; - - } - - @Override - public int hashCode() { - int result = value.hashCode(); - result = 31 * result + text.hashCode(); - return result; - } - - @Override - public String toString() { - return text; - } - } - - protected static ValueEntry[] buildModel(String nullLibelle, - String falseLibelle, - String trueLibelle) { - ValueEntry[] result = new ValueEntry[3]; - - String text; - if (StringUtils.isBlank(nullLibelle)) { - text = Value.NULL.getDefaultLibelle(); - } else { - text = nullLibelle; - } - result[0] = new ValueEntry(Value.NULL, t(text)); - - if (StringUtils.isBlank(falseLibelle)) { - text = Value.FALSE.getDefaultLibelle(); - } else { - text = falseLibelle; - } - result[1] = new ValueEntry(Value.FALSE, t(text)); - - if (StringUtils.isBlank(trueLibelle)) { - text = Value.TRUE.getDefaultLibelle(); - } else { - text = trueLibelle; - } - result[2] = new ValueEntry(Value.TRUE, t(text)); - return result; - } - - public BooleanEditor() { - this(null, null, null); - } - - public BooleanEditor(String nullLibelle, - String falseLibelle, - String trueLibelle) { - super(buildModel(nullLibelle, falseLibelle, trueLibelle)); - } - - public void setBooleanValue(Boolean b) { - Value v = Value.valueOf(b); - ValueEntry e = (ValueEntry) dataModel.getElementAt(v.ordinal()); - setSelectedItem(e); - } - - public Boolean getBooleanValue() { - Object o = getSelectedItem(); - if (o == null) { - return null; - } - Boolean result; - ValueEntry v = (ValueEntry) o; - result = v.getValue().getBooleanValue(); - return result; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/DecoratedNodeEntity.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/DecoratedNodeEntity.java deleted file mode 100644 index 0935836..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/DecoratedNodeEntity.java +++ /dev/null @@ -1,60 +0,0 @@ -package fr.ird.observe.ui.util; - -/*- - * #%L - * ObServe :: Application Swing - * %% - * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.base.Preconditions; -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.ui.tree.AbstrctReferenceNodeSupport; -import org.nuiton.decorator.Decorator; - -/** - * @author Kevin Morin (Code Lutin) - * @since 5.0 - */ -public class DecoratedNodeEntity { - - private final String id; - - private final String label; - - public static <E extends IdDto> DecoratedNodeEntity newDecoratedNodeEntity(AbstrctReferenceNodeSupport<E, ?> node, Decorator<?> decorator) { - Preconditions.checkNotNull(node); - Preconditions.checkNotNull(decorator); - return new DecoratedNodeEntity(node.getId(), decorator.toString(node.getEntity())); - } - - public String getId() { - return id; - } - - @Override - public String toString() { - return label; - } - - protected DecoratedNodeEntity(String id, String label) { - this.id = id; - this.label = label; - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/FloatConverter.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/FloatConverter.java deleted file mode 100644 index 3eb6981..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/FloatConverter.java +++ /dev/null @@ -1,87 +0,0 @@ -/* - * #%L - * MS-Access Importer - * - * $Id$ - * $HeadURL$ - * %% - * Copyright (C) 2010 - 2011 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.ui.util; - -import org.apache.commons.beanutils.ConversionException; -import org.nuiton.converter.NuitonConverter; - -import static org.nuiton.i18n.I18n.t; - -/** - * A float converter which is not dependant on user locale to obtain the locale - * {@code dot} representation. - * - * It can transform {@code 0.2} and also {@code 0, 2}. - * - * @author tchemit - chemit@codelutin.com - * @since 1.3 - */ -public class FloatConverter implements NuitonConverter { - - @Override - public Object convert(Class aClass, Object value) { - if (value == null) { - throw new ConversionException( - t("nuitonutil.error.convertor.noValue", this)); - } - if (isEnabled(aClass)) { - Object result; - if (isEnabled(value.getClass())) { - result = value; - return result; - } - if (value instanceof String) { - result = valueOf((String) value); - return result; - } - } - throw new ConversionException( - t("nuitonutil.error.no.convertor", aClass.getName(), value)); - } - - protected Float valueOf(String value) { - try { - if (value.contains(",")) { - value = value.replaceAll(",", "."); - } - Float result; - result = Float.valueOf(value); - return result; - } catch (NumberFormatException e) { - throw new ConversionException( - t("nuitonutil.error.float.convertor", value, this, e.getMessage())); - } - } - - - protected boolean isEnabled(Class<?> aClass) { - return Float.class.equals(aClass); - } - - @Override - public Class<Float> getType() { - return Float.class; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/JVetoableTabbedPane.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/JVetoableTabbedPane.java deleted file mode 100644 index 2b77d41..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/JVetoableTabbedPane.java +++ /dev/null @@ -1,102 +0,0 @@ -package fr.ird.observe.ui.util; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JTabbedPane; - -/** - * Created on 12/13/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.10 - */ -public class JVetoableTabbedPane extends JTabbedPane { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = LogFactory.getLog(JVetoableTabbedPane.class); - - protected transient ChangeSelectedIndex changeSelectedIndex; - - protected int previousIndex = -1; - - public void setChangeSelectedIndex(ChangeSelectedIndex changeSelectedIndex) { - this.changeSelectedIndex = changeSelectedIndex; - } - - public int getPreviousIndex() { - return previousIndex; - } - - @Override - public void setSelectedIndex(int index) { - - int selectedIndex = getSelectedIndex(); - - boolean canChange = true; - - if (changeSelectedIndex != null) { - - canChange = changeSelectedIndex.canChangeTab(selectedIndex, index); - - } - - if (canChange) { - - previousIndex = selectedIndex; - - if (log.isDebugEnabled()) { - log.debug("User accept to change from " + previousIndex + " tab to " + index + " tab."); - } - - super.setSelectedIndex(index); - - } else { - - if (log.isDebugEnabled()) { - log.debug("User refuse to change from " + selectedIndex + " tab to " + index + " tab."); - } - - } - - } - - public static interface ChangeSelectedIndex { - - /** - * Ask to change tab from {@code selectedIndex} tab to {@code index}. - * - * If response is {@code false}, then we should not quit the current tab. - * - * @param currentSelectedIndex the current index of the selected tab - * @param newSelectedIndex the index of the tab we want to go on - * @return {@code true} if we can do the change, {@code false} otherwise. - */ - boolean canChangeTab(int currentSelectedIndex, int newSelectedIndex); - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/ObserveSwingValidatorMessageTableModel.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/ObserveSwingValidatorMessageTableModel.java deleted file mode 100644 index f5e3410..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/ObserveSwingValidatorMessageTableModel.java +++ /dev/null @@ -1,84 +0,0 @@ -package fr.ird.observe.ui.util; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import jaxx.runtime.validator.swing.SwingValidatorMessage; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.JComponent; -import java.util.Collection; -import java.util.Collections; -import java.util.function.Predicate; - -/** - * Created on 3/18/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.15 - */ -public class ObserveSwingValidatorMessageTableModel extends SwingValidatorMessageTableModel { - - private static final long serialVersionUID = 1L; - - @Override - public void removeMessages(JComponent editor, - NuitonValidatorScope scope) { - if (scope == null) { - // on supprime tout sans aucun calcul - int nb = getRowCount(); - if (nb > 0) { - data.clear(); - fireTableRowsDeleted(0, nb - 1); - } - } else { - super.removeMessages(editor, scope); - } - } - - public void removeMessages(Predicate<SwingValidatorMessage> predicate) { - - for (int i = getRowCount() - 1; i > -1; i--) { - SwingValidatorMessage error = data.get(i); - - if (predicate.test(error)) { - // remove the message - data.remove(i); - fireTableRowsDeleted(i, i); - } - } - - } - - public <M extends SwingValidatorMessage> void addMessages(Collection<M> messages) { - - data.addAll(messages); - - // resort datas - Collections.sort(data); - - // notify - fireTableDataChanged(); - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/ObserveValidationMessageTableRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/ObserveValidationMessageTableRenderer.java deleted file mode 100644 index 79b2885..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/ObserveValidationMessageTableRenderer.java +++ /dev/null @@ -1,147 +0,0 @@ -package fr.ird.observe.ui.util; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.services.service.actions.validate.ValidationMessage; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.ui.admin.validate.ValidationMessageTableModel; -import jaxx.runtime.validator.swing.SwingValidatorUtil; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.ImageIcon; -import javax.swing.JLabel; -import javax.swing.JTable; -import javax.swing.table.DefaultTableCellRenderer; -import java.awt.Color; -import java.awt.Component; - -import static org.nuiton.i18n.I18n.t; - -/** -* Created on 12/13/14. -* -* @author Tony Chemit - chemit@codelutin.com -* @since XXX -*/ -public class ObserveValidationMessageTableRenderer extends DefaultTableCellRenderer { - - private static final long serialVersionUID = 1L; - - protected transient DecoratorService decoratorService; - - public DecoratorService getDecoratorService() { - if (decoratorService == null) { - decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); - } - return decoratorService; - } - - public String getFieldName(JTable table, String value, int row) { - - String fieldName = value; - DecoratorService dService = getDecoratorService(); - if (!dService.getPropertyMatch(fieldName).matches()) { - fieldName = DecoratorService.getPropertyLabel(fieldName); - } - return t(fieldName); - } - - @Override - public Component getTableCellRendererComponent(JTable table, - Object value, - boolean isSelected, - boolean hasFocus, - int row, - int column) { - JLabel rendererComponent = (JLabel) - super.getTableCellRendererComponent( - table, - value, - isSelected, - hasFocus, - row, - column - ); - - ImageIcon icon = null; - String text = null; - String toolTipText = null; - - column = table.convertColumnIndexToModel(column); - if (table.getRowSorter() != null) { - row = table.getRowSorter().convertRowIndexToModel(row); - } - - switch (column) { - case 0: - // scope - NuitonValidatorScope scope = (NuitonValidatorScope) value; - icon = SwingValidatorUtil.getIcon(scope); - String label = t(scope.getLabel()); - toolTipText = t("validator.scope.tip", label); - break; - - case 1: - // field name - text = getFieldName(table, (String) value, row); - toolTipText = t("validator.field.tip", text); - break; - - case 2: - // message - text = getMessage(table, (String) value, row); - toolTipText = t("validator.message.tip", text); - break; - } - - rendererComponent.setText(text); - rendererComponent.setToolTipText(toolTipText); - rendererComponent.setIcon(icon); - - ValidationMessageTableModel model = (ValidationMessageTableModel) table.getModel(); - - NuitonValidatorScope scope = (NuitonValidatorScope) ( - column == 0 ? value : model.getValueAt(row, 0)); - - Color textColor = scope == NuitonValidatorScope.WARNING ? Color.RED : Color.BLACK; - rendererComponent.setForeground(textColor); - - return rendererComponent; - } - - public ImageIcon getIcon(NuitonValidatorScope scope) { - ImageIcon icon = SwingValidatorUtil.getIcon(scope); - return icon; - } - - public String getMessage(JTable table, String value, int row) { - ValidationMessageTableModel tableModel = - (ValidationMessageTableModel) table.getModel(); - ValidationMessage validationMessage = tableModel.getRow(row); - String text = validationMessage.getMessage(); - return text; - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/ObserveValidatorMessageTableRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/ObserveValidatorMessageTableRenderer.java deleted file mode 100644 index 1eed2f2..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/ObserveValidatorMessageTableRenderer.java +++ /dev/null @@ -1,104 +0,0 @@ -package fr.ird.observe.ui.util; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.ObserveSwingApplicationContext; -import jaxx.runtime.validator.swing.SwingValidatorMessage; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableModel; -import jaxx.runtime.validator.swing.SwingValidatorMessageTableRenderer; -import org.apache.commons.lang3.BooleanUtils; -import org.nuiton.validator.NuitonValidatorScope; - -import javax.swing.JComponent; -import javax.swing.JTable; -import java.awt.Color; -import java.awt.Component; - -import static org.nuiton.i18n.I18n.t; - -/** -* Created on 12/13/14. -* -* @author Tony Chemit - chemit@codelutin.com -* @since XXX -*/ -public class ObserveValidatorMessageTableRenderer extends SwingValidatorMessageTableRenderer { - - private static final long serialVersionUID = 1L; - - protected transient DecoratorService decoratorService; - - public DecoratorService getDecoratorService() { - if (decoratorService == null) { - decoratorService = ObserveSwingApplicationContext.get().getDecoratorService(); - } - return decoratorService; - } - - @Override - public String getFieldName(JTable table, String value, int row) { - SwingValidatorMessageTableModel tableModel = (SwingValidatorMessageTableModel) table.getModel(); - SwingValidatorMessage model = tableModel.getRow(row); - JComponent editor = model.getEditor(); - String fieldName = null; - if (editor != null) { - String validatorLabel = (String) editor.getClientProperty("validatorLabel"); - - if (validatorLabel != null) { - fieldName = validatorLabel; - } - - Boolean doNotTranslateFieldName = (Boolean) editor.getClientProperty("doNotTranslateFieldName"); - if (BooleanUtils.isTrue(doNotTranslateFieldName)) { - fieldName = value; - } - } - - if (fieldName == null) { - fieldName = value; - - DecoratorService dService = getDecoratorService(); - if (!dService.getPropertyMatch(fieldName).matches()) { - fieldName = DecoratorService.getPropertyLabel(fieldName); - } - fieldName = t(fieldName); - } - - return fieldName; - } - - @Override - public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { - Component result = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - - SwingValidatorMessageTableModel model = (SwingValidatorMessageTableModel) table.getModel(); - - NuitonValidatorScope scope = (NuitonValidatorScope) ( - column == 0 ? value : model.getValueAt(row, 0)); - - Color textColor = scope == NuitonValidatorScope.WARNING ? Color.RED : Color.BLACK; - result.setForeground(textColor); - return result; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/SpringUtilities.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/SpringUtilities.java deleted file mode 100644 index 3c111a1..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/SpringUtilities.java +++ /dev/null @@ -1,250 +0,0 @@ -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -/* - * Copyright (c) 1995 - 2008 Sun Microsystems, Inc. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * - * - Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * - * - Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * - Neither the name of Sun Microsystems nor the names of its - * contributors may be used to endorse or promote products derived - * from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS - * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, - * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR - * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR - * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, - * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, - * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR - * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING - * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ - -package fr.ird.observe.ui.util; - -import javax.swing.Spring; -import javax.swing.SpringLayout; -import java.awt.Component; -import java.awt.Container; - -/** - * A 1.4 file that provides utility methods for - * creating form- or grid-style layouts with SpringLayout. - * These utilities are used by several programs, such as - * SpringBox and SpringCompactGrid. - * - * @author Tony Chemit - chemit@codelutin.com - */ -public class SpringUtilities { - /** - * A debugging utility that prints to stdout the component's - * minimum, preferred, and maximum sizes. - */ - public static void printSizes(Component c) { - System.out.println("minimumSize = " + c.getMinimumSize()); - System.out.println("preferredSize = " + c.getPreferredSize()); - System.out.println("maximumSize = " + c.getMaximumSize()); - } - - /** - * Aligns the first {@code rows} * {@code cols} - * components of {@code parent} in - * a grid. Each component is as big as the maximum - * preferred width and height of the components. - * The parent is made just big enough to fit them all. - * - * @param rows number of rows - * @param cols number of columns - * @param initialX x location to start the grid at - * @param initialY y location to start the grid at - * @param xPad x padding between cells - * @param yPad y padding between cells - */ - public static void makeGrid(Container parent, - int rows, int cols, - int initialX, int initialY, - int xPad, int yPad) { - SpringLayout layout; - try { - layout = (SpringLayout) parent.getLayout(); - } catch (ClassCastException exc) { - System.err.println("The first argument to makeGrid must use SpringLayout."); - return; - } - - Spring xPadSpring = Spring.constant(xPad); - Spring yPadSpring = Spring.constant(yPad); - Spring initialXSpring = Spring.constant(initialX); - Spring initialYSpring = Spring.constant(initialY); - int max = rows * cols; - - //Calculate Springs that are the max of the width/height so that all - //cells have the same size. - Spring maxWidthSpring = layout.getConstraints(parent.getComponent(0)). - getWidth(); - Spring maxHeightSpring = layout.getConstraints(parent.getComponent(0)). - getWidth(); - for (int i = 1; i < max; i++) { - SpringLayout.Constraints cons = layout.getConstraints( - parent.getComponent(i)); - - maxWidthSpring = Spring.max(maxWidthSpring, cons.getWidth()); - maxHeightSpring = Spring.max(maxHeightSpring, cons.getHeight()); - } - - //Apply the new width/height Spring. This forces all the - //components to have the same size. - for (int i = 0; i < max; i++) { - SpringLayout.Constraints cons = layout.getConstraints( - parent.getComponent(i)); - - cons.setWidth(maxWidthSpring); - cons.setHeight(maxHeightSpring); - } - - //Then adjust the x/y constraints of all the cells so that they - //are aligned in a grid. - SpringLayout.Constraints lastCons = null; - SpringLayout.Constraints lastRowCons = null; - for (int i = 0; i < max; i++) { - SpringLayout.Constraints cons = layout.getConstraints( - parent.getComponent(i)); - if (i % cols == 0) { //start of new row - lastRowCons = lastCons; - cons.setX(initialXSpring); - } else { //x position depends on previous component - cons.setX(Spring.sum(lastCons.getConstraint(SpringLayout.EAST), - xPadSpring)); - } - - if (i / cols == 0) { //first row - cons.setY(initialYSpring); - } else { //y position depends on previous row - cons.setY(Spring.sum(lastRowCons.getConstraint(SpringLayout.SOUTH), - yPadSpring)); - } - lastCons = cons; - } - - //Set the parent's size. - SpringLayout.Constraints pCons = layout.getConstraints(parent); - pCons.setConstraint(SpringLayout.SOUTH, - Spring.sum( - Spring.constant(yPad), - lastCons.getConstraint(SpringLayout.SOUTH))); - pCons.setConstraint(SpringLayout.EAST, - Spring.sum( - Spring.constant(xPad), - lastCons.getConstraint(SpringLayout.EAST))); - } - - /* Used by makeCompactGrid. */ - - private static SpringLayout.Constraints getConstraintsForCell( - int row, int col, - Container parent, - int cols) { - SpringLayout layout = (SpringLayout) parent.getLayout(); - Component c = parent.getComponent(row * cols + col); - return layout.getConstraints(c); - } - - /** - * Aligns the first {@code rows} * {@code cols} - * components of {@code parent} in - * a grid. Each component in a column is as wide as the maximum - * preferred width of the components in that column; - * height is similarly determined for each row. - * The parent is made just big enough to fit them all. - * - * @param rows number of rows - * @param cols number of columns - * @param initialX x location to start the grid at - * @param initialY y location to start the grid at - * @param xPad x padding between cells - * @param yPad y padding between cells - */ - public static void makeCompactGrid(Container parent, - int rows, int cols, - int initialX, int initialY, - int xPad, int yPad) { - SpringLayout layout; - try { - layout = (SpringLayout) parent.getLayout(); - } catch (ClassCastException exc) { - System.err.println("The first argument to makeCompactGrid must use SpringLayout."); - return; - } - - //Align all cells in each column and make them the same width. - Spring x = Spring.constant(initialX); - for (int c = 0; c < cols; c++) { - Spring width = Spring.constant(0); - for (int r = 0; r < rows; r++) { - width = Spring.max(width, - getConstraintsForCell(r, c, parent, cols). - getWidth()); - } - for (int r = 0; r < rows; r++) { - SpringLayout.Constraints constraints = - getConstraintsForCell(r, c, parent, cols); - constraints.setX(x); - constraints.setWidth(width); - } - x = Spring.sum(x, Spring.sum(width, Spring.constant(xPad))); - } - - //Align all cells in each row and make them the same height. - Spring y = Spring.constant(initialY); - for (int r = 0; r < rows; r++) { - Spring height = Spring.constant(0); - for (int c = 0; c < cols; c++) { - height = Spring.max(height, - getConstraintsForCell(r, c, parent, cols). - getHeight()); - } - for (int c = 0; c < cols; c++) { - SpringLayout.Constraints constraints = - getConstraintsForCell(r, c, parent, cols); - constraints.setY(y); - constraints.setHeight(height); - } - y = Spring.sum(y, Spring.sum(height, Spring.constant(yPad))); - } - - //Set the parent's size. - SpringLayout.Constraints pCons = layout.getConstraints(parent); - pCons.setConstraint(SpringLayout.SOUTH, y); - pCons.setConstraint(SpringLayout.EAST, x); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/AbstractSelectTableAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/AbstractSelectTableAction.java deleted file mode 100644 index 7959d50..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/AbstractSelectTableAction.java +++ /dev/null @@ -1,119 +0,0 @@ -package fr.ird.observe.ui.util.table; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import jaxx.runtime.swing.JTables; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.AbstractAction; -import javax.swing.JTable; - -/** - * Abstract action to select a cell in a table. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.8 - */ -public abstract class AbstractSelectTableAction<M extends EditableTableModelSupport> extends AbstractAction { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = - LogFactory.getLog(AbstractSelectTableAction.class); - - private final M model; - - private final JTable table; - - public AbstractSelectTableAction(M model, JTable table) { - this.model = model; - this.table = table; - } - - protected void doSelectCell(int rowIndex, int columnIndex) { - - if (log.isDebugEnabled()) { - log.debug("Will select cell at " + getCellCoordinate(rowIndex, columnIndex)); - } - JTables.doSelectCell(table, rowIndex, columnIndex); - } - - protected int getSelectedRow() { - int result = table.getSelectedRow(); - return result; - } - - protected int getSelectedColumn() { - int result = table.getSelectedColumn(); - return result; - } - - protected int getRowCount() { - return table.getRowCount(); - } - - protected int getColumnCount() { - return table.getColumnCount(); - } - - protected boolean isCellEditable(int rowIndex, int columnIndex) { - boolean result = rowIndex > -1 && columnIndex > -1 && - table.isCellEditable(rowIndex, columnIndex); - return result; - } - - protected boolean isCreateNewRow(int rowIndex) { - - boolean canCreateNewRow = model.isCanAddRow(); - - if (canCreateNewRow) { - - if (rowIndex == -1 && model.isEmpty()) { - - // model is empty, we surely can add a new row - canCreateNewRow = true; - - } else { - - // ask model if we can add a new row - canCreateNewRow = model.isCanCreateNewRow(rowIndex); - - } - - } - - return canCreateNewRow; - - } - - protected String getCellCoordinate(int rowIndex, int columnIndex) { - return " [" + rowIndex + ", " + columnIndex + "]"; - } - - protected void addNewRow() { - model.addNewRow(); - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/AutotSelectRowAndShowPopupActionSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/AutotSelectRowAndShowPopupActionSupport.java deleted file mode 100644 index 8a957a2..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/AutotSelectRowAndShowPopupActionSupport.java +++ /dev/null @@ -1,227 +0,0 @@ -package fr.ird.observe.ui.util.table; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import org.apache.commons.lang3.ArrayUtils; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import javax.swing.SwingUtilities; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; - -/** - * Created on 12/12/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.10 - */ -public abstract class AutotSelectRowAndShowPopupActionSupport { - - /** Logger. */ - private static final Log log = LogFactory.getLog(AutotSelectRowAndShowPopupActionSupport.class); - - private final JScrollPane pane; - - private final JTable table; - - private final JPopupMenu popup; - - protected AutotSelectRowAndShowPopupActionSupport(JScrollPane pane, final JTable table, JPopupMenu popup) { - this.pane = pane; - this.table = table; - this.popup = popup; - - KeyAdapter keyAdapter = new KeyAdapter() { - @Override - public void keyPressed(KeyEvent e) { - if (table.isEnabled()) { - openRowMenu(e); - } - } - }; - this.table.addKeyListener(keyAdapter); - pane.addKeyListener(keyAdapter); - - MouseAdapter mouseAdapter = new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - if (AutotSelectRowAndShowPopupActionSupport.this.table.isEnabled()) { - - autoSelectRowInTable(e); - - } - } - }; - this.table.addMouseListener(mouseAdapter); - pane.addMouseListener(mouseAdapter); - } - - public JPopupMenu getPopup() { - return popup; - } - - public JTable getTable() { - return table; - } - - protected abstract void beforeOpenPopup(int modelRowIndex, int modelColumnIndex); - - public void autoSelectRowInTable(MouseEvent e) { - - boolean rightClick = SwingUtilities.isRightMouseButton(e); - - if (rightClick || SwingUtilities.isLeftMouseButton(e)) { - - // get the coordinates of the mouse click - Point p = e.getPoint(); - - int[] selectedRows = table.getSelectedRows(); - int[] selectedColumns = table.getSelectedColumns(); - - // get the row index at this point - int rowIndex = table.rowAtPoint(p); - - // get the column index at this point - int columnIndex = table.columnAtPoint(p); - - if (log.isDebugEnabled()) { - log.debug("At point [" + p + "] found Row " + rowIndex + ", Column " + columnIndex); - } - - boolean canContinue = true; - - if (table.isEditing()) { - - // stop editing - boolean stopEdit = table.getCellEditor().stopCellEditing(); - if (!stopEdit) { - if (log.isWarnEnabled()) { - log.warn("Could not stop edit cell..."); - } - canContinue = false; - } - } - - if (canContinue) { - - // select row (could empty selection) - if (rowIndex == -1) { - table.clearSelection(); - } else if (!ArrayUtils.contains(selectedRows, rowIndex)) { - // set selection - table.setRowSelectionInterval(rowIndex, rowIndex); - } - - // select column (could empty selection) - if (columnIndex == -1) { - table.clearSelection(); - } else if (!ArrayUtils.contains(selectedColumns, columnIndex)) { - table.setColumnSelectionInterval(columnIndex, columnIndex); - } - - if (rightClick) { - - showPopup(rowIndex, columnIndex, p); - -// // use now model coordinate -// int modelRowIndex = rowIndex == -1 ? -1 : table.convertRowIndexToModel(rowIndex); -// int modelColumnIndex = columnIndex == -1 ? -1 : table.convertColumnIndexToModel(columnIndex); -// -// beforeOpenPopup(modelRowIndex, modelColumnIndex); -// -// // on right click show popup -// popup.show(table, e.getX(), e.getY()); - } - } - } - } - - public void openRowMenu(KeyEvent e) { - - if (e.getKeyCode() == KeyEvent.VK_CONTEXT_MENU) { - - // get the lowest selected row - int[] selectedRows = table.getSelectedRows(); - int lowestRow = -1; - for (int row : selectedRows) { - lowestRow = Math.max(lowestRow, row); - } - // get the selected column - int selectedColumn = table.getSelectedColumn(); - Rectangle r = table.getCellRect(lowestRow, selectedColumn, true); - - // get the point in the middle lower of the cell - Point p = new Point(r.x + r.width / 2, r.y + r.height); - - if (log.isDebugEnabled()) { - log.debug("Row " + lowestRow + " found t point [" + p + "]"); - } - - boolean canContinue = true; - - if (table.isEditing()) { - - // stop editing - boolean stopEdit = table.getCellEditor().stopCellEditing(); - if (!stopEdit) { - if (log.isWarnEnabled()) { - log.warn("Could not stop edit cell..."); - } - canContinue = false; - } - } - - if (canContinue) { - - showPopup(lowestRow, selectedColumn, p); - -// // use now model coordinate -// int rowIndex = table.convertRowIndexToModel(lowestRow); -// int columnIndex = table.convertColumnIndexToModel(selectedColumn); -// beforeOpenPopup(rowIndex, columnIndex); -// -// popup.show(table, p.x, p.y); - } - } - } - - protected void showPopup(int row, int column, Point p) { - - // use now model coordinate - int rowIndex = row == -1 ? -1 : table.convertRowIndexToModel(row); - int columnIndex = column == -1 ? -1 : table.convertColumnIndexToModel(column); - beforeOpenPopup(rowIndex, columnIndex); - - popup.show(table, p.x, p.y); - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/EditableList.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/EditableList.java deleted file mode 100644 index 5b7dad3..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/EditableList.java +++ /dev/null @@ -1,65 +0,0 @@ -package fr.ird.observe.ui.util.table; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * Created on 12/10/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.9 - */ -public class EditableList<E extends Serializable> implements Serializable { - - private static final long serialVersionUID = 1L; - - final List<E> original = new ArrayList<>(); - - final List<E> data = new ArrayList<>(); - - public List<E> getData() { - return data; - } - - public void setData(List<E> data) { - this.data.clear(); - this.data.addAll(data); - } - - public List<E> getOriginal() { - return original; - } - - public void setOriginal(List<E> data) { - this.original.clear(); - this.original.addAll(data); - } - - public void reset() { - setData(Collections.emptyList()); - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/EditableTableModelSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/EditableTableModelSupport.java deleted file mode 100644 index bd416fd..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/EditableTableModelSupport.java +++ /dev/null @@ -1,629 +0,0 @@ -package fr.ird.observe.ui.util.table; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import fr.ird.observe.ui.UIHelper; -import jaxx.runtime.swing.editor.cell.NumberCellEditor; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.jdesktop.swingx.autocomplete.ComboBoxCellEditor; - -import javax.swing.JTable; -import javax.swing.ListSelectionModel; -import javax.swing.event.ListSelectionListener; -import javax.swing.table.AbstractTableModel; -import javax.swing.table.TableCellEditor; -import javax.swing.table.TableColumn; -import javax.swing.table.TableColumnModel; -import java.awt.event.FocusAdapter; -import java.awt.event.FocusEvent; -import java.awt.event.KeyAdapter; -import java.awt.event.KeyEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Enumeration; -import java.util.List; - -/** - * Created on 12/3/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.8 - */ -public abstract class EditableTableModelSupport<E extends Serializable> extends AbstractTableModel { - - /** Logger. */ - private static final Log log = LogFactory.getLog(EditableTableModelSupport.class); - - public static final String EDITABLE_PROPERTY = "editable"; - - public static final String EMPTY_PROPERTY = "empty"; - - public static final String MODIFIED_PROPERTY = "modified"; - - public static final String VALID_PROPERTY = "valid"; - - public static final String SELECTED_ROW_INDEX_PROPERTY = "selectedRowIndex"; - - public static final String SELECTED_ROW_PROPERTY = "selectedRow"; - - public static final String SELECTION_EMPTY_PROPERTY = "selectionEmpty"; - - private static final long serialVersionUID = 1L; - - /** pour la propagation des modifications d'états */ - protected final PropertyChangeSupport pcs = new PropertyChangeSupport(this); - - /** un drapeau pour savoir si le modèle est éditable */ - protected boolean editable; - - /** un drapeau pour savoir si le modèle est valide */ - protected boolean valid; - - /** un drapeau pour savoir si le modèle est modifié */ - protected boolean modified; - - /** la ligne sélectionnée et en cours d'édition. */ - protected int selectedRowIndex = -1; /* -1 = pas de selection */ - - /** la liste des données du modèle */ - protected final List<E> data = new ArrayList<>(); - - private JTable table; - - private transient ListSelectionModel selectionModel; - - private final boolean canAddRow; - - protected transient ListSelectionListener whenSelectionModelChanged; - - protected EditableTableModelSupport(boolean canAddRow) { - this.canAddRow = canAddRow; - } - - public boolean isCanAddRow() { - return canAddRow; - } - - protected abstract E createNewRow(); - - public abstract boolean isRowNotEmpty(E valid); - - protected abstract boolean isRowValid(E valid); - - protected boolean isCanCreateNewRow(int rowIndex) { - - boolean canCreateNewRow = canAddRow; - if (canAddRow) { - E row = getData(rowIndex); - canCreateNewRow = isRowNotEmpty(row) && isRowValid(row); - } - - return canCreateNewRow; - - } - - public List<E> getNotEmptyData() { - List<E> result = new ArrayList<>(); - for (E row : data) { - if (isRowNotEmpty(row)) { - result.add(row); - } - } - return result; - } - - public List<E> getData() { - return data; - } - - public E getData(int rowIndex) { - return data.get(rowIndex); - } - - - @Override - public boolean isCellEditable(int rowIndex, int columnIndex) { - return true; - } - - @Override - public int getRowCount() { - return data.size(); - } - - public void setData(List<E> data) { - this.data.clear(); - this.data.addAll(data); - if (this.data.isEmpty() && editable && canAddRow) { - - // add an empty row (no fire and select: will be done just below) - addNewRow(0, false); - - } - - // reset previous selection - selectedRowIndex = -1; - - fireTableDataChanged(); - - // on selectionne la première ligne (ou supprime la selection si plus de donnes) - setSelectedRowIndex(isEmpty() ? -1 : 0, true); - - fireEmpty(); - - } - - public void removeData(int selectedRow) { - - this.data.remove(selectedRow); - fireTableRowsDeleted(selectedRow, selectedRow); - - // on selectionne la ligne précédente (ou supprime la selection si plus de donnes) - setSelectedRowIndex(isEmpty() ? -1 : selectedRow - 1, true); - - fireEmpty(); - - } - - public void removeSelectedRow() { - - // get selected row - int selectedRowIndex1 = getSelectedRowIndex(); - - // clear selection (to avoid any trouble while trying to access previous selected values which does not exists - // any long in data list) - setSelectedRowIndex(-1, true); - - // safe remove data - removeData(selectedRowIndex1); - - } - - public void addNewRow() { - - int row = getRowCount(); - addNewRow(row, true); - - } - - public void insertBeforeSelectedRow() { - - int currentRow = getSelectedRowIndex(); - - setSelectedRowIndex(-1); // clear selection - - int insertRow = currentRow; - if (insertRow < 0) { - insertRow = 0; - } - if (log.isInfoEnabled()) { - log.info("Insert before selected row: " + currentRow + " :: " + insertRow); - } - - addNewRow(insertRow, true); - } - - public void insertAfterSelectedRow() { - - int currentRow = getSelectedRowIndex(); - - setSelectedRowIndex(-1); // clear selection - - int insertRow = currentRow == getRowCount() ? currentRow : currentRow + 1; - if (log.isInfoEnabled()) { - log.info("Insert after selected row: " + currentRow + " :: " + insertRow); - } - - addNewRow(insertRow, true); - - } - - public void addNewRow(int row, boolean fireAndSelectNewRow) { - - ensureEditable(); - - // on est autorise a ajouter une nouvelle entrée - - E bean = createNewRow(); - - if (row == getRowCount()) { - - // add new row - data.add(bean); - - } else { - - // insert new row (but not at the end) - data.add(row, bean); - - } - - if (fireAndSelectNewRow) { - - fireTableRowsInserted(row, row); - fireEmpty(); - - // la nouvelle ligne est celle en cours d'edition - setSelectedRowIndex(row, true); - - } - - fireEmpty(); - - } - - public void clear() { - - setSelectedRowIndex(-1); - setData(Collections.emptyList()); - validate(); - setModified(false); - fireEmpty(); - - } - - public boolean isEmpty() { - return getRowCount() == 0; - } - - public boolean isSelectionEmpty() { - return getSelectedRowIndex() == -1; - } - - public E getSelectedRow() { - return isSelectionEmpty() ? null : getData(getSelectedRowIndex()); - } - - public int getSelectedRowIndex() { - return selectedRowIndex; - } - - public void setSelectedRowIndex(int selectedRowIndex) { - setSelectedRowIndex(selectedRowIndex, false); - } - - private boolean selectionIsAdjusting; - - public void setSelectedRowIndex(int selectedRowIndex, boolean pushToSelectionModel) { - - if (!selectionIsAdjusting) { - - selectionIsAdjusting = true; - - try { - - int oldSelectedRowIndex = getSelectedRowIndex(); - //boolean oldSelectionEmpty = isSelectionEmpty(); - E oldSelectedRow = getSelectedRow(); - - this.selectedRowIndex = selectedRowIndex; - - if (pushToSelectionModel && getSelectionModel() != null) { - - getSelectionModel().setSelectionInterval(selectedRowIndex, selectedRowIndex); - - } - - firePropertyChange(SELECTED_ROW_INDEX_PROPERTY, oldSelectedRowIndex, selectedRowIndex); - firePropertyChange(SELECTION_EMPTY_PROPERTY, null /* to force fire */, isSelectionEmpty()); - firePropertyChange(SELECTED_ROW_PROPERTY, oldSelectedRow, getSelectedRow()); - - } finally { - - selectionIsAdjusting = false; - - } - - } - - } - - public boolean isModified() { - return modified; - } - - public void setModified(boolean modified) { - this.modified = modified; - firePropertyChange(MODIFIED_PROPERTY, null, modified); - } - - public void addPropertyChangeListener(PropertyChangeListener listener) { - pcs.addPropertyChangeListener(listener); - } - - public void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { - pcs.addPropertyChangeListener(propertyName, listener); - } - - public void removePropertyChangeListener(PropertyChangeListener listener) { - pcs.removePropertyChangeListener(listener); - } - - public void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { - pcs.removePropertyChangeListener(propertyName, listener); - } - - public void firePropertyChange(String propertyName, Object oldValue, Object newValue) { - pcs.firePropertyChange(propertyName, oldValue, newValue); - } - - public void fireEmpty() { - firePropertyChange(EMPTY_PROPERTY, null, isEmpty()); - } - - protected void ensureEditable() throws IllegalStateException { - if (!editable) { - throw new IllegalStateException("can not edit this model since it is marked as none editable " + this); - } - } - - public void setEditable(Boolean editable) { - this.editable = editable; - } - - public boolean isValid() { - return valid; - } - - public void setValid(boolean valid) { - this.valid = valid; - firePropertyChange(VALID_PROPERTY, null, isValid()); - } - - public void validate() { - - boolean newValidValue = computeValidState(); - setValid(newValidValue); - - } - - protected boolean computeValidState() { - boolean newValidValue = true; - - for (E row : data) { - boolean rowValid = !isRowNotEmpty(row) || isRowValid(row); - if (!rowValid) { - newValidValue = false; - break; - } - } - return newValidValue; - } - - public void installSelectionListener(JTable table) { - - // always try to uninstall it before to avoid any memory leak - uninstallSelectionListener(table); - - this.table = table; - - ListSelectionListener listener = getWhenSelectionModelChanged(); - getSelectionModel().addListSelectionListener(listener); - - } - - public ListSelectionModel getSelectionModel() { - if (selectionModel == null) { - selectionModel = table == null ? null : table.getSelectionModel(); - } - return selectionModel; - } - - public void uninstallSelectionListener(JTable table) { - - ListSelectionListener listener = getWhenSelectionModelChanged(); - table.getSelectionModel().removeListSelectionListener(listener); - - this.table = null; - this.selectionModel = null; - - } - - private static final String OBSERVE_KEY_ADAPTER = "ObServeKeyAdapter"; - - private static final String OBSERVE_FOCUS_ADAPTER = "ObServeFocusAdapter"; - - public void installTableFocusListener(final JTable table) { - - // always try to uninstall it before to avoid any memory leak - uninstallTableFocusListener(table); - - FocusAdapter focusAdapter = new FocusAdapter() { - @Override - public void focusLost(FocusEvent e) { - - UIHelper.stopEditing(table); - } - }; - - Enumeration<TableColumn> columns = table.getColumnModel().getColumns(); - while (columns.hasMoreElements()) { - TableColumn tableColumn = columns.nextElement(); - TableCellEditor cellEditor = tableColumn.getCellEditor(); - if (cellEditor instanceof NumberCellEditor) { - NumberCellEditor editor = (NumberCellEditor) cellEditor; - editor.getNumberEditor().getTextField().addFocusListener(focusAdapter); - } else if (cellEditor instanceof ComboBoxCellEditor) { -// ComboBoxCellEditor editor = (ComboBoxCellEditor) cellEditor; - //FIXME should also use the focus listener here - } - } - - if (log.isDebugEnabled()) { - log.debug("Intall " + focusAdapter); - } - - table.putClientProperty(OBSERVE_FOCUS_ADAPTER, focusAdapter); - - } - - public void uninstallTableFocusListener(final JTable table) { - - FocusAdapter focusAdapter = (FocusAdapter) table.getClientProperty(OBSERVE_FOCUS_ADAPTER); - - if (focusAdapter != null) { - - if (log.isDebugEnabled()) { - log.debug("Desintall " + focusAdapter); - } - - TableColumnModel columnModel = table.getColumnModel(); - Enumeration<TableColumn> columns = columnModel.getColumns(); - while (columns.hasMoreElements()) { - TableColumn tableColumn = columns.nextElement(); - TableCellEditor cellEditor = tableColumn.getCellEditor(); - if (cellEditor instanceof NumberCellEditor) { - NumberCellEditor editor = (NumberCellEditor) cellEditor; - editor.getNumberEditor().getTextField().removeFocusListener(focusAdapter); - } - } - - table.putClientProperty(OBSERVE_KEY_ADAPTER, null); - } - } - - public void installTableKeyListener(final JTable table) { - - // always try to uninstall it before to avoid any memory leak - uninstallTableKeyListener(table); - - EditableTableModelSupport model = (EditableTableModelSupport) table.getModel(); - final MoveToNextEditableCellAction nextCellAction = MoveToNextEditableCellAction.newAction(model, table); - final MoveToPreviousEditableCellAction previousCellAction = MoveToPreviousEditableCellAction.newAction(model, table); - - final MoveToNextEditableRowAction nextRowAction = MoveToNextEditableRowAction.newAction(model, table); - final MoveToPreviousEditableRowAction previousRowAction = MoveToPreviousEditableRowAction.newAction(model, table); - - KeyAdapter keyAdapter = new KeyAdapter() { - - @Override - public void keyPressed(KeyEvent e) { - TableCellEditor editor = table.getCellEditor(); - - int keyCode = e.getKeyCode(); - if (keyCode == KeyEvent.VK_LEFT || - (keyCode == KeyEvent.VK_TAB && e.isShiftDown())) { - e.consume(); - if (editor != null) { - editor.stopCellEditing(); - } - previousCellAction.actionPerformed(null); - - } else if (keyCode == KeyEvent.VK_RIGHT || - keyCode == KeyEvent.VK_TAB) { - e.consume(); - if (editor != null) { - editor.stopCellEditing(); - } - nextCellAction.actionPerformed(null); - - } else if (keyCode == KeyEvent.VK_UP || - (keyCode == KeyEvent.VK_ENTER && e.isShiftDown())) { - e.consume(); - if (editor != null) { - editor.stopCellEditing(); - } - previousRowAction.actionPerformed(null); - - } else if (e.getKeyCode() == KeyEvent.VK_ENTER || - keyCode == KeyEvent.VK_DOWN) { - e.consume(); - if (editor != null) { - editor.stopCellEditing(); - } - nextRowAction.actionPerformed(null); - } - } - }; - - Enumeration<TableColumn> columns = table.getColumnModel().getColumns(); - while (columns.hasMoreElements()) { - TableColumn tableColumn = columns.nextElement(); - TableCellEditor cellEditor = tableColumn.getCellEditor(); - if (cellEditor instanceof NumberCellEditor) { - NumberCellEditor editor = (NumberCellEditor) cellEditor; - editor.getNumberEditor().getTextField().addKeyListener(keyAdapter); - - } - } - - if (log.isDebugEnabled()) { - log.debug("Intall " + keyAdapter); - } - - table.addKeyListener(keyAdapter); - table.putClientProperty(OBSERVE_KEY_ADAPTER, keyAdapter); - - } - - public void uninstallTableKeyListener(final JTable table) { - - KeyAdapter keyAdapter = (KeyAdapter) table.getClientProperty(OBSERVE_KEY_ADAPTER); - - if (keyAdapter != null) { - - if (log.isDebugEnabled()) { - log.debug("Desintall " + keyAdapter); - } - - table.removeKeyListener(keyAdapter); - - TableColumnModel columnModel = table.getColumnModel(); - Enumeration<TableColumn> columns = columnModel.getColumns(); - while (columns.hasMoreElements()) { - TableColumn tableColumn = columns.nextElement(); - TableCellEditor cellEditor = tableColumn.getCellEditor(); - if (cellEditor instanceof NumberCellEditor) { - NumberCellEditor editor = (NumberCellEditor) cellEditor; - editor.getNumberEditor().getTextField().removeKeyListener(keyAdapter); - } - } - table.putClientProperty(OBSERVE_KEY_ADAPTER, null); - } - } - - protected ListSelectionListener getWhenSelectionModelChanged() { - if (whenSelectionModelChanged == null) { - whenSelectionModelChanged = e -> { - - if (!e.getValueIsAdjusting()) { - int selectedRow = table.getSelectedRow(); - if (selectedRow >= getRowCount()) { - selectedRow = getRowCount() - 1; - if (log.isInfoEnabled()) { - log.info("Decrease selectedRow!!! to " + selectedRow); - } - } - setSelectedRowIndex(selectedRow); - } - - }; - } - return whenSelectionModelChanged; - } - -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/EditableTableWithCacheTableModelSupport.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/EditableTableWithCacheTableModelSupport.java deleted file mode 100644 index 42d5ad6..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/EditableTableWithCacheTableModelSupport.java +++ /dev/null @@ -1,151 +0,0 @@ -package fr.ird.observe.ui.util.table; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; -import fr.ird.observe.services.dto.IdDto; -import org.nuiton.util.beans.Binder; -import org.nuiton.util.beans.BinderFactory; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeMap; - -/** - * Created on 12/11/14. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.10 - */ -public abstract class EditableTableWithCacheTableModelSupport<E extends IdDto> extends EditableTableModelSupport<E> { - - private static final long serialVersionUID = 1L; - - /** - * Cache de liste de données par numéro de ligne. Cela sert à pouvoir conserver plusieurs listes - * de données issues de ce table. Typiquement dans l'écran de capture ll ou on doit conserver pour une capture - * (donc une ligne du tableau principal) n mesures de taille et n meausre de poids. - */ - protected final Map<Integer, EditableList<E>> cacheByRow; - - protected EditableTableWithCacheTableModelSupport() { - super(true); - this.cacheByRow = new TreeMap<>(); - } - - public List<E> getCacheForRow(int rowIndex) { - EditableList<E> measures = cacheByRow.get(rowIndex); - return measures == null ? null : measures.getData(); - } - - public void initCacheForRow(int editingRow, List<E> data) { - - EditableList<E> editableList = cacheByRow.get(editingRow); - Preconditions.checkState(editableList == null, "Cant have a list for row: " + editingRow); - editableList = new EditableList<>(); - - // Get a copy of the list (to avoid to edit the content of the list) - List<E> original = copyList(data); - editableList.setOriginal(original); - editableList.setData(data); - cacheByRow.put(editingRow, editableList); - - } - - public void storeInCacheForRow(int editingRow) { - - List<E> measures = getData(); - EditableList<E> editableList = cacheByRow.get(editingRow); - Preconditions.checkState(editableList != null, "No list found for row: " + editingRow); - editableList.setData(measures); - - } - - public void removeCacheForRow(int rowToDelete) { - - cacheByRow.remove(rowToDelete); - - List<Integer> rows = Lists.newArrayList(getCacheRowsChanged()); - Collections.sort(rows); - - for (Integer row : rows) { - - if (row > rowToDelete) { - - // set now to row -1 - EditableList<E> remove = cacheByRow.remove(row); - cacheByRow.put(row - 1, remove); - - } - } - - } - - public void resetCacheForRow(int rowtoReset) { - - EditableList<E> editableList = cacheByRow.get(rowtoReset); - Preconditions.checkState(editableList != null); - - // remove data from cache - editableList.reset(); - - // restore a copy of original data - List<E> newData = copyList(editableList.getOriginal()); - editableList.setData(newData); - setData(newData); - - validate(); - - } - - public Set<Integer> getCacheRowsChanged() { - Set<Integer> rows = cacheByRow.keySet(); - return rows; - } - - @Override - public void clear() { - - cacheByRow.clear(); - super.clear(); - - } - - protected List<E> copyList(List<E> data) { - List<E> copy = new ArrayList<>(data.size()); - for (E measure : data) { - E originalMeasure = createNewRow(); - - Class<E> sourceType = (Class<E>) originalMeasure.getClass(); - Binder<E, E> binder = BinderFactory.newBinder(sourceType); - binder.copy(measure, originalMeasure); - - copy.add(originalMeasure); - } - return copy; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/InlineTableAutotSelectRowAndShowPopupAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/InlineTableAutotSelectRowAndShowPopupAction.java deleted file mode 100644 index b6d949e..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/InlineTableAutotSelectRowAndShowPopupAction.java +++ /dev/null @@ -1,74 +0,0 @@ -package fr.ird.observe.ui.util.table; - -/*- - * #%L - * ObServe :: Application Swing - * %% - * Copyright (C) 2008 - 2016 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import javax.swing.JMenuItem; -import javax.swing.JPopupMenu; -import javax.swing.JScrollPane; -import javax.swing.JTable; -import java.io.Serializable; - -/** - * Created on 15/03/16. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 5.0 - */ -public class InlineTableAutotSelectRowAndShowPopupAction<E extends Serializable, M extends EditableTableModelSupport<E>> extends AutotSelectRowAndShowPopupActionSupport { - - private final JMenuItem addWidget; - private final JMenuItem deleteWidget; - private final M tableModel; - - public InlineTableAutotSelectRowAndShowPopupAction(JScrollPane scrollPane, - JTable table, - M tableModel, - JPopupMenu popup, - JMenuItem addWidget, - JMenuItem deleteWidget) { - super(scrollPane, table, popup); - this.addWidget = addWidget; - this.deleteWidget = deleteWidget; - this.tableModel = tableModel; - } - - @Override - protected void beforeOpenPopup(int modelRowIndex, int modelColumnIndex) { - - boolean canAdd = tableModel.isValid(); - boolean canDelete = !tableModel.isSelectionEmpty(); - - if (canDelete) { - - // check also that the row is not empty - E selectedData = tableModel.getSelectedRow(); - canDelete = tableModel.isRowNotEmpty(selectedData); - - } - - addWidget.setEnabled(canAdd); - deleteWidget.setEnabled(canDelete); - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/MoveToNextEditableCellAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/MoveToNextEditableCellAction.java deleted file mode 100644 index 88166de..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/MoveToNextEditableCellAction.java +++ /dev/null @@ -1,100 +0,0 @@ -package fr.ird.observe.ui.util.table; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JTable; -import java.awt.event.ActionEvent; - -/** - * Action to select next editable cell in a table. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.8 - */ -public class MoveToNextEditableCellAction<M extends EditableTableModelSupport> extends AbstractSelectTableAction<M> { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = - LogFactory.getLog(MoveToNextEditableCellAction.class); - - protected MoveToNextEditableCellAction(M model, JTable table) { - super(model, table); - } - - public static <M extends EditableTableModelSupport> MoveToNextEditableCellAction<M> newAction(M model, JTable table) { - return new MoveToNextEditableCellAction<>(model, table); - } - - @Override - public void actionPerformed(ActionEvent e) { - - int currentRow = getSelectedRow(); - int currentColumn = getSelectedColumn(); - - if (log.isDebugEnabled()) { - log.debug("Move to previous editable cell " + - getCellCoordinate(currentRow, currentColumn)); - } - - int columnCount = getColumnCount(); - - int rowCount = getRowCount(); - - if (currentRow <= rowCount || currentColumn <= columnCount) { - - // go to next cell - currentColumn++; - boolean canSelect = true; - - // select next cell - if (currentColumn >= columnCount) { - - // no more cell, so will move to next editable column on next row - currentColumn = 0; - currentRow++; - - if (currentRow == rowCount) { - - if (isCreateNewRow(currentRow -1)) { - - // create a new row in model - addNewRow(); - } else { - - // can not create new row, so do nothing - canSelect = false; - } - } - } - - if (canSelect) { - doSelectCell(currentRow, currentColumn); - } - } - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/MoveToNextEditableRowAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/MoveToNextEditableRowAction.java deleted file mode 100644 index 5b9e3f7..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/MoveToNextEditableRowAction.java +++ /dev/null @@ -1,92 +0,0 @@ -package fr.ird.observe.ui.util.table; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JTable; -import java.awt.event.ActionEvent; - -/** - * Action to select next editable row in a table. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.8 - */ -public class MoveToNextEditableRowAction<M extends EditableTableModelSupport> extends AbstractSelectTableAction<M> { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = - LogFactory.getLog(MoveToNextEditableRowAction.class); - - protected MoveToNextEditableRowAction(M model, JTable table) { - super(model, table); - } - - public static <M extends EditableTableModelSupport> MoveToNextEditableRowAction<M> newAction(M model, JTable table) { - return new MoveToNextEditableRowAction<>(model, table); - } - - @Override - public void actionPerformed(ActionEvent e) { - int currentRow = getSelectedRow(); - int currentColumn = getSelectedColumn(); - - if (log.isDebugEnabled()) { - log.debug("Move to next row editable cell " + - getCellCoordinate(currentRow, currentColumn)); - } - - int rowCount = getRowCount(); - - if (currentRow < rowCount) { - // go to next cell - currentRow++; - boolean canSelect = true; - - // select next cell - if (currentRow >= rowCount) { - - if (log.isDebugEnabled()) { - log.debug("No next row"); - } - - if (isCreateNewRow(currentRow - 1)) { - - // create a new row in model - addNewRow(); - - } else { - canSelect = false; - } - } - - if (canSelect) { - doSelectCell(currentRow, currentColumn); - } - } - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/MoveToPreviousEditableCellAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/MoveToPreviousEditableCellAction.java deleted file mode 100644 index dbe9e77..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/MoveToPreviousEditableCellAction.java +++ /dev/null @@ -1,80 +0,0 @@ -package fr.ird.observe.ui.util.table; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JTable; -import java.awt.event.ActionEvent; - -/** - * Action to select previous editable cell in a table. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.8 - */ -public class MoveToPreviousEditableCellAction<M extends EditableTableModelSupport> extends AbstractSelectTableAction<M> { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = - LogFactory.getLog(MoveToPreviousEditableCellAction.class); - - protected MoveToPreviousEditableCellAction(M model, JTable table) { - super(model, table); - } - - public static <M extends EditableTableModelSupport> MoveToPreviousEditableCellAction<M> newAction(M model, JTable table) { - return new MoveToPreviousEditableCellAction<>(model, table); - } - - @Override - public void actionPerformed(ActionEvent e) { - int currentRow = getSelectedRow(); - int currentColumn = getSelectedColumn(); - - if (log.isDebugEnabled()) { - log.debug("Move to previous editable cell, " + - getCellCoordinate(currentRow, currentColumn)); - } - - int columnCount = getColumnCount(); - - if (currentRow > 0 || currentColumn > 0) { - - // go to next cell - currentColumn--; - - // select next cell - if (currentColumn < 0) { - - currentColumn = columnCount - 1; - currentRow--; - } - - doSelectCell(currentRow, currentColumn); - } - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/MoveToPreviousEditableRowAction.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/MoveToPreviousEditableRowAction.java deleted file mode 100644 index 513a652..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/MoveToPreviousEditableRowAction.java +++ /dev/null @@ -1,71 +0,0 @@ -package fr.ird.observe.ui.util.table; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2014 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import javax.swing.JTable; -import java.awt.event.ActionEvent; - -/** - * Action to select previous editable row in a table. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.8 - */ -public class MoveToPreviousEditableRowAction<M extends EditableTableModelSupport> extends AbstractSelectTableAction<M> { - - private static final long serialVersionUID = 1L; - - /** Logger. */ - private static final Log log = - LogFactory.getLog(MoveToPreviousEditableRowAction.class); - - protected MoveToPreviousEditableRowAction(M model, JTable table) { - super(model, table); - } - - public static <M extends EditableTableModelSupport> MoveToPreviousEditableRowAction<M> newAction(M model, JTable table) { - return new MoveToPreviousEditableRowAction<>(model, table); - } - - @Override - public void actionPerformed(ActionEvent e) { - - int currentRow = getSelectedRow(); - int currentColumn = getSelectedColumn(); - - if (log.isDebugEnabled()) { - log.debug("Move to previous row editable cell " + - getCellCoordinate(currentRow, currentColumn)); - } - - if (currentRow > 0) { - - // go to next cell - currentRow--; - doSelectCell(currentRow, currentColumn); - } - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/ObserveBooleanTableCellRenderer.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/ObserveBooleanTableCellRenderer.java deleted file mode 100644 index a4a04fe..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/table/ObserveBooleanTableCellRenderer.java +++ /dev/null @@ -1,93 +0,0 @@ -package fr.ird.observe.ui.util.table; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import javax.swing.Icon; -import javax.swing.JCheckBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JTable; -import javax.swing.table.TableCellRenderer; -import java.awt.Color; -import java.awt.Component; -import java.util.function.Predicate; - -/** - * TODO A remonter dans JAXX. - * - * Created on 14/08/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 4.0.1.1 - */ -public class ObserveBooleanTableCellRenderer extends JCheckBox implements TableCellRenderer { - - private static final long serialVersionUID = 1L; - - protected final TableCellRenderer defaultDelegate; - - private final Predicate predicate; - - private static final Predicate<?> DEFAULT_PREDICATE = input -> (input != null && (Boolean) input); - - public ObserveBooleanTableCellRenderer(TableCellRenderer delegate, Predicate<?> predicate) { - this(delegate, null, predicate); - } - - public ObserveBooleanTableCellRenderer(TableCellRenderer delegate) { - //super(new BorderLayout()); - this(delegate, DEFAULT_PREDICATE); - - } - - public ObserveBooleanTableCellRenderer(TableCellRenderer delegate, Icon icon, Predicate<?> predicate) { - this.defaultDelegate = delegate; - this.predicate = predicate; - setOpaque(true); - setBorderPainted(true); - setHorizontalAlignment(JLabel.CENTER); - setIcon(icon); - } - - @Override - public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { - ((JComponent) defaultDelegate).setBackground(null); - JComponent render = (JComponent) defaultDelegate.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); - if (isSelected) { - setForeground(table.getSelectionForeground()); - setBackground(table.getSelectionBackground()); - } else { - setForeground(render.getForeground()); - setBackground(render.getBackground()); - if (row % 2 == 0) { - setBackground(Color.WHITE); - } - } - - boolean selectCheckBox = predicate.test(value); - setSelected(selectCheckBox); - - setBorder(render.getBorder()); - return this; - } -} \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/tripMap/ObserveMapPane.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/tripMap/ObserveMapPane.java deleted file mode 100644 index c02bff8..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/tripMap/ObserveMapPane.java +++ /dev/null @@ -1,366 +0,0 @@ -package fr.ird.observe.ui.util.tripMap; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.geotools.geometry.jts.ReferencedEnvelope; -import org.geotools.renderer.lite.RendererUtilities; -import org.geotools.styling.FeatureTypeStyle; -import org.geotools.styling.Rule; -import org.geotools.styling.Style; -import org.geotools.swing.JMapPane; -import org.geotools.swing.event.MapPaneAdapter; -import org.geotools.swing.event.MapPaneEvent; - -import java.awt.Color; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Point; -import java.awt.Polygon; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.util.List; - -import static org.nuiton.i18n.I18n.n; -import static org.nuiton.i18n.I18n.t; - -/** - * @author Sylvain Bavencoff - bavencoff@codelutin.com - */ -public class ObserveMapPane extends JMapPane { - - private static final long serialVersionUID = 1L; - private static final Log log = LogFactory.getLog(ObserveMapPane.class); - - protected static final int MARGIN = 10; - - protected static final int SCALE_HEIGHT = 15; - protected static final int SCALE_WIDTH_MAX = 200; - - protected static final int METERS_BY_MILES = 1852; - - protected int scaleWidth; - - protected String labelScaleUp; - - protected double rotation; - - public ObserveMapPane() { - labelScaleUp = "0 m"; - scaleWidth = 100; - rotation = 0; - addMapPaneListener(new MapPaneAdapter() { - @Override - public void onDisplayAreaChanged(MapPaneEvent ev) { - updateScale(); - } - }); - legendItems = Lists.newArrayList(); - - } - - - protected void updateScale() { - ReferencedEnvelope displayArea = getDisplayArea(); - double dpi = 2.54 / 100; // pour avoir l'echélle en metre/pixel - - try { - double meterPerPixel = RendererUtilities.calculateScale(displayArea, getWidth(), getHeight(), dpi); - - double maxWidthMeter = SCALE_WIDTH_MAX * meterPerPixel; - - double maxWidthMiles = maxWidthMeter / METERS_BY_MILES; - - int nbDigit = (int) Math.floor(Math.log10(maxWidthMiles)); - - int firstDigit = (int) Math.floor(maxWidthMiles / Math.pow(10, nbDigit)); // le premier chiffre significatif - - int useFirstDigit; - - if (firstDigit >= 5) { - useFirstDigit = 5; - } else if (firstDigit >= 2) { - useFirstDigit = 2; - } else { - useFirstDigit = 1; - } - - long scaleInMiles = useFirstDigit * (long) Math.pow(10, nbDigit); - - scaleWidth = (int) Math.round(scaleInMiles * METERS_BY_MILES / meterPerPixel); - - labelScaleUp = String.format("%,d " + t("observe.content.map.miles"), scaleInMiles); - - } catch (Exception e) { - if (log.isErrorEnabled()) { - log.error("error", e); - } - } - } - - protected void paintScale(Graphics graphics) { - graphics.setColor(Color.BLACK); - - FontMetrics fm = graphics.getFontMetrics(); - - Rectangle2D textArea = fm.getStringBounds(labelScaleUp, graphics); - - int labelLeft = getWidth() - MARGIN * 2 - scaleWidth - (int) textArea.getWidth(); - - graphics.drawString(labelScaleUp, labelLeft, getHeight() - MARGIN); - - int scalesEndX = getWidth() - MARGIN; - - int scaleStartX = scalesEndX - scaleWidth; - - int scalesEndY = getHeight() - MARGIN; - - int scaleStartY = scalesEndY - SCALE_HEIGHT; - - graphics.drawLine(scaleStartX, scaleStartY, scaleStartX, scalesEndY); - graphics.drawLine(scaleStartX, scalesEndY, scalesEndX, scalesEndY); - graphics.drawLine(scalesEndX, scalesEndY, scalesEndX, scaleStartY); - - } - - protected static int AXIS_LENGTH = 30; - - protected static int SUB_AXIS_LENGTH = 5; - - protected static int CENTER_MARGIN = 50; - - protected static int INTER_AXIS_TEXT = 3; - - protected static double FONT_SIZE = 12; - - - protected void paintCompass(Graphics graphics) { - - Point center = new Point(getWidth() - CENTER_MARGIN, CENTER_MARGIN); - - Font font = graphics.getFont(); - Font fontRatio = font.deriveFont((float) (FONT_SIZE)); - graphics.setFont(fontRatio); - - FontMetrics fm = graphics.getFontMetrics(); - - for (CardinalPoint cardinalPoint : CardinalPoint.values()) { - - Point2D direction = cardinalPoint.getDirection(rotation, AXIS_LENGTH, center); - - Point2D sommet1 = cardinalPoint.getDirection(rotation - Math.PI / 4, SUB_AXIS_LENGTH, center); - - Point2D sommet2 = cardinalPoint.getDirection(rotation + Math.PI / 4, SUB_AXIS_LENGTH, center); - - - Polygon polygon = new Polygon(); - polygon.addPoint((int) center.getX(), (int) center.getY()); - polygon.addPoint((int) direction.getX(), (int) direction.getY()); - polygon.addPoint((int) sommet2.getX(), (int) sommet2.getY()); - graphics.fillPolygon(polygon); - - graphics.drawLine((int) sommet1.getX(), (int) sommet1.getY(), (int) direction.getX(), (int) direction.getY()); - - Rectangle2D textArea = fm.getStringBounds(cardinalPoint.getLabel(), graphics); - - // on cherche la ditance entre le centre du text et sa bordure dans le direction donné - double l = cardinalPoint.distanceCenterBorder(rotation, textArea); - - Point2D textCenter = cardinalPoint.getDirection(rotation, AXIS_LENGTH + INTER_AXIS_TEXT + l, center); - - graphics.drawString( - cardinalPoint.getLabel(), - (int) (textCenter.getX() - textArea.getWidth() / 2), - (int) (textCenter.getY() + textArea.getHeight() / 2)); - } - - } - - - protected static int LEGEND_MARGIN = 3; - - protected List<ObserveMapPaneLegendItem> legendItems; - - public List<ObserveMapPaneLegendItem> getLegendItems() { - return legendItems; - } - - public void setLegendItems(List<ObserveMapPaneLegendItem> legendItems) { - this.legendItems = legendItems; - } - - protected void paintLegend(Graphics graphics) { - - if (legendItems != null) { - - int x = 0; - int y = getHeight() - ObserveMapPaneLegendItem.LEGEND_ITEM_HEIGHT * legendItems.size() - 2 * LEGEND_MARGIN; - - ObserverMapPanLegendDrawer drawer = new ObserverMapPanLegendDrawer(); - - FontMetrics fm = graphics.getFontMetrics(); - - int maxLabelWidth = 0; - - for (ObserveMapPaneLegendItem item : legendItems) { - Rectangle2D labelArea = fm.getStringBounds(item.getLabel(), graphics); - - maxLabelWidth = Math.max((int)labelArea.getWidth(), maxLabelWidth); - - } - - int legendWidth = ObserveMapPaneLegendItem.LEGEND_SYMBOL_WIDTH + maxLabelWidth + ObserveMapPaneLegendItem.LEGEND_MARGIN * 2; - - graphics.setColor(ObserveMapPaneLegendItem.LEGEND_BACKGROUND); - graphics.fillRect( - x, - y, - legendWidth, - LEGEND_MARGIN); - - y += LEGEND_MARGIN; - - for (ObserveMapPaneLegendItem item : legendItems) { - - graphics.setColor(ObserveMapPaneLegendItem.LEGEND_BACKGROUND); - graphics.fillRect( - x, - y, - legendWidth, - ObserveMapPaneLegendItem.LEGEND_ITEM_HEIGHT); - - BufferedImage symbole = new BufferedImage( - ObserveMapPaneLegendItem.LEGEND_SYMBOL_WIDTH, - ObserveMapPaneLegendItem.LEGEND_ITEM_HEIGHT, - BufferedImage.TYPE_INT_ARGB); - - Style style = item.getStyle(); - - for (FeatureTypeStyle featureTypeStyle : style.featureTypeStyles()) { - - for (Rule rule : featureTypeStyle.rules()) { - - if (rule.getFilter().evaluate(item.getSimpleFeature())) { - - drawer.drawDirect(symbole, item.getSimpleFeature(), rule); - - } - } - } - - graphics.drawImage(symbole, x + LEGEND_MARGIN, y, null); - - graphics.setColor(Color.BLACK); - - int labelMarginBottom = ((ObserveMapPaneLegendItem.LEGEND_ITEM_HEIGHT - fm.getHeight()) / 2) + fm.getDescent(); - - graphics.drawString(item.getLabel(), - x + LEGEND_MARGIN + ObserveMapPaneLegendItem.LEGEND_SYMBOL_WIDTH, - y + ObserveMapPaneLegendItem.LEGEND_ITEM_HEIGHT - labelMarginBottom); - - y += ObserveMapPaneLegendItem.LEGEND_ITEM_HEIGHT; - - } - - graphics.setColor(ObserveMapPaneLegendItem.LEGEND_BACKGROUND); - graphics.fillRect( - x, - y, - legendWidth, - LEGEND_MARGIN); - - } - - } - - - - @Override - public void paint(Graphics graphics) { - - super.paint(graphics); - - paintScale(graphics); - - paintCompass(graphics); - - paintLegend(graphics); - - } - - protected enum CardinalPoint { - NORTH(-1, 0, 0, -1, n("observe.content.map.north")), - SOUTH( 1, 0, 0, 1, n("observe.content.map.south")), - WEST ( 0, -1, 1, 0, n("observe.content.map.west")), - EST ( 0, 1, -1, 0, n("observe.content.map.east")); - - protected int matrix00; - protected int matrix01; - protected int matrix10; - protected int matrix11; - protected String label; - - CardinalPoint(int matrix00, int matrix01, int matrix10, int matrix11, String label) { - this.matrix00 = matrix00; - this.matrix01 = matrix01; - this.matrix10 = matrix10; - this.matrix11 = matrix11; - this.label = label; - } - - public Point2D.Double getDirection(double angle, double length, Point center) { - - double x = Math.sin(angle) * length; - double y = Math.cos(angle) * length; - - double deltaX = matrix00 * x + matrix01 * y; - double deltaY = matrix10 * x + matrix11 * y; - Point2D.Double result = new Point2D.Double(center.getX() + deltaX, center.getY() + deltaY); - - return result; - } - - // on cherche la ditance entre le centre du text et sa bordure dans le direction donné - public double distanceCenterBorder(double angle, Rectangle2D textArea) { - - double x = Math.sin(angle); - double y = Math.cos(angle); - - double deltaW = Math.abs(textArea.getWidth() / 2 / (matrix00 * x + matrix01 * y)); - double deltaH = Math.abs(textArea.getHeight() / 2 / (matrix10 * x + matrix11 * y)); - - double delta = Math.min(deltaH, deltaW); - - return delta; - } - - public String getLabel() { - return t(label); - } - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/tripMap/ObserveMapPaneLegendItem.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/tripMap/ObserveMapPaneLegendItem.java deleted file mode 100644 index a0ea0e2..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/tripMap/ObserveMapPaneLegendItem.java +++ /dev/null @@ -1,90 +0,0 @@ -package fr.ird.observe.ui.util.tripMap; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.vividsolutions.jts.geom.Coordinate; -import org.geotools.styling.Style; -import org.opengis.feature.simple.SimpleFeature; - -import java.awt.Color; - -/** - * @author Sylvain Bavencoff - bavencoff@codelutin.com - */ -public class ObserveMapPaneLegendItem { - - protected static final int LEGEND_ITEM_HEIGHT = 20; - protected static final int LEGEND_SYMBOL_WIDTH = 50; - protected static final int LEGEND_MARGIN = 5; - protected static final Color LEGEND_BACKGROUND = new Color(1f, 1f, 1f, 0.8f); - - - public static Coordinate[] lineCoordinates() { - Coordinate[] coordinates = new Coordinate[2]; - coordinates[0] = new Coordinate(LEGEND_MARGIN, LEGEND_ITEM_HEIGHT / 2); - coordinates[1] = new Coordinate(LEGEND_SYMBOL_WIDTH - LEGEND_MARGIN, LEGEND_ITEM_HEIGHT / 2); - return coordinates; - } - - public static Coordinate pointCoordinates() { - Coordinate coordinate = new Coordinate(LEGEND_SYMBOL_WIDTH / 2, LEGEND_ITEM_HEIGHT / 2); - return coordinate; - } - - - protected SimpleFeature simpleFeature; - - protected Style style; - - protected String label; - - public ObserveMapPaneLegendItem(SimpleFeature simpleFeature, Style style, String label) { - this.simpleFeature = simpleFeature; - this.style = style; - this.label = label; - } - - public SimpleFeature getSimpleFeature() { - return simpleFeature; - } - - public void setSimpleFeature(SimpleFeature simpleFeature) { - this.simpleFeature = simpleFeature; - } - - public Style getStyle() { - return style; - } - - public void setStyle(Style style) { - this.style = style; - } - - public String getLabel() { - return label; - } - - public void setLabel(String label) { - this.label = label; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/tripMap/ObserverMapPanLegendDrawer.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/tripMap/ObserverMapPanLegendDrawer.java deleted file mode 100644 index 8003536..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/tripMap/ObserverMapPanLegendDrawer.java +++ /dev/null @@ -1,111 +0,0 @@ -package fr.ird.observe.ui.util.tripMap; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.vividsolutions.jts.geom.Geometry; -import org.geotools.geometry.jts.LiteShape; -import org.geotools.legend.Drawer; -import org.geotools.styling.LineSymbolizer; -import org.geotools.styling.Rule; -import org.geotools.styling.SLD; -import org.geotools.styling.Symbolizer; -import org.opengis.feature.simple.SimpleFeature; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Stroke; -import java.awt.geom.AffineTransform; -import java.awt.image.BufferedImage; - -/** - * @author Sylvain Bavencoff - bavencoff@codelutin.com - */ -public class ObserverMapPanLegendDrawer { - - protected final Drawer drawer; - - - public ObserverMapPanLegendDrawer() { - drawer = Drawer.create(); - - } - - public void drawDirect(BufferedImage bi, SimpleFeature feature, Rule rule) { - AffineTransform affineTransform = new AffineTransform(); - - LiteShape shape = new LiteShape(null, affineTransform, false); - for (Symbolizer symbolizer : rule.getSymbolizers()) { - if (symbolizer instanceof LineSymbolizer) { - LineSymbolizer lineSymbolizer = (LineSymbolizer) symbolizer; - - Geometry geometry = findGeometry(feature, lineSymbolizer); - if (geometry != null) { - - Graphics graphics = bi.getGraphics(); - Graphics2D g = (Graphics2D) graphics; - - shape.setGeometry(geometry); - - - Color c = SLD.color(lineSymbolizer); - int w = SLD.width(lineSymbolizer); - float[] lineDash = SLD.lineDash(lineSymbolizer); - if (c != null && w > 0) { - g.setColor(c); - - Stroke str = new BasicStroke( - w, - BasicStroke.CAP_SQUARE, - BasicStroke.JOIN_MITER, - 10.0f, lineDash, 0.0f - ); - g.setStroke(str); - - g.draw(shape); - } - } - } else { - drawer.drawFeature(bi, feature, affineTransform, false, symbolizer, null, shape); - } - - } - - - } - - protected Geometry findGeometry(SimpleFeature feature, LineSymbolizer lineSymbolizer) { - String geomName = lineSymbolizer.getGeometryPropertyName(); - - Geometry geom; - if (geomName == null) { - geom = (Geometry) feature.getDefaultGeometry(); - } else { - geom = (Geometry) feature.getAttribute(geomName); - } - return geom; - } - - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/tripMap/TripMapContentBuilder.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/tripMap/TripMapContentBuilder.java deleted file mode 100644 index d2cbb80..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/tripMap/TripMapContentBuilder.java +++ /dev/null @@ -1,477 +0,0 @@ -package fr.ird.observe.ui.util.tripMap; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; -import com.google.common.collect.Sets; -import com.vividsolutions.jts.geom.Coordinate; -import com.vividsolutions.jts.geom.GeometryFactory; -import com.vividsolutions.jts.geom.LineString; -import com.vividsolutions.jts.geom.Point; -import com.vividsolutions.jts.geom.Polygon; -import fr.ird.observe.ObserveSwingTechnicalException; -import fr.ird.observe.services.dto.TripMapPointDto; -import fr.ird.observe.services.dto.constants.TripMapPointType; -import fr.ird.observe.services.util.I18nEnumUtil; -import org.apache.commons.lang3.StringUtils; -import org.apache.commons.lang3.time.DateUtils; -import org.geotools.data.FileDataStore; -import org.geotools.data.FileDataStoreFinder; -import org.geotools.data.simple.SimpleFeatureSource; -import org.geotools.factory.CommonFactoryFinder; -import org.geotools.feature.DefaultFeatureCollection; -import org.geotools.feature.simple.SimpleFeatureBuilder; -import org.geotools.feature.simple.SimpleFeatureTypeBuilder; -import org.geotools.geometry.jts.JTSFactoryFinder; -import org.geotools.map.FeatureLayer; -import org.geotools.map.Layer; -import org.geotools.map.MapContent; -import org.geotools.referencing.CRS; -import org.geotools.styling.NamedLayer; -import org.geotools.styling.SLD; -import org.geotools.styling.SLDParser; -import org.geotools.styling.Style; -import org.geotools.styling.StyleFactory; -import org.geotools.styling.StyledLayer; -import org.geotools.styling.StyledLayerDescriptor; -import org.geotools.styling.UserLayer; -import org.opengis.feature.simple.SimpleFeature; -import org.opengis.feature.simple.SimpleFeatureType; -import org.opengis.referencing.FactoryException; - -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.text.DateFormat; -import java.text.SimpleDateFormat; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -import static org.nuiton.i18n.I18n.t; - -/** - * @author Sylvain Bavencoff - bavencoff@codelutin.com - */ -public class TripMapContentBuilder { - - public static final String TRIP_LINES_LAYER_NAME = "Trip lines"; - public static final String TRIP_LONGLINE_FISHING_ZONE_LAYER_NAME = "Trip longline zone"; - public static final String TRIP_LONGLINE_LINE_LAYER_NAME = "Trip longline line"; - public static final String TRIP_POINTS_LAYER_NAME = "Trip points"; - - protected static final Set<TripMapPointType> TRIP_MAP_POINT_TYPES_IN_LEGEND = ImmutableSet.of( - TripMapPointType.seineActivityInHarbour, - TripMapPointType.seineActivityWithFreeSchoolType, - TripMapPointType.seineActivityWithObjectSchoolType, - TripMapPointType.longlineActivityInHarbour, - TripMapPointType.longlineActivityWithSettingStart, - TripMapPointType.longlineActivityWithSettingEnd, - TripMapPointType.longlineActivityWithHaulingStart, - TripMapPointType.longlineActivityWithHaulingEnd, - TripMapPointType.longlineActivityWithStation, - TripMapPointType.longlineActivityWithInteraction); - - public static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("dd/MM"); - - protected StyledLayerDescriptor styledLayerDescriptor; - protected final MapContent mapContent; - protected final List<ObserveMapPaneLegendItem> legendItems; - - public TripMapContentBuilder() { - mapContent = new MapContent(); - legendItems = Lists.newArrayList(); - } - - public MapContent getMapContent() { - return mapContent; - } - - public List<ObserveMapPaneLegendItem> getLegendItems() { - return legendItems; - } - - public void setStyledLayerDescriptor(File styleFile) throws FileNotFoundException { - - StyleFactory styleFactory = CommonFactoryFinder.getStyleFactory(null); - - SLDParser stylereader = new SLDParser(styleFactory, styleFile); - - styledLayerDescriptor = stylereader.parseSLD(); - } - - public void addLayer(File layerFile) throws IOException { - FileDataStore store = FileDataStoreFinder.getDataStore(layerFile); - SimpleFeatureSource featureSource = store.getFeatureSource(); - Style style = SLD.createSimpleStyle(featureSource.getSchema()); - style = findStyle(styledLayerDescriptor, store.getNames().get(0).getLocalPart(), null, style); - Layer layer = new FeatureLayer(featureSource, style, layerFile.getName()); - mapContent.addLayer(layer); - } - - public void addTripLine(List<TripMapPointDto> tripMapPoints) throws FactoryException { - - GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); - - SimpleFeatureTypeBuilder lineFeatureTypeBuilder = new SimpleFeatureTypeBuilder(); - lineFeatureTypeBuilder.setName("lineBuilder"); - lineFeatureTypeBuilder.setCRS(CRS.decode("EPSG:4326", true)); - lineFeatureTypeBuilder.add("line", LineString.class); - lineFeatureTypeBuilder.add("label", String.class); - lineFeatureTypeBuilder.add("type", String.class); - - SimpleFeatureType lineFeatureType = lineFeatureTypeBuilder.buildFeatureType(); - SimpleFeatureBuilder lineBuilder = new SimpleFeatureBuilder(lineFeatureType); - - DefaultFeatureCollection linesFeatures = new DefaultFeatureCollection(); - - List<Coordinate> coordinatesByDay = null; - - TripMapPointDto previousPoint = null; - - for (TripMapPointDto point : tripMapPoints) { - if (previousPoint == null) { - coordinatesByDay = Lists.newLinkedList(); - } else if (!DateUtils.isSameDay(previousPoint.getTime(), point.getTime())) { - - if (coordinatesByDay.size() > 1) { - LineString line = geometryFactory.createLineString(coordinatesByDay.toArray(new Coordinate[0])); - lineBuilder.add(line); - lineBuilder.add(DATE_FORMAT.format(previousPoint.getTime())); - lineBuilder.add("tripDay"); - SimpleFeature feature = lineBuilder.buildFeature(null); - - linesFeatures.add(feature); - } - - - Coordinate[] coordinates = { - new Coordinate(previousPoint.getLongitude(), previousPoint.getLatitude()), - new Coordinate(point.getLongitude(), point.getLatitude()), - }; - LineString lineBetweenTwoDays = geometryFactory.createLineString(coordinates); - lineBuilder.add(lineBetweenTwoDays); - lineBuilder.add(DateFormat.getDateInstance().format(previousPoint.getTime())); - lineBuilder.add("tripBetweenTwoDays"); - linesFeatures.add(lineBuilder.buildFeature(null)); - - coordinatesByDay = Lists.newLinkedList(); - } - - Coordinate coordinate = new Coordinate(point.getLongitude(), point.getLatitude()); - coordinatesByDay.add(coordinate); - - previousPoint = point; - } - - if (coordinatesByDay != null && coordinatesByDay.size() > 1) { - LineString line = geometryFactory.createLineString(coordinatesByDay.toArray(new Coordinate[0])); - lineBuilder.add(line); - lineBuilder.add(DATE_FORMAT.format(previousPoint.getTime())); - lineBuilder.add("tripDay"); - linesFeatures.add(lineBuilder.buildFeature(null)); - } - - Style styleLines = findStyle(styledLayerDescriptor, TRIP_LINES_LAYER_NAME, null); - - if (! linesFeatures.isEmpty()) { - Layer layerLines = new FeatureLayer(linesFeatures, styleLines, TRIP_LINES_LAYER_NAME); - mapContent.addLayer(layerLines); - } - - - // add line in legend - LineString line = geometryFactory.createLineString(ObserveMapPaneLegendItem.lineCoordinates()); - lineBuilder.add(line); - lineBuilder.add(""); - lineBuilder.add("tripDay"); - - ObserveMapPaneLegendItem legendTripDay = new ObserveMapPaneLegendItem( - lineBuilder.buildFeature(null), - styleLines, - t("observe.content.map.legend.tripDay")); - legendItems.add(legendTripDay); - - lineBuilder.add(line); - lineBuilder.add(""); - lineBuilder.add("tripBetweenTwoDays"); - ObserveMapPaneLegendItem legendTripBetweenTwoDays = new ObserveMapPaneLegendItem( - lineBuilder.buildFeature(null), - styleLines, - t("observe.content.map.legend.tripBetweenTwoDays")); - legendItems.add(legendTripBetweenTwoDays); - - } - - public void addLonglineFishingZone(List<TripMapPointDto> tripMapPoints) throws FactoryException { - GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); - - SimpleFeatureTypeBuilder polygonFeatureTypeBuilder = new SimpleFeatureTypeBuilder(); - polygonFeatureTypeBuilder.setName("longlineFishingZoneBuilder"); - polygonFeatureTypeBuilder.setCRS(CRS.decode("EPSG:4326", true)); - polygonFeatureTypeBuilder.add("zone", Polygon.class); - polygonFeatureTypeBuilder.add("label", String.class); - polygonFeatureTypeBuilder.add("type", String.class); - - SimpleFeatureType polygonFeatureType = polygonFeatureTypeBuilder.buildFeatureType(); - SimpleFeatureBuilder polygonBuilder = new SimpleFeatureBuilder(polygonFeatureType); - - DefaultFeatureCollection polygonsFeatures = new DefaultFeatureCollection(); - - for (int indexPoint = 3; indexPoint < tripMapPoints.size(); indexPoint++) { - if (tripMapPoints.get(indexPoint).getType().equals(TripMapPointType.longlineActivityWithHaulingEnd) - && tripMapPoints.get(indexPoint - 1).getType().equals(TripMapPointType.longlineActivityWithHaulingStart) - && tripMapPoints.get(indexPoint - 2).getType().equals(TripMapPointType.longlineActivityWithSettingEnd) - && tripMapPoints.get(indexPoint - 3).getType().equals(TripMapPointType.longlineActivityWithSettingStart)) { - - Coordinate[] coordinates = { - new Coordinate(tripMapPoints.get(indexPoint - 3).getLongitude(), tripMapPoints.get(indexPoint - 3).getLatitude()), - new Coordinate(tripMapPoints.get(indexPoint - 2).getLongitude(), tripMapPoints.get(indexPoint - 2).getLatitude()), - new Coordinate(tripMapPoints.get(indexPoint - 1).getLongitude(), tripMapPoints.get(indexPoint - 1).getLatitude()), - new Coordinate(tripMapPoints.get(indexPoint).getLongitude(), tripMapPoints.get(indexPoint).getLatitude()), - new Coordinate(tripMapPoints.get(indexPoint - 3).getLongitude(), tripMapPoints.get(indexPoint - 3).getLatitude()) - }; - - - Polygon polygon = geometryFactory.createPolygon(coordinates); - //polygon = (Polygon) polygon.convexHull(); // permet de transformer un poliqgone croisé en polygon convex - polygonBuilder.add(polygon); - polygonBuilder.add(DATE_FORMAT.format(tripMapPoints.get(indexPoint - 3).getTime())); - polygonBuilder.add("longlineFishingZone"); - SimpleFeature feature = polygonBuilder.buildFeature(null); - polygonsFeatures.add(feature); - - } - } - - if (!polygonsFeatures.isEmpty()) { - Style styleLines = findStyle(styledLayerDescriptor, TRIP_LONGLINE_FISHING_ZONE_LAYER_NAME, null); - Layer layerLines = new FeatureLayer(polygonsFeatures, styleLines, TRIP_LONGLINE_FISHING_ZONE_LAYER_NAME); - mapContent.addLayer(layerLines); - } - } - - public void addLonglineLine(List<TripMapPointDto> tripMapPoints) throws FactoryException { - GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); - - SimpleFeatureTypeBuilder lineFeatureTypeBuilder = new SimpleFeatureTypeBuilder(); - lineFeatureTypeBuilder.setName("longlineSettingBuilder"); - lineFeatureTypeBuilder.setCRS(CRS.decode("EPSG:4326", true)); - lineFeatureTypeBuilder.add("line", LineString.class); - lineFeatureTypeBuilder.add("type", String.class); - - SimpleFeatureType lineFeatureType = lineFeatureTypeBuilder.buildFeatureType(); - SimpleFeatureBuilder lineBuilder = new SimpleFeatureBuilder(lineFeatureType); - - DefaultFeatureCollection linesFeatures = new DefaultFeatureCollection(); - - List<Coordinate> defaultLineCoordinates = Lists.newLinkedList(); - - for (int indexPoint = 0; indexPoint < tripMapPoints.size(); indexPoint++) { - if (indexPoint > 1 && tripMapPoints.get(indexPoint).getType().equals(TripMapPointType.longlineActivityWithSettingEnd) - && tripMapPoints.get(indexPoint - 1).getType().equals(TripMapPointType.longlineActivityWithSettingStart) - || tripMapPoints.get(indexPoint).getType().equals(TripMapPointType.longlineActivityWithHaulingEnd) - && tripMapPoints.get(indexPoint - 1).getType().equals(TripMapPointType.longlineActivityWithHaulingStart)) { - - Coordinate[] coordinates = { - new Coordinate(tripMapPoints.get(indexPoint - 1).getLongitude(), tripMapPoints.get(indexPoint - 1).getLatitude()), - new Coordinate(tripMapPoints.get(indexPoint).getLongitude(), tripMapPoints.get(indexPoint).getLatitude()), - }; - - boolean setting = tripMapPoints.get(indexPoint).getType().equals(TripMapPointType.longlineActivityWithSettingEnd); - LineString lineString = geometryFactory.createLineString(coordinates); - lineBuilder.add(lineString); - lineBuilder.add(setting ? "setting" : "hauling"); - SimpleFeature feature = lineBuilder.buildFeature(null); - linesFeatures.add(feature); - - defaultLineCoordinates.clear(); - } - - if (! (tripMapPoints.get(indexPoint).getType().equals(TripMapPointType.longlineActivityWithSettingEnd) - || tripMapPoints.get(indexPoint).getType().equals(TripMapPointType.longlineActivityWithHaulingStart))) { - - defaultLineCoordinates.add(new Coordinate(tripMapPoints.get(indexPoint).getLongitude(), tripMapPoints.get(indexPoint).getLatitude())); - - } - - if ((tripMapPoints.get(indexPoint).getType().equals(TripMapPointType.longlineActivityWithSettingStart) - || indexPoint == tripMapPoints.size() - 1) && defaultLineCoordinates.size() > 1) { - - LineString lineString = geometryFactory.createLineString(defaultLineCoordinates.toArray( new Coordinate[0])); - lineBuilder.add(lineString); - lineBuilder.add("trip"); - SimpleFeature feature = lineBuilder.buildFeature(null); - linesFeatures.add(feature); - - defaultLineCoordinates.clear(); - - } - - - - } - - Style styleLines = findStyle(styledLayerDescriptor, TRIP_LONGLINE_LINE_LAYER_NAME, null); - if (!linesFeatures.isEmpty()) { - Layer layerLines = new FeatureLayer(linesFeatures, styleLines, TRIP_LONGLINE_LINE_LAYER_NAME); - mapContent.addLayer(layerLines); - } - - // add line in legend - LineString line = geometryFactory.createLineString(ObserveMapPaneLegendItem.lineCoordinates()); - lineBuilder.add(line); - lineBuilder.add("setting"); - - ObserveMapPaneLegendItem legendTripDay = new ObserveMapPaneLegendItem( - lineBuilder.buildFeature(null), - styleLines, - t("observe.content.map.legend.setting")); - legendItems.add(legendTripDay); - - line = geometryFactory.createLineString(ObserveMapPaneLegendItem.lineCoordinates()); - lineBuilder.add(line); - lineBuilder.add("hauling"); - - legendTripDay = new ObserveMapPaneLegendItem( - lineBuilder.buildFeature(null), - styleLines, - t("observe.content.map.legend.hauling")); - legendItems.add(legendTripDay); - - - } - - - public void addPoints(List<TripMapPointDto> tripMapPoints) throws FactoryException { - - GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(); - - SimpleFeatureTypeBuilder pointFeatureTypeBuilder = new SimpleFeatureTypeBuilder(); - pointFeatureTypeBuilder.setName("point Builder"); - pointFeatureTypeBuilder.setCRS(CRS.decode("EPSG:4326", true)); - pointFeatureTypeBuilder.add("point", Point.class); - pointFeatureTypeBuilder.add("label", String.class); - pointFeatureTypeBuilder.add("pointType", String.class); - - SimpleFeatureType pointFeatureType = pointFeatureTypeBuilder.buildFeatureType(); - SimpleFeatureBuilder pointBuilder = new SimpleFeatureBuilder(pointFeatureType); - - DefaultFeatureCollection pointsFeatures = new DefaultFeatureCollection(); - - Style stylePoints = findStyle(styledLayerDescriptor, TRIP_POINTS_LAYER_NAME, null); - - Set<TripMapPointType> pointTypeInLegend = Sets.newHashSet(); - - for (TripMapPointDto tripMapPoint : tripMapPoints) { - Coordinate coordinate = new Coordinate(tripMapPoint.getLongitude(), tripMapPoint.getLatitude()); - - TripMapPointType type = tripMapPoint.getType(); - - Point point = geometryFactory.createPoint(coordinate); - pointBuilder.add(point); - pointBuilder.add(DATE_FORMAT.format(tripMapPoint.getTime())); - pointBuilder.add(type.name()); - pointsFeatures.add(pointBuilder.buildFeature(null)); - - // add point in legend - if (TRIP_MAP_POINT_TYPES_IN_LEGEND.contains(type) && ! pointTypeInLegend.contains(type)) { - point = geometryFactory.createPoint(ObserveMapPaneLegendItem.pointCoordinates()); - pointBuilder.add(point); - pointBuilder.add(""); - pointBuilder.add(type.name()); - - ObserveMapPaneLegendItem legendPoint = new ObserveMapPaneLegendItem( - pointBuilder.buildFeature(null), - stylePoints, - I18nEnumUtil.getLabel(type)); - legendItems.add(legendPoint); - pointTypeInLegend.add(type); - } - - } - - if (! pointsFeatures.isEmpty()) { - Layer pointsLayer = new FeatureLayer(pointsFeatures, stylePoints, TRIP_POINTS_LAYER_NAME); - mapContent.addLayer(pointsLayer); - } - - } - - - protected Style findStyle(StyledLayerDescriptor styledLayerDescriptor, final String layerName, String styleName, Style defaultStyle) { - - Optional<StyledLayer> styledLayerOptional = styledLayerDescriptor.layers().stream().filter( input -> input.getName().equals(layerName)).findFirst(); - - Style style = defaultStyle; - - if (styledLayerOptional.isPresent()) { - - StyledLayer styledLayer = styledLayerOptional.get(); - - Style[] styles = new Style[0]; - - if (styledLayer instanceof UserLayer) { - - styles = ((UserLayer) styledLayer).getUserStyles(); - - } else if (styledLayer instanceof NamedLayer) { - - styles = ((NamedLayer) styledLayer).getStyles(); - - } - - if (styles.length == 1) { - - style = styles[0]; - - } else { - - for (Style styleTmp : styles) { - - if (StringUtils.isBlank(styleName) && styleTmp.isDefault() - || styleTmp.getName().equals(styleName)) { - - style = styleTmp; - } - } - } - } - - return style; - - } - - protected Style findStyle(StyledLayerDescriptor styledLayerDescriptor, final String layerName, String styleName) { - - Style style = findStyle(styledLayerDescriptor, layerName, styleName, null); - - if (style == null) { - throw new ObserveSwingTechnicalException(String.format("No style found for layer name '%s' and style name '%s'", layerName, styleName)); - } - return style; - - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/tripMap/TripMapUI.jaxx b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/tripMap/TripMapUI.jaxx deleted file mode 100644 index de519aa..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/tripMap/TripMapUI.jaxx +++ /dev/null @@ -1,53 +0,0 @@ -<!-- - #%L - ObServe :: Swing - %% - Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - %% - This program is free software: you can redistribute it and/or modify - it under the terms of the GNU General Public License as - published by the Free Software Foundation, either version 3 of the - License, or (at your option) any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public - License along with this program. If not, see - <http://www.gnu.org/licenses/gpl-3.0.html>. - #L% - --> -<JPanel id="tripMap" - layout="{new CardLayout()}"> - - <import> - java.awt.CardLayout - fr.ird.observe.ui.util.tripMap.ObserveMapPane - static org.nuiton.i18n.I18n.n - </import> - - <TripMapUIHandler id='handler' initializer='TripMapUIHandler.newHandler(this)'/> - - <script><![CDATA[ - -void $afterCompleteSetup() { - getHandler().initUI(); -} - -]]> - </script> - - <JPopupMenu id='mapPopupMenu'> - <JMenuItem id='zoomIt' onActionPerformed='getHandler().zoomIt()'/> - <JMenuItem id='exportPng' onActionPerformed='getHandler().exportPng()'/> - </JPopupMenu> - - <JLabel id="waitLoadingLabel"/> - - <ObserveMapPane id='observeMapPane' - constraints="BorderLayout.CENTER"/> - - -</JPanel> \ No newline at end of file diff --git a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/tripMap/TripMapUIHandler.java b/observe-application-swing/src/main/java/fr/ird/observe/ui/util/tripMap/TripMapUIHandler.java deleted file mode 100644 index 3fe4634..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/ui/util/tripMap/TripMapUIHandler.java +++ /dev/null @@ -1,363 +0,0 @@ -package fr.ird.observe.ui.util.tripMap; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Lists; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.ObserveSwingTechnicalException; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.services.dto.IdDtos; -import fr.ird.observe.services.dto.TripMapDto; -import fr.ird.observe.services.dto.TripMapPointDto; -import fr.ird.observe.ui.UIHelper; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.geotools.geometry.DirectPosition2D; -import org.geotools.geometry.jts.ReferencedEnvelope; -import org.geotools.swing.JMapPane; -import org.geotools.swing.event.MapPaneEvent; -import org.geotools.swing.event.MapPaneListener; - -import javax.imageio.ImageIO; -import java.awt.CardLayout; -import java.awt.Point; -import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionListener; -import java.awt.event.MouseWheelEvent; -import java.awt.event.MouseWheelListener; -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.util.List; - -import static org.nuiton.i18n.I18n.t; - -/** - * @author Sylvain Bavencoff - bavencoff@codelutin.com - */ -public class TripMapUIHandler { - - public static final double ZOOM_STEP_RATIO = 0.1; - - public static TripMapUIHandler newHandler(TripMapUI view) { - return new TripMapUIHandler(view); - } - - private static final Log log = LogFactory.getLog(TripMapUIHandler.class); - - protected final TripMapUI view; - - private ObserveSwingApplicationConfig config; - protected ReferencedEnvelope tripArea; - - protected boolean rendererRunning; - - public TripMapUIHandler(TripMapUI view) { - this.view = view; - } - - public void initUI() { - - ObserveMapPane mapPane = getObserveMapPane(); - - MouseMapListener mouseMapListener = new MouseMapListener(); - mapPane.addMouseWheelListener(mouseMapListener); - mapPane.addMouseMotionListener(mouseMapListener); - mapPane.addMouseListener(mouseMapListener); - mapPane.addMapPaneListener(new TripMapListener()); - - mapPane.setComponentPopupMenu(view.getMapPopupMenu()); - - rendererRunning = false; - - } - - public void setConfig(ObserveSwingApplicationConfig config) { - this.config = config; - - JMapPane mapPane = getObserveMapPane(); - mapPane.setBackground(config.getMapBackgroundColor()); - } - - protected ObserveMapPane getObserveMapPane() { - return view.getObserveMapPane(); - } - - public void doOpenMap(TripMapDto tripMapDto) { - - try { - ((CardLayout) view.getLayout()).first(view); - ObserveSwingApplicationContext.get().getMainUI().setBusy(true); - - ObserveMapPane mapPane = getObserveMapPane(); - - if (mapPane.getMapContent() != null) { - // appeler pour libéré les listeners - mapPane.getMapContent().dispose(); - } - - List<TripMapPointDto> tripMapPoints = Lists.newArrayList(tripMapDto.getPoints()); - - - TripMapContentBuilder mapContentBuilder = new TripMapContentBuilder(); - mapContentBuilder.setStyledLayerDescriptor(config.getMapStyleFile()); - - for (File layerFile : config.getMapLayerFiles()) { - mapContentBuilder.addLayer(layerFile); - } - - if (IdDtos.isSeineId(tripMapDto.getId())) { - - mapContentBuilder.addTripLine(tripMapPoints); - - } else if (IdDtos.isLonglineId(tripMapDto.getId())) { - - mapContentBuilder.addLonglineFishingZone(tripMapPoints); - mapContentBuilder.addLonglineLine(tripMapPoints); - - } - - mapContentBuilder.addPoints(tripMapPoints); - - // set zoom - tripArea = new ReferencedEnvelope(); - for (TripMapPointDto point : tripMapPoints) { - tripArea.expandToInclude(new DirectPosition2D(point.getLongitude(), point.getLatitude())); - } - tripArea.expandBy(1.1); - - mapPane.setMapContent(mapContentBuilder.getMapContent()); - mapPane.setLegendItems(mapContentBuilder.getLegendItems()); - - } catch (Exception e) { - throw new ObserveSwingTechnicalException("Unable to load trip map activity points", e); - } finally { - ObserveSwingApplicationContext.get().getMainUI().setBusy(false); - } - - } - - public void doCloseMap() { - ((CardLayout) view.getLayout()).first(view); - } - - public void zoomIt() { - if (! tripArea.isEmpty()) { - JMapPane mapPane = getObserveMapPane(); - mapPane.setDisplayArea(tripArea); - } - } - - public void exportPng() { - - File file = UIHelper.chooseFile( - view, - t("observe.content.map.export.chooseFile.title"), - t("observe.content.map.export.chooseFile.ok"), - null, - "^.+\\.png|.+\\.PNG$", - t("observe.content.map.export.chooseFile.png")); - - if (file != null && UIHelper.confirmOverwriteFileIfExist(view, file)) { - - BufferedImage im = new BufferedImage(view.getWidth(), view.getHeight(), BufferedImage.TYPE_INT_ARGB); - view.paint(im.getGraphics()); - try { - ImageIO.write(im, "PNG", file); - } catch (IOException e) { - throw new ObserveSwingTechnicalException("unable to export map ", e); - } - - UIHelper.displayInfo(t("observe.content.map.export.success", file)); - } - } - - protected double zoomRatio = 1; - protected Point zoomCenter; - - protected void zoomApply() { - if (zoomRatio != 1 && ! rendererRunning) { - - JMapPane mapPane = getObserveMapPane(); - - ReferencedEnvelope displayArea = mapPane.getDisplayArea(); - - double deltaWidth = displayArea.getWidth() * (zoomRatio -1); - double deltaHeight = displayArea.getHeight() * (zoomRatio - 1); - - double ratioLeft = zoomCenter.getX() * 1d / mapPane.getWidth(); - - // l'axe de Y est inversé entre le référentiel du composant swing et le référentiel géographique - double ratioTop = 1 - (zoomCenter.getY() * 1d / mapPane.getHeight()); - - double deltaLeft = deltaWidth * ratioLeft; - double deltaRight = deltaLeft - deltaWidth; - - double deltaTop = deltaHeight * ratioTop; - double deltaBottom = deltaTop - deltaHeight; - - if (log.isDebugEnabled()) { - log.debug(String.format("Map mouse zoom (zoom ratio : %s, deltaLeft : %s, deltaRight : %s, deltaTop : %s, deltaBottom : %s)", - zoomRatio, deltaLeft, deltaRight, deltaRight, deltaBottom)); - } - - ReferencedEnvelope newDisplayArea = new ReferencedEnvelope( - displayArea.getMinX() + deltaLeft, - displayArea.getMaxX() + deltaRight, - displayArea.getMinY() + deltaTop, - displayArea.getMaxY() + deltaBottom, - displayArea.getCoordinateReferenceSystem() - ); - - mapPane.setDisplayArea(newDisplayArea); - - zoomRatio = 1; - - } - - } - - private class MouseMapListener implements MouseWheelListener, MouseListener, MouseMotionListener { - - @Override - public void mouseWheelMoved(MouseWheelEvent e) { - int notches = e.getWheelRotation(); - zoomRatio = zoomRatio * (1 + (ZOOM_STEP_RATIO * notches * -1)); - zoomCenter = e.getPoint(); - zoomApply(); - } - - @Override - public void mouseClicked(MouseEvent e) { - - } - - protected Point2D startPointInWorld; - protected AffineTransform startScreenToWorldTransform; - protected ReferencedEnvelope startDisplayArea; - - @Override - public void mousePressed(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON1) { - startMove(e.getPoint()); - } - } - - @Override - public void mouseReleased(MouseEvent e) { - if (e.getButton() == MouseEvent.BUTTON1) { - endMove(e.getPoint()); - } - } - - @Override - public void mouseEntered(MouseEvent e) { - - } - - @Override - public void mouseExited(MouseEvent e) { - - } - - @Override - public void mouseDragged(MouseEvent e) { -// endMove(e.getPoint()); - } - - @Override - public void mouseMoved(MouseEvent e) { - - } - - protected void startMove(Point2D startPointInScreen) { - JMapPane mapPane = getObserveMapPane(); - - startDisplayArea = mapPane.getDisplayArea(); - - startScreenToWorldTransform = mapPane.getScreenToWorldTransform(); - - startPointInWorld = new Point2D.Double(); - - startScreenToWorldTransform.transform(startPointInScreen, startPointInWorld); - - } - - protected void endMove(Point2D endPointInScreen) { - - Point2D endPointInWorld = new Point2D.Double(); - - startScreenToWorldTransform.transform(endPointInScreen, endPointInWorld); - - double transX = startPointInWorld.getX() - endPointInWorld.getX(); - double transY = startPointInWorld.getY() - endPointInWorld.getY(); - - ReferencedEnvelope endDisplayArea = new ReferencedEnvelope(startDisplayArea); - - endDisplayArea.translate(transX, transY); - - JMapPane mapPane = getObserveMapPane(); - - mapPane.setDisplayArea(endDisplayArea); - - if (log.isDebugEnabled()) { - log.debug(String.format("Translate (x : %s, y : %s)", transX, transY)); - } - } - } - - protected class TripMapListener implements MapPaneListener { - - protected boolean firstRendering; - - @Override - public void onNewMapContent(MapPaneEvent ev) { - firstRendering = true; - } - - @Override - public void onDisplayAreaChanged(MapPaneEvent ev) { - } - - @Override - public void onRenderingStarted(MapPaneEvent ev) { - rendererRunning = true; - } - - @Override - public void onRenderingStopped(MapPaneEvent ev) { - rendererRunning = false; - if (firstRendering) { - zoomIt(); - ((CardLayout) view.getLayout()).last(view); - firstRendering = false; - } else { - zoomApply(); - } - } - } - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/validation/ObserveSwingValidator.java b/observe-application-swing/src/main/java/fr/ird/observe/validation/ObserveSwingValidator.java deleted file mode 100644 index 3693948..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/validation/ObserveSwingValidator.java +++ /dev/null @@ -1,179 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.validation; - -import com.opensymphony.xwork2.ActionContext; -import com.opensymphony.xwork2.util.ValueStack; -import fr.ird.observe.ObserveSwingApplicationContext; -import jaxx.runtime.validator.swing.SwingValidator; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.nuiton.validator.NuitonValidatorFactory; -import org.nuiton.validator.NuitonValidatorProvider; -import org.nuiton.validator.NuitonValidatorScope; -import org.nuiton.validator.xwork2.XWork2ValidatorUtil; - -/** - * Une surcharge du validateur swing offert par jaxx pour pouvoir ajouter dans - * la stack le DataContext (pour faire de la validation sur le context de - * données d'un niveau supérieur (valider une marée à partir d'une route par - * exemple). - * - * @param <B> le type d'objet a valider - * @author Tony Chemit - chemit@codelutin.com - * @since 1.0 - */ -public class ObserveSwingValidator<B> extends SwingValidator<B> { - - /** Logger */ - private static final Log log = LogFactory.getLog(ObserveSwingValidator.class); - - /** un etat pour initialiser la stack une unique fois la stack */ - private static boolean init; - - private static ValidationContext validationContext; - - public static <B> ObserveSwingValidator<B> newValidator(Class<B> type, - String context, - NuitonValidatorScope... scopes) { - return new ObserveSwingValidator<>( - type, - context, - scopes - ); - } - - public static <B> ObserveSwingValidator<B> newValidator(NuitonValidatorProvider provider, - Class<B> type, - String context, - NuitonValidatorScope... scopes) { - return new ObserveSwingValidator<>( - provider, - type, - context, - scopes - ); - } - - public ObserveSwingValidator( - Class<B> type, - String context, - NuitonValidatorScope... scopes) { - super(NuitonValidatorFactory.getDefaultProvider(), type, context, scopes); - } - - public ObserveSwingValidator(NuitonValidatorProvider provider, - Class<B> type, - String context, - NuitonValidatorScope... scopes) { - super(provider, type, context, scopes); - } - - @Override - protected void rebuildDelegateValidator(Class<B> beanType, - String context, - NuitonValidatorScope... scopes) { - super.rebuildDelegateValidator(beanType, context, scopes); - - if (isInit()) { - // deja initialise - return; - } - - // on positionne dans la stack de dataContext pour pouvoir faire de la - // validation sur des objets dans le scope. - - ValidationContext dataContext = getValidationContext(); - if (dataContext == null) { - - // aucun context de validation enregistré - if (log.isDebugEnabled()) { - log.debug("No validation context registred, try in application context..."); - } - ObserveSwingApplicationContext rootContext = ObserveSwingApplicationContext.get(); - if (rootContext == null) { - throw new IllegalStateException( - "pas de context d'application enregistré... utiliser la " + - "methode " + - //FIXME -// DataSourceFactory.class.getName() + - "#setApplicationContext(context)"); - } - dataContext = rootContext.getValidationContext(); - } - - reloadDataContext(dataContext, true); - - // on marque pour ne jamais revenir ici - setInit(true); - } - - public static void reloadDataContext(ValidationContext validationContext, boolean strict) { - if (validationContext != ObserveSwingValidator.validationContext) { - - // keep this validation context - ObserveSwingValidator.validationContext = validationContext; - setInit(false); - } - ValueStack valueStack; - ActionContext context = ActionContext.getContext(); - if (context == null) { - - if (strict) { - throw new IllegalStateException( - "pas de context xworks enregistré... utiliser la methode " + - ActionContext.class.getName() + "#setContext(context)"); - } - - valueStack = XWork2ValidatorUtil.getSharedValueStack(); - if (valueStack == null) { - return; - } - } else { - valueStack = context.getValueStack(); - } - - if (log.isDebugEnabled()) { - log.debug("Enregistrement du context de validation [" + validationContext + "] dans la valueStack de " + - "validation (" + valueStack + ')'); - } - - valueStack.push(validationContext); - } - - public static ValidationContext getValidationContext() { - if (validationContext == null) { - validationContext = ObserveSwingApplicationContext.get().getValidationContext(); - } - return validationContext; - } - - private static boolean isInit() { - return init; - } - - private static void setInit(boolean init) { - ObserveSwingValidator.init = init; - } - - -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/validation/ValidationContext.java b/observe-application-swing/src/main/java/fr/ird/observe/validation/ValidationContext.java deleted file mode 100644 index 61f176f..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/validation/ValidationContext.java +++ /dev/null @@ -1,317 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.validation; - -import fr.ird.observe.ObserveOpenDataManager; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.application.swing.decoration.DecoratorService; -import fr.ird.observe.db.DataContext; -import fr.ird.observe.db.ObserveSwingDataSource; -import fr.ird.observe.services.dto.IdDto; -import fr.ird.observe.services.dto.longline.ActivityLonglineDto; -import fr.ird.observe.services.dto.longline.SetLonglineDto; -import fr.ird.observe.services.dto.longline.TripLonglineDto; -import fr.ird.observe.services.dto.referential.SpeciesDto; -import fr.ird.observe.services.dto.seine.ActivitySeineDto; -import fr.ird.observe.services.dto.seine.FloatingObjectDto; -import fr.ird.observe.services.dto.seine.RouteDto; -import fr.ird.observe.services.dto.seine.SetSeineDto; -import fr.ird.observe.services.dto.seine.TripSeineDto; -import fr.ird.observe.services.service.ReferentialService; -import fr.ird.observe.services.service.longline.ActivityLonglineService; -import fr.ird.observe.services.service.longline.SetLonglineService; -import fr.ird.observe.services.service.longline.TripLonglineService; -import fr.ird.observe.services.service.seine.ActivitySeineService; -import fr.ird.observe.services.service.seine.FloatingObjectService; -import fr.ird.observe.services.service.seine.RouteService; -import fr.ird.observe.services.service.seine.SetSeineService; -import fr.ird.observe.services.service.seine.TripSeineService; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import java.util.List; -import java.util.Map; -import java.util.TreeMap; - -/** - * Contient les objets en cours de validation. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.4 - */ -public class ValidationContext { - - /** Logger */ - static private final Log log = LogFactory.getLog(ValidationContext.class); - - public static final String VALIDATION_TRANSACTION_NAME = "validation"; - - private static final DtoSupplier<TripSeineDto> TRIP_SEINE_DTO_SUPPLIER = new DtoSupplier<TripSeineDto>() { - - @Override - public TripSeineDto get(ObserveSwingDataSource dataSource, String id) { - TripSeineService service = dataSource.newTripSeineService(); - TripSeineDto dto = service.loadDto(id); - return dto; - } - }; - - private static final DtoSupplier<RouteDto> ROUTE_DTO_SUPPLIER = new DtoSupplier<RouteDto>() { - - @Override - public RouteDto get(ObserveSwingDataSource dataSource, String id) { - RouteService service = dataSource.newRouteService(); - RouteDto dto = service.loadDto(id); - return dto; - } - }; - - private static final DtoSupplier<ActivitySeineDto> ACTIVITY_SEINE_DTO_SUPPLIER = new DtoSupplier<ActivitySeineDto>() { - - @Override - public ActivitySeineDto get(ObserveSwingDataSource dataSource, String id) { - ActivitySeineService service = dataSource.newActivitySeineService(); - ActivitySeineDto dto = service.loadDto(id); - return dto; - } - }; - - private static final DtoSupplier<TripLonglineDto> TRIP_LONGLINE_DTO_SUPPLIER = new DtoSupplier<TripLonglineDto>() { - - @Override - public TripLonglineDto get(ObserveSwingDataSource dataSource, String id) { - TripLonglineService service = dataSource.newTripLonglineService(); - TripLonglineDto dto = service.loadDto(id); - return dto; - } - }; - - private static final DtoSupplier<ActivityLonglineDto> ACTIVITY_LONGLINE_DTO_SUPPLIER = new DtoSupplier<ActivityLonglineDto>() { - - @Override - public ActivityLonglineDto get(ObserveSwingDataSource dataSource, String id) { - ActivityLonglineService service = dataSource.newActivityLonglineService(); - ActivityLonglineDto dto = service.loadDto(id); - return dto; - } - }; - - private static final DtoSupplier<SetSeineDto> SET_SEINE_DTO_SUPPLIER = new DtoSupplier<SetSeineDto>() { - - @Override - public SetSeineDto get(ObserveSwingDataSource dataSource, String id) { - SetSeineService service = dataSource.newSetSeineService(); - SetSeineDto dto = service.loadDto(id); - return dto; - } - }; - - private static final DtoSupplier<SetLonglineDto> SET_LONGLINE_DTO_SUPPLIER = new DtoSupplier<SetLonglineDto>() { - - @Override - public SetLonglineDto get(ObserveSwingDataSource dataSource, String id) { - SetLonglineService service = dataSource.newSetLonglineService(); - SetLonglineDto dto = service.loadDto(id); - return dto; - } - }; - - private static final DtoSupplier<FloatingObjectDto> FLOATING_OBJECT_DTO_SUPPLIER = new DtoSupplier<FloatingObjectDto>() { - - @Override - public FloatingObjectDto get(ObserveSwingDataSource dataSource, String id) { - FloatingObjectService service = dataSource.newFloatingObjectService(); - FloatingObjectDto dto = service.loadDto(id); - return dto; - } - }; - - private static final DtoSupplier<SpeciesDto> SPECIES_DTO_SUPPLIER = new DtoSupplier<SpeciesDto>() { - - @Override - public SpeciesDto get(ObserveSwingDataSource dataSource, String id) { - ReferentialService service = dataSource.newReferentialService(); - SpeciesDto dto = service.loadSpecies(id); - return dto; - } - }; - - protected final DataContext dataContext; - - protected Map<String, Object> cache; - - private List<?> referentielList; - - public Map<String, Object> getCache() { - if (cache == null) { - cache = new TreeMap<>(); - } - return cache; - } - - public void cleanCache() { - getCache().clear(); - referentielList = null; - } - - public ValidationContext(DataContext dataContext) { - this.dataContext = dataContext; - } - - public DecoratorService getDecoratorService() { - return ObserveSwingApplicationContext.get().getDecoratorService(); - } - - public ObserveOpenDataManager getOpenDataManager() { - return ObserveSwingApplicationContext.get().getOpenDataManager(); - } - - public DataContext getDataContext() { - return dataContext; - } - - public TripSeineDto getCurrentTripSeine() { - String tripSeineId = dataContext.getSelectedTripSeineId(); - TripSeineDto result = null; - if (tripSeineId != null) { - result = getDto(TRIP_SEINE_DTO_SUPPLIER, tripSeineId); - } - return result; - } - - public TripLonglineDto getCurrentTripLongline() { - String tripLonglineId = dataContext.getSelectedTripLonglineId(); - TripLonglineDto result = null; - if (tripLonglineId != null) { - result = getDto(TRIP_LONGLINE_DTO_SUPPLIER, tripLonglineId); - } - return result; - } - - public RouteDto getCurrentRoute() { - String routeId = dataContext.getSelectedRouteId(); - RouteDto result = null; - if (routeId != null) { - result = getDto(ROUTE_DTO_SUPPLIER, routeId); - } - return result; - } - - public ActivitySeineDto getCurrentActivitySeine() { - String activitySeineId = dataContext.getSelectedActivitySeineId(); - ActivitySeineDto result = null; - if (activitySeineId != null) { - result = getDto(ACTIVITY_SEINE_DTO_SUPPLIER, activitySeineId); - } - return result; - } - - public ActivityLonglineDto getCurrentActivityLongline() { - String activityLonglineId = dataContext.getSelectedActivityLonglineId(); - ActivityLonglineDto result = null; - if (activityLonglineId != null) { - result = getDto(ACTIVITY_LONGLINE_DTO_SUPPLIER, activityLonglineId); - } - return result; - } - - public SetSeineDto getCurrentSetSeine() { - String setSeineId = dataContext.getSelectedSetSeineId(); - SetSeineDto result = null; - if (setSeineId != null) { - result = getDto(SET_SEINE_DTO_SUPPLIER, setSeineId); - } - return result; - } - - public SetLonglineDto getCurrentSetLongline() { - String setLonglineId = dataContext.getSelectedSetLonglineId(); - SetLonglineDto result = null; - if (setLonglineId != null) { - result = getDto(SET_LONGLINE_DTO_SUPPLIER, setLonglineId); - } - return result; - } - - public FloatingObjectDto getCurrentFloatingObject() { - String floatingObjectId = dataContext.getSelectedFloatingObjectId(); - FloatingObjectDto result = null; - if (floatingObjectId != null) { - result = getDto(FLOATING_OBJECT_DTO_SUPPLIER, floatingObjectId); - } - return result; - } - - public SpeciesDto getSpecies(String speciesId) { - SpeciesDto result = null; - if (speciesId != null) { - result = getDto(SPECIES_DTO_SUPPLIER, speciesId); - } - return result; - } - - public List<?> getEditingReferentielList() { - return referentielList; - } - - public void setEditingReferentielList(List<?> referentielList) { - if (log.isDebugEnabled()) { - log.debug("Add referentielList (size : " + (referentielList == null ? 0 : referentielList.size()) + ")"); - } - this.referentielList = referentielList; - } - - protected <D extends IdDto> D getDto(DtoSupplier<D> dtoSupplier, String id) { - Object o = getCache().get(id); - if (o != null) { - if (log.isDebugEnabled()) { - log.debug("Use cached entity : " + id); - } - // found in cache - return (D) o; - } - - D result = dtoSupplier.get(id); - - if (result != null) { - if (log.isInfoEnabled()) { - log.info("Put entity into cache : " + id); - } - getCache().put(id, result); - - } - - return result; - } - - protected static abstract class DtoSupplier<D extends IdDto> { - - public final D get(String id) { - ObserveSwingDataSource dataSource = ObserveSwingApplicationContext.get().getDataSourcesManager().getMainDataSource(); - D dto = get(dataSource, id); - return dto; - } - - public abstract D get(ObserveSwingDataSource dataSource, String id); - - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/validation/ValidationModelMode.java b/observe-application-swing/src/main/java/fr/ird/observe/validation/ValidationModelMode.java deleted file mode 100644 index 0926594..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/validation/ValidationModelMode.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.validation; - -import static org.nuiton.i18n.I18n.n; - -/** - * Pour caractériser le type de modele de validation a utiliser. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.3 - */ -public enum ValidationModelMode { - - /** validation du referentiel */ - REFERENTIEL( - n("observe.actions.validate.model.type.referentiel"), - n("observe.actions.validate.model.type.referentiel.description"), - true, false), - - /** validation de donnees observer */ - DATA( - n("observe.actions.validate.model.type.data"), - n("observe.actions.validate.model.type.data.description"), - false, true), - - /** validation du referentiel et de donnees observer */ - ALL( - n("observe.actions.validate.model.type.all"), - n("observe.actions.validate.model.type.all.description"), - true, false); - - private final String label; - - private final String description; - - private final boolean referential; - - private final boolean data; - - ValidationModelMode(String label, - String description, - boolean referential, - boolean data) { - this.label = label; - this.description = description; - this.referential = referential; - this.data = data; - } - - public String getLabel() { - return label; - } - - public String getDescription() { - return description; - } - - public boolean isReferential() { - return referential; - } - - public boolean isData() { - return data; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/validation/ValidationService.java b/observe-application-swing/src/main/java/fr/ird/observe/validation/ValidationService.java deleted file mode 100644 index fc6f35c..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/validation/ValidationService.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.validation; - -import fr.ird.observe.services.dto.AbstractObserveDto; -import fr.ird.observe.services.dto.IdDto; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; - -import org.nuiton.validator.NuitonValidatorScope; -import org.nuiton.validator.bean.simple.SimpleBeanValidator; - -import java.util.Set; - -/** - * Contrat du service de validation des données. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 1.3 - */ -public class ValidationService { - - /** Logger */ - private static final Log log = - LogFactory.getLog(ValidationService.class); - - /** - * Obtenir le validateur d'un type objet - * - * @param context le lastName du context de validation - * @param scopes les scopes autorisés - * @param klass type de l'objet à valider - * @param <B> type de l'objet à valider - * @return le validateur trouvé ou {@code null} - */ - public <B> SimpleBeanValidator<B> getValidator(String context, - NuitonValidatorScope[] scopes, - Class<B> klass) { - - SimpleBeanValidator<B> valitator = SimpleBeanValidator.newValidator( - klass, - context, - scopes - ); - - Set<NuitonValidatorScope> resultScopes = valitator.getEffectiveScopes(); - if (resultScopes.isEmpty()) { - valitator = null; - if (log.isDebugEnabled()) { - log.debug(klass + " : validator skip (no scopes detected)"); - } - } else { - if (log.isDebugEnabled()) { - log.debug(klass + " : keep validator " + valitator); - } - } - return valitator; - } - - /** - * Obtenir le dictionnaire des validateurs pour les types d'entités donnés. - * - * @param contextName le lastName du context de validation - * @param scopes les scopes autorisés - * @param beanclass types des entités - * @return le dictionnaire des validateurs par type d'entité. - */ - public ValidatorsMap getValidators( - String contextName, - NuitonValidatorScope[] scopes, - Class<?>... beanclass) { - ValidatorsMap map = detectValidators( - contextName, - scopes, - beanclass - ); - return map; - } - - /** - * Obtenir le dictionnaire des validateurs pour les entités donnés. - * - * <b>Note:</b> On effectue un parcours des entités pour connaitre les types - * d'objets à valider, il faut donc des les collections des entités soient - * toutes chargées (ou l'objet attaché à une transaction...). - * - * @param contextName le lastName du context de validation - * @param scopes les scopes autorisés - * @param dtos les entités - * @return le dictionnaire des validateurs par type d'entité. - */ - public ValidatorsMap getValidators( - String contextName, - NuitonValidatorScope[] scopes, - IdDto... dtos) { - - //FIXME - Set<Class<? extends AbstractObserveDto>> types = null; -// try { -// types = TopiaEntityHelper.detectTypes( -// ObserveEntityEnum.values(), -// entities -// ); -// } catch (TopiaException e) { -// throw new IllegalArgumentException( -// "could not obtains types for reason " + e.getMessage(), e); -// } - - ValidatorsMap result = detectValidators( - contextName, - scopes, - types.toArray(new Class<?>[types.size()]) - ); - return result; - } - - @SuppressWarnings("unchecked") - public <T> ValidatorsMap detectValidators( - String context, - NuitonValidatorScope[] scopes, - Class<?>... types) { - - ValidatorsMap result = new ValidatorsMap(); - - for (Class<?> c : types) { - // on cherche le validateur - SimpleBeanValidator<T> validator = (SimpleBeanValidator<T>) - getValidator(context, scopes, c); - if (validator != null) { - // on enregistre le validateur - result.put(c, validator); - } - } - return result; - } -} diff --git a/observe-application-swing/src/main/java/fr/ird/observe/validation/ValidatorsMap.java b/observe-application-swing/src/main/java/fr/ird/observe/validation/ValidatorsMap.java deleted file mode 100644 index 54958f5..0000000 --- a/observe-application-swing/src/main/java/fr/ird/observe/validation/ValidatorsMap.java +++ /dev/null @@ -1,121 +0,0 @@ -/* - * #%L - * ObServe :: Business - * %% - * Copyright (C) 2008 - 2010 CodeLutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ -package fr.ird.observe.validation; - -import org.nuiton.validator.NuitonValidatorScope; -import org.nuiton.validator.bean.simple.SimpleBeanValidator; - -import java.util.Collection; -import java.util.EnumSet; -import java.util.HashMap; -import java.util.Map; -import java.util.Set; - -/** - * Un dictionnaire de validateurs ordonnees par le type de leur bean. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 2.1 - */ -public class ValidatorsMap implements Map<Class<?>, SimpleBeanValidator<?>> { - - protected final Map<Class<?>, SimpleBeanValidator<?>> delegate; - - public ValidatorsMap() { - delegate = new HashMap<>(); - } - - public NuitonValidatorScope[] getScopes() { - EnumSet<NuitonValidatorScope> result = - EnumSet.noneOf(NuitonValidatorScope.class); - for (SimpleBeanValidator<?> b : values()) { - result.addAll(b.getScopes()); - } - return result.toArray(new NuitonValidatorScope[result.size()]); - } - - public <X> SimpleBeanValidator<X> getValidator(Class<X> klass) { - SimpleBeanValidator<X> beanValidator = (SimpleBeanValidator<X>) get(klass); - return beanValidator; - } - - @Override - public int size() { - return delegate.size(); - } - - @Override - public boolean isEmpty() { - return delegate.isEmpty(); - } - - @Override - public boolean containsKey(Object key) { - return delegate.containsKey(key); - } - - @Override - public boolean containsValue(Object value) { - return delegate.containsValue(value); - } - - @Override - public SimpleBeanValidator<?> get(Object key) { - return delegate.get(key); - } - - @Override - public SimpleBeanValidator<?> put(Class<?> key, SimpleBeanValidator<?> value) { - return delegate.put(key, value); - } - - @Override - public SimpleBeanValidator<?> remove(Object key) { - return delegate.remove(key); - } - - @Override - public void putAll(Map<? extends Class<?>, ? extends SimpleBeanValidator<?>> m) { - delegate.putAll(m); - } - - @Override - public void clear() { - delegate.clear(); - } - - @Override - public Set<Class<?>> keySet() { - return delegate.keySet(); - } - - @Override - public Collection<SimpleBeanValidator<?>> values() { - return delegate.values(); - } - - @Override - public Set<Entry<Class<?>, SimpleBeanValidator<?>>> entrySet() { - return delegate.entrySet(); - } - -} diff --git a/observe-application-swing/src/main/resources/META-INF/services/org.nuiton.config.ApplicationConfigProvider b/observe-application-swing/src/main/resources/META-INF/services/org.nuiton.config.ApplicationConfigProvider index b6c2e86..d862cac 100644 --- a/observe-application-swing/src/main/resources/META-INF/services/org.nuiton.config.ApplicationConfigProvider +++ b/observe-application-swing/src/main/resources/META-INF/services/org.nuiton.config.ApplicationConfigProvider @@ -1 +1 @@ -fr.ird.observe.configuration.ObserveSwingApplicationConfigProvider \ No newline at end of file +fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfigProvider \ No newline at end of file diff --git a/observe-application-swing/src/main/resources/log4j.properties b/observe-application-swing/src/main/resources/log4j.properties index 28f9047..d61125b 100644 --- a/observe-application-swing/src/main/resources/log4j.properties +++ b/observe-application-swing/src/main/resources/log4j.properties @@ -39,13 +39,13 @@ log4j.appender.file.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss} %5p [%t] ( # levels log4j.logger.fr.ird.observe=INFO -log4j.logger.fr.ird.observe.db.impl.DataContext=WARN -log4j.logger.fr.ird.observe.db.impl.DataService=WARN +log4j.logger.fr.ird.observe.application.swing.db.impl.DataContext=WARN +log4j.logger.fr.ird.observe.application.swing.db.impl.DataService=WARN log4j.logger.fr.ird.observe.entities.Entities=DEBUG -log4j.logger.fr.ird.observe.validation.field=WARN +log4j.logger.fr.ird.observe.application.swing.validation.field=WARN -log4j.logger.fr.ird.observe.ui.tree=INFO -log4j.logger.fr.ird.observe.ui.util.decorator=ERROR +log4j.logger.fr.ird.observe.application.swing.ui.tree=INFO +log4j.logger.fr.ird.observe.application.swing.ui.util.decorator=ERROR log4j.logger.org.nuiton.config=INFO log4j.logger.org.nuiton.topia.migration=INFO @@ -53,4 +53,4 @@ log4j.logger.org.nuiton.topia.migration=INFO log4j.logger.jaxx.runtime.validator.swing.SwingValidator=ERROR -log4j.logger.fr.ird.observe.ui.util.tripMap.TripMapHandler=DEBUG +log4j.logger.fr.ird.observe.application.swing.ui.util.tripMap.TripMapHandler=DEBUG diff --git a/observe-application-swing/src/main/resources/observe-log4j.properties b/observe-application-swing/src/main/resources/observe-log4j.properties index 61ae1eb..7906211 100644 --- a/observe-application-swing/src/main/resources/observe-log4j.properties +++ b/observe-application-swing/src/main/resources/observe-log4j.properties @@ -39,13 +39,13 @@ log4j.appender.file.layout.ConversionPattern=%d{dd MMM yyyy HH:mm:ss} %5p [%t] ( # levels log4j.logger.fr.ird.observe=INFO -log4j.logger.fr.ird.observe.db.impl.DataContext=WARN -log4j.logger.fr.ird.observe.db.impl.DataService=WARN +log4j.logger.fr.ird.observe.application.swing.db.impl.DataContext=WARN +log4j.logger.fr.ird.observe.application.swing.db.impl.DataService=WARN log4j.logger.fr.ird.observe.entities.Entities=DEBUG -log4j.logger.fr.ird.observe.validation.field=WARN +log4j.logger.fr.ird.observe.application.swing.validation.field=WARN -log4j.logger.fr.ird.observe.ui.tree=INFO -log4j.logger.fr.ird.observe.ui.util.decorator=ERROR +log4j.logger.fr.ird.observe.application.swing.ui.tree=INFO +log4j.logger.fr.ird.observe.application.swing.ui.util.decorator=ERROR log4j.logger.org.nuiton.topia.migration=INFO log4j.logger.org.nuiton.config=INFO @@ -53,4 +53,4 @@ log4j.logger.org.nuiton.config=INFO log4j.logger.jaxx.runtime.validator.swing.SwingValidator=ERROR -log4j.logger.fr.ird.observe.ui.util.tripMap.TripMapHandler=DEBUG +log4j.logger.fr.ird.observe.application.swing.ui.util.tripMap.TripMapHandler=DEBUG diff --git a/observe-application-swing/src/test/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionValidatorServiceTest.java b/observe-application-swing/src/test/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionValidatorServiceTest.java new file mode 100644 index 0000000..147c7b5 --- /dev/null +++ b/observe-application-swing/src/test/java/fr/ird/observe/application/swing/ui/content/impl/longline/LonglineDetailCompositionValidatorServiceTest.java @@ -0,0 +1,215 @@ +package fr.ird.observe.application.swing.ui.content.impl.longline; + +/* + * #%L + * ObServe :: Swing + * %% + * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit + * %% + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as + * published by the Free Software Foundation, either version 3 of the + * License, or (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public + * License along with this program. If not, see + * <http://www.gnu.org/licenses/gpl-3.0.html>. + * #L% + */ + +import com.google.common.collect.Iterables; +import fr.ird.observe.application.swing.ObserveSwingApplicationContext; +import fr.ird.observe.application.swing.configuration.ObserveSwingApplicationConfig; +import fr.ird.observe.services.dto.longline.BasketDto; +import fr.ird.observe.services.dto.longline.BranchlineDto; +import fr.ird.observe.services.dto.longline.SectionDto; +import jaxx.runtime.validator.swing.SwingValidator; +import jaxx.runtime.validator.swing.SwingValidatorMessage; +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.nuiton.i18n.I18n; +import org.nuiton.i18n.init.ClassPathI18nInitializer; +import org.nuiton.validator.NuitonValidatorScope; +import org.nuiton.validator.bean.simple.SimpleBeanValidatorMessage; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Locale; + +/** + * Created on 3/18/15. + * + * @author Tony Chemit - chemit@codelutin.com + * @since 3.15 + */ +public class LonglineDetailCompositionValidatorServiceTest { + + /** Logger. */ + private static final Log log = LogFactory.getLog(LonglineDetailCompositionValidatorServiceTest.class); + + protected LonglineDetailCompositionValidatorService service; + + @Before + public void setUp() { + + if (ObserveSwingApplicationContext.isInit()) { + + ObserveSwingApplicationContext.get().close(); + } + + ObserveSwingApplicationContext applicationContext = new ObserveSwingApplicationContext(new ObserveSwingApplicationConfig()); + + SwingValidator<SectionDto> sectionValidator = new SwingValidator<>(SectionDto.class, "ui-update-table", NuitonValidatorScope.values()); + SwingValidator<BasketDto> basketValidator = new SwingValidator<>(BasketDto.class, "ui-update-table", NuitonValidatorScope.values()); + SwingValidator<BranchlineDto> branchlineValidator = new SwingValidator<>(BranchlineDto.class, "ui-update-table", NuitonValidatorScope.values()); + + service = new LonglineDetailCompositionValidatorService( + sectionValidator, + basketValidator, + branchlineValidator, + Collections.emptyMap(), + applicationContext.getDecoratorService()); + + I18n.init(new ClassPathI18nInitializer(), Locale.FRANCE); + + } + + @Test + public void testValidateSections() { + + List<SectionDto> sections = new ArrayList<>(); + { + SectionDto section = new SectionDto(); + section.setId("0"); + sections.add(section); + } + { + SectionDto section = new SectionDto(); + section.setId("1"); + sections.add(section); + } + + { + // 2 sections, without settingIdentifier + List<SwingValidatorMessage> messages = service.validateSections(sections); + assertMessages(messages, 2); + } + + { + // 2 sections, with settingIdentifier + sections.get(0).setSettingIdentifier(1); + sections.get(1).setSettingIdentifier(2); + + List<SwingValidatorMessage> messages = service.validateSections(sections); + assertMessages(messages, 0); + + } + + { // 2 sections with baskets without settingIdentifier + { + BasketDto basket = new BasketDto(); + basket.setId("00"); + sections.get(0).addBasket(basket); + } + { + BasketDto basket = new BasketDto(); + basket.setId("01"); + sections.get(0).addBasket(basket); + } + { + BasketDto basket = new BasketDto(); + basket.setId("10"); + sections.get(1).addBasket(basket); + } + { + BasketDto basket = new BasketDto(); + basket.setId("11"); + sections.get(1).addBasket(basket); + } + List<SwingValidatorMessage> messages = service.validateSections(sections); + assertMessages(messages, 4); + } + + { // 2 sections with baskets with settingIdentifier + + Iterables.get(sections.get(0).getBasket(), 0).setSettingIdentifier(1); + Iterables.get(sections.get(0).getBasket(), 1).setSettingIdentifier(2); + Iterables.get(sections.get(1).getBasket(), 0).setSettingIdentifier(1); + Iterables.get(sections.get(1).getBasket(), 1).setSettingIdentifier(2); + + List<SwingValidatorMessage> messages = service.validateSections(sections); + assertMessages(messages, 0); + + } + + { // Section 1 - Basket 1 mistmatch floatline1Length with Section 1 - Basket 2 + + Iterables.get(sections.get(0).getBasket(), 0).setFloatline1Length(1f); + Iterables.get(sections.get(0).getBasket(), 0).setFloatline2Length(2f); + Iterables.get(sections.get(0).getBasket(), 1).setFloatline1Length(1f); // should be 2 + Iterables.get(sections.get(0).getBasket(), 1).setFloatline2Length(6f); + Iterables.get(sections.get(1).getBasket(), 0).setFloatline1Length(6f); + Iterables.get(sections.get(1).getBasket(), 0).setFloatline2Length(11f); + Iterables.get(sections.get(1).getBasket(), 1).setFloatline1Length(11f); + Iterables.get(sections.get(1).getBasket(), 1).setFloatline2Length(12f); + + List<SwingValidatorMessage> messages = service.validateSections(sections); + assertMessages(messages, 1); + + } + + { // OK d'ont check if last floatline has same length of first floatline for next section + + Iterables.get(sections.get(0).getBasket(), 0).setFloatline1Length(1f); + Iterables.get(sections.get(0).getBasket(), 0).setFloatline2Length(2f); + Iterables.get(sections.get(0).getBasket(), 1).setFloatline1Length(2f); + Iterables.get(sections.get(0).getBasket(), 1).setFloatline2Length(6f); + Iterables.get(sections.get(1).getBasket(), 0).setFloatline1Length(10f); // Should be 6 + Iterables.get(sections.get(1).getBasket(), 0).setFloatline2Length(11f); + Iterables.get(sections.get(1).getBasket(), 1).setFloatline1Length(11f); + Iterables.get(sections.get(1).getBasket(), 1).setFloatline2Length(12f); + + List<SwingValidatorMessage> messages = service.validateSections(sections); + assertMessages(messages, 0); + + } + + { // Ok + + Iterables.get(sections.get(0).getBasket(), 0).setFloatline1Length(1f); + Iterables.get(sections.get(0).getBasket(), 0).setFloatline2Length(2f); + Iterables.get(sections.get(0).getBasket(), 1).setFloatline1Length(2f); + Iterables.get(sections.get(0).getBasket(), 1).setFloatline2Length(10f); + Iterables.get(sections.get(1).getBasket(), 0).setFloatline1Length(10f); + Iterables.get(sections.get(1).getBasket(), 0).setFloatline2Length(11f); + Iterables.get(sections.get(1).getBasket(), 1).setFloatline1Length(11f); + Iterables.get(sections.get(1).getBasket(), 1).setFloatline2Length(12f); + + List<SwingValidatorMessage> messages = service.validateSections(sections); + assertMessages(messages, 0); + + } + + } + + protected void assertMessages(List<SwingValidatorMessage> messages, int expectedNbMessages) { + + StringBuilder builder = new StringBuilder(); + for (SimpleBeanValidatorMessage message : messages) { + builder.append("\n").append(message.getScope()).append(" - ").append(message.getField()).append(" - ").append(message.getI18nError(message.getMessage())); + } + if (log.isInfoEnabled()) { + log.info(builder.toString()); + } + Assert.assertEquals("Should have found " + expectedNbMessages + " messages, but found " + messages.size(), expectedNbMessages, messages.size()); + } +} \ No newline at end of file diff --git a/observe-application-swing/src/test/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionValidatorServiceTest.java b/observe-application-swing/src/test/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionValidatorServiceTest.java deleted file mode 100644 index 1acf95c..0000000 --- a/observe-application-swing/src/test/java/fr/ird/observe/ui/content/impl/longline/LonglineDetailCompositionValidatorServiceTest.java +++ /dev/null @@ -1,215 +0,0 @@ -package fr.ird.observe.ui.content.impl.longline; - -/* - * #%L - * ObServe :: Swing - * %% - * Copyright (C) 2008 - 2015 IRD, Codelutin, Tony Chemit - * %% - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as - * published by the Free Software Foundation, either version 3 of the - * License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public - * License along with this program. If not, see - * <http://www.gnu.org/licenses/gpl-3.0.html>. - * #L% - */ - -import com.google.common.collect.Iterables; -import fr.ird.observe.ObserveSwingApplicationContext; -import fr.ird.observe.configuration.ObserveSwingApplicationConfig; -import fr.ird.observe.services.dto.longline.BasketDto; -import fr.ird.observe.services.dto.longline.BranchlineDto; -import fr.ird.observe.services.dto.longline.SectionDto; -import jaxx.runtime.validator.swing.SwingValidator; -import jaxx.runtime.validator.swing.SwingValidatorMessage; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.nuiton.i18n.I18n; -import org.nuiton.i18n.init.ClassPathI18nInitializer; -import org.nuiton.validator.NuitonValidatorScope; -import org.nuiton.validator.bean.simple.SimpleBeanValidatorMessage; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Locale; - -/** - * Created on 3/18/15. - * - * @author Tony Chemit - chemit@codelutin.com - * @since 3.15 - */ -public class LonglineDetailCompositionValidatorServiceTest { - - /** Logger. */ - private static final Log log = LogFactory.getLog(LonglineDetailCompositionValidatorServiceTest.class); - - protected LonglineDetailCompositionValidatorService service; - - @Before - public void setUp() { - - if (ObserveSwingApplicationContext.isInit()) { - - ObserveSwingApplicationContext.get().close(); - } - - ObserveSwingApplicationContext applicationContext = new ObserveSwingApplicationContext(new ObserveSwingApplicationConfig()); - - SwingValidator<SectionDto> sectionValidator = new SwingValidator<>(SectionDto.class, "ui-update-table", NuitonValidatorScope.values()); - SwingValidator<BasketDto> basketValidator = new SwingValidator<>(BasketDto.class, "ui-update-table", NuitonValidatorScope.values()); - SwingValidator<BranchlineDto> branchlineValidator = new SwingValidator<>(BranchlineDto.class, "ui-update-table", NuitonValidatorScope.values()); - - service = new LonglineDetailCompositionValidatorService( - sectionValidator, - basketValidator, - branchlineValidator, - Collections.emptyMap(), - applicationContext.getDecoratorService()); - - I18n.init(new ClassPathI18nInitializer(), Locale.FRANCE); - - } - - @Test - public void testValidateSections() { - - List<SectionDto> sections = new ArrayList<>(); - { - SectionDto section = new SectionDto(); - section.setId("0"); - sections.add(section); - } - { - SectionDto section = new SectionDto(); - section.setId("1"); - sections.add(section); - } - - { - // 2 sections, without settingIdentifier - List<SwingValidatorMessage> messages = service.validateSections(sections); - assertMessages(messages, 2); - } - - { - // 2 sections, with settingIdentifier - sections.get(0).setSettingIdentifier(1); - sections.get(1).setSettingIdentifier(2); - - List<SwingValidatorMessage> messages = service.validateSections(sections); - assertMessages(messages, 0); - - } - - { // 2 sections with baskets without settingIdentifier - { - BasketDto basket = new BasketDto(); - basket.setId("00"); - sections.get(0).addBasket(basket); - } - { - BasketDto basket = new BasketDto(); - basket.setId("01"); - sections.get(0).addBasket(basket); - } - { - BasketDto basket = new BasketDto(); - basket.setId("10"); - sections.get(1).addBasket(basket); - } - { - BasketDto basket = new BasketDto(); - basket.setId("11"); - sections.get(1).addBasket(basket); - } - List<SwingValidatorMessage> messages = service.validateSections(sections); - assertMessages(messages, 4); - } - - { // 2 sections with baskets with settingIdentifier - - Iterables.get(sections.get(0).getBasket(), 0).setSettingIdentifier(1); - Iterables.get(sections.get(0).getBasket(), 1).setSettingIdentifier(2); - Iterables.get(sections.get(1).getBasket(), 0).setSettingIdentifier(1); - Iterables.get(sections.get(1).getBasket(), 1).setSettingIdentifier(2); - - List<SwingValidatorMessage> messages = service.validateSections(sections); - assertMessages(messages, 0); - - } - - { // Section 1 - Basket 1 mistmatch floatline1Length with Section 1 - Basket 2 - - Iterables.get(sections.get(0).getBasket(), 0).setFloatline1Length(1f); - Iterables.get(sections.get(0).getBasket(), 0).setFloatline2Length(2f); - Iterables.get(sections.get(0).getBasket(), 1).setFloatline1Length(1f); // should be 2 - Iterables.get(sections.get(0).getBasket(), 1).setFloatline2Length(6f); - Iterables.get(sections.get(1).getBasket(), 0).setFloatline1Length(6f); - Iterables.get(sections.get(1).getBasket(), 0).setFloatline2Length(11f); - Iterables.get(sections.get(1).getBasket(), 1).setFloatline1Length(11f); - Iterables.get(sections.get(1).getBasket(), 1).setFloatline2Length(12f); - - List<SwingValidatorMessage> messages = service.validateSections(sections); - assertMessages(messages, 1); - - } - - { // OK d'ont check if last floatline has same length of first floatline for next section - - Iterables.get(sections.get(0).getBasket(), 0).setFloatline1Length(1f); - Iterables.get(sections.get(0).getBasket(), 0).setFloatline2Length(2f); - Iterables.get(sections.get(0).getBasket(), 1).setFloatline1Length(2f); - Iterables.get(sections.get(0).getBasket(), 1).setFloatline2Length(6f); - Iterables.get(sections.get(1).getBasket(), 0).setFloatline1Length(10f); // Should be 6 - Iterables.get(sections.get(1).getBasket(), 0).setFloatline2Length(11f); - Iterables.get(sections.get(1).getBasket(), 1).setFloatline1Length(11f); - Iterables.get(sections.get(1).getBasket(), 1).setFloatline2Length(12f); - - List<SwingValidatorMessage> messages = service.validateSections(sections); - assertMessages(messages, 0); - - } - - { // Ok - - Iterables.get(sections.get(0).getBasket(), 0).setFloatline1Length(1f); - Iterables.get(sections.get(0).getBasket(), 0).setFloatline2Length(2f); - Iterables.get(sections.get(0).getBasket(), 1).setFloatline1Length(2f); - Iterables.get(sections.get(0).getBasket(), 1).setFloatline2Length(10f); - Iterables.get(sections.get(1).getBasket(), 0).setFloatline1Length(10f); - Iterables.get(sections.get(1).getBasket(), 0).setFloatline2Length(11f); - Iterables.get(sections.get(1).getBasket(), 1).setFloatline1Length(11f); - Iterables.get(sections.get(1).getBasket(), 1).setFloatline2Length(12f); - - List<SwingValidatorMessage> messages = service.validateSections(sections); - assertMessages(messages, 0); - - } - - } - - protected void assertMessages(List<SwingValidatorMessage> messages, int expectedNbMessages) { - - StringBuilder builder = new StringBuilder(); - for (SimpleBeanValidatorMessage message : messages) { - builder.append("\n").append(message.getScope()).append(" - ").append(message.getField()).append(" - ").append(message.getI18nError(message.getMessage())); - } - if (log.isInfoEnabled()) { - log.info(builder.toString()); - } - Assert.assertEquals("Should have found " + expectedNbMessages + " messages, but found " + messages.size(), expectedNbMessages, messages.size()); - } -} \ No newline at end of file -- To stop receiving notification emails like this one, please contact codelutin.com SCM administrator <admin+scm@codelutin.com>.
participants (1)
-
codelutin.com scm